Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion frontend/src/components/chat/CreateGroupDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const props = defineProps({
show: { type: Boolean, default: false },
users: { type: Array, default: () => [] },
form: { type: Object, required: true },
submitting: { type: Boolean, default: false }
submitting: { type: Boolean, default: false },
error: { type: String, default: '' }
});

const emit = defineEmits(['close', 'toggle-member', 'submit']);
Expand Down Expand Up @@ -71,6 +72,8 @@ useOverlayLifecycle({
</div>
</div>

<p v-if="error" class="room-dialog__error" role="alert">{{ error }}</p>

<div class="room-dialog__actions">
<button type="button" class="room-dialog__secondary" @click="emit('close')">{{ t('common.cancel') }}</button>
<button
Expand Down Expand Up @@ -128,6 +131,7 @@ useOverlayLifecycle({
.room-dialog__member { display: flex; align-items: center; gap: 8px; min-height: 44px; padding: 8px 12px; border: 1px solid #e8ecf0; border-radius: 20px; background: #fff; cursor: pointer; touch-action: manipulation; }
.room-dialog__member--selected { border-color: #008069; background: #e8f0fe; }
.room-dialog__actions { display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px; }
.room-dialog__error { margin: 16px 0 0; color: #b42318; font-size: 13px; overflow-wrap: anywhere; }
.room-dialog__secondary, .room-dialog__primary { min-height: 44px; padding: 10px 20px; border-radius: 8px; cursor: pointer; touch-action: manipulation; }
.room-dialog__secondary { border: 1px solid #e8ecf0; background: #fff; }
.room-dialog__primary { border: 0; background: #008069; color: #fff; }
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/composables/useRoomManagement.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,12 @@ export function useRoomManagement({
}

function openCreateGroup() {
error.value = "";
showCreateGroup.value = true;
}

function closeCreateGroup() {
error.value = "";
showCreateGroup.value = false;
createGroupForm.name = "";
createGroupForm.kind = "private";
Expand All @@ -71,7 +73,7 @@ export function useRoomManagement({
}

async function createGroup() {
if (!createGroupForm.name.trim()) {
if (!createGroupForm.name.trim() || creatingGroup.value) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/locales/en-US.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export default {
'group.changeAvatar': 'Change avatar',
'group.delete': 'Delete group',
'group.removeMemberConfirm': 'Remove {name} from this group?',
'group.deleteConfirm': 'Delete group {name}?',
'group.deleteConfirm': 'Permanently delete group {name} and all its messages? This cannot be undone.',
'group.enterName': 'Please enter a group name.',
'publicGroups.notJoined': 'Groups you have not joined',
'publicGroups.fallback': 'G',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/locales/zh-CN.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export default {
'group.changeAvatar': '更换头像',
'group.delete': '删除群组',
'group.removeMemberConfirm': '确认将 {name} 移出群组吗?',
'group.deleteConfirm': '确认删除群组 {name} 吗?',
'group.deleteConfirm': '确认永久删除群组 {name} 及其全部消息吗?此操作无法撤销。',
'group.enterName': '请输入群组名称。',
'publicGroups.notJoined': '未加入群组',
'publicGroups.fallback': '群',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/pages/ChatPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,7 @@ onBeforeUnmount(() => {
:users="users"
:form="createGroupForm"
:submitting="creatingGroup"
:error="error"
@close="closeCreateGroup"
@toggle-member="toggleCreateGroupMember"
@submit="createGroup"
Expand Down
162 changes: 162 additions & 0 deletions test/channel-deletion.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { Hono } from "hono";
import initSqlJs from "sql.js";

import { registerChannelRoutes } from "../worker/src/api/channels.js";
import { hardDeleteChannel } from "../worker/src/data/channel-deletion.ts";
import { ApiError } from "../worker/src/errors.js";
import { runScheduledGc } from "../worker/src/gc.js";
import { createD1Adapter } from "./support/d1.js";

const SQL = await initSqlJs();

function createHarness(isAdmin = false) {
const database = new SQL.Database();
database.exec(readFileSync(new URL("../worker/schema.sql", import.meta.url), "utf8"));
database.run(
`INSERT INTO users (id, username, display_name, password_hash, password_salt)
VALUES (1, 'owner', 'Owner', 'hash', 'salt'), (2, 'member', 'Member', 'hash', 'salt')`,
);
const deletedFiles = [];
const env = {
DB: createD1Adapter(database),
FILES: { async delete(key) { deletedFiles.push(key); } },
};
const app = new Hono();
app.use("*", async (c, next) => {
c.set("session", { userId: 1, displayName: "Owner", isAdmin });
await next();
});
app.onError((error, c) => c.json(
{ error: error instanceof ApiError ? error.message : "服务器开小差了" },
error instanceof ApiError ? error.status : 500,
));
registerChannelRoutes(app);
return {
database, env, deletedFiles,
async request(path, method, payload) {
return app.fetch(new Request(`https://example.com${path}`, {
method,
headers: { "content-type": "application/json" },
...(payload ? { body: JSON.stringify(payload) } : {}),
}), env);
},
};
}

function count(database, table, where = "1") {
return database.exec(`SELECT COUNT(*) FROM ${table} WHERE ${where}`)[0].values[0][0];
}

async function createGroup(harness, name = "重建群", kind = "private") {
const response = await harness.request("/api/channels", "POST", {
name, kind, memberUserIds: [2],
});
assert.equal(response.status, 200);
return (await response.json()).channel.id;
}

function addRelatedRecords(database, id) {
database.run("UPDATE channels SET avatar_key = 'group-avatar' WHERE id = ?", [id]);
database.run(
`INSERT INTO messages (channel_id, sender_id, content, attachment_key)
VALUES (?, 1, 'private history', 'group-file')`, [id],
);
const messageId = database.exec("SELECT last_insert_rowid()")[0].values[0][0];
database.run("INSERT INTO message_reads (channel_id, user_id, last_read_message_id) VALUES (?, 2, ?)", [id, messageId]);
database.run("INSERT INTO channel_pins (channel_id, message_id, pinned_by) VALUES (?, ?, 1)", [id, messageId]);
database.run("INSERT INTO message_event_compaction (channel_id, compacted_through) VALUES (?, 1)", [id]);
database.run("INSERT INTO telegram_mappings (channel_id, telegram_chat_id) VALUES (?, '-123')", [id]);
database.run(
`INSERT INTO uploaded_files (object_key, owner_user_id)
VALUES ('group-avatar', 1), ('group-file', 1)`,
);
}

for (const kind of ["public", "private"]) {
for (const admin of [false, true]) {
test(`${kind} 群组经${admin ? "管理员" : "群主"}硬删除后可同名创建且没有旧群数据`, async () => {
const harness = createHarness(admin);
const { database, env } = harness;
const id = await createGroup(harness, "重建群", kind);
addRelatedRecords(database, id);
const duplicate = await harness.request("/api/channels", "POST", { name: "重建群", kind });
assert.equal(duplicate.status, 400);
assert.deepEqual(await duplicate.json(), { error: "群组名称已存在" });

const path = admin ? `/api/admin/channels/${id}` : `/api/channels/${id}`;
assert.equal((await harness.request(path, "DELETE")).status, 200);
assert.equal(count(database, "channels", `id = ${id}`), 0);
for (const table of ["messages", "channel_members", "message_reads", "channel_pins", "message_events", "message_event_compaction", "telegram_mappings"]) {
assert.equal(count(database, table, `channel_id = ${id}`), 0, table);
}
assert.equal(count(database, "pending_r2_delete"), 2);
assert.deepEqual(database.exec("PRAGMA foreign_key_check"), []);
const recreated = await createGroup(harness, "重建群", kind);
assert.ok(recreated > id);
assert.equal(count(database, "messages", `channel_id = ${recreated}`), 0);
assert.equal(count(database, "channel_members", `channel_id = ${recreated}`), 2);
assert.equal((await harness.request(`/api/channels/${id}/members`, "GET")).status, 404);
assert.equal((await hardDeleteChannel(env.DB, id)).channelsDeleted, 0);
});
}
}

test("硬删除事务失败会同时回滚文件队列、消息及成员", async () => {
const harness = createHarness();
const id = await createGroup(harness);
addRelatedRecords(harness.database, id);
harness.database.run(
`CREATE TRIGGER simulate_delete_failure BEFORE DELETE ON channels
BEGIN SELECT RAISE(ABORT, 'test failure'); END`,
);
await assert.rejects(hardDeleteChannel(harness.env.DB, id), /test failure/);
assert.equal(count(harness.database, "channels", `id = ${id}`), 1);
assert.equal(count(harness.database, "messages", `channel_id = ${id}`), 1);
assert.equal(count(harness.database, "channel_members", `channel_id = ${id}`), 2);
assert.equal(count(harness.database, "message_reads", `channel_id = ${id}`), 1);
assert.equal(count(harness.database, "pending_r2_delete"), 0);
assert.deepEqual(harness.database.exec("PRAGMA foreign_key_check"), []);
});

test("删除入口拒绝普通成员,底层不会删除 general 或私聊", async () => {
const harness = createHarness();
const id = await createGroup(harness);
harness.database.run("UPDATE channel_members SET role = 'member' WHERE channel_id = ?", [id]);
assert.equal((await harness.request(`/api/channels/${id}`, "DELETE")).status, 403);
assert.equal(count(harness.database, "channels", `id = ${id}`), 1);
harness.database.run("INSERT INTO channels (name, kind, dm_key) VALUES ('dm:1:2', 'dm', '1:2')");
const dmId = harness.database.exec("SELECT last_insert_rowid()")[0].values[0][0];
for (const channelId of [1, dmId]) {
assert.equal((await hardDeleteChannel(harness.env.DB, channelId)).channelsDeleted, 0);
assert.equal(count(harness.database, "channels", `id = ${channelId}`), 1);
}
});

test("GC 复用硬删除清理历史群组,文件失败重试且保留共享引用", async () => {
const harness = createHarness();
const { database, env, deletedFiles } = harness;
const id = await createGroup(harness);
addRelatedRecords(database, id);
database.run("UPDATE channels SET deleted_at = datetime('now', '-61 day') WHERE id = ?", [id]);
database.run("UPDATE users SET avatar_key = 'group-avatar' WHERE id = 2");
const deleteFile = env.FILES.delete;
env.FILES.delete = async () => { throw new Error("R2 unavailable"); };
const summary = await runScheduledGc(env);
assert.equal(summary.channelsDeleted, 1);
assert.equal(count(database, "channels", `id = ${id}`), 0);
assert.equal(count(database, "message_reads", `channel_id = ${id}`), 0);
assert.equal(count(database, "pending_r2_delete"), 1);
assert.equal(count(database, "pending_r2_delete", "object_key = 'group-file' AND retry_count = 1"), 1);
assert.equal(count(database, "uploaded_files"), 2);
env.FILES.delete = deleteFile;
database.run("UPDATE pending_r2_delete SET next_retry_at = CURRENT_TIMESTAMP");
await runScheduledGc(env);
assert.deepEqual(deletedFiles, ["group-file"]);
assert.equal(count(database, "pending_r2_delete"), 0);
assert.equal(count(database, "uploaded_files", "object_key = 'group-file'"), 0);
assert.equal(count(database, "uploaded_files", "object_key = 'group-avatar'"), 1);
assert.deepEqual(database.exec("PRAGMA foreign_key_check"), []);
});
36 changes: 36 additions & 0 deletions test/room-management.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,42 @@ test("公开群组创建会保留类型并允许不预先邀请成员", async ()
]);
});

test("创建失败保留表单与错误提示,关闭或重新打开时清除旧错误", async () => {
const { management, error } = createHarness({
roomApi: { async createGroup() { throw new Error("群组名称已存在"); } },
});
error.value = "旧错误";
management.creation.open();
assert.equal(error.value, "");
management.creation.form.name = "Team";
await management.creation.submit();
assert.equal(management.creation.show.value, true);
assert.equal(management.creation.form.name, "Team");
assert.equal(management.creation.submitting.value, false);
assert.equal(error.value, "群组名称已存在");
management.creation.close();
assert.equal(error.value, "");
});

test("创建请求进行中不会重复提交", async () => {
let resolveCreate;
let callCount = 0;
const { management } = createHarness({
roomApi: {
createGroup() {
callCount += 1;
return new Promise((resolve) => { resolveCreate = resolve; });
},
},
});
management.creation.form.name = "Team";
const pending = management.creation.submit();
await management.creation.submit();
assert.equal(callCount, 1);
resolveCreate({ channel: { id: 9, kind: "private" } });
await pending;
});

test("成员加载、邀请和移除通过同一 module 接口更新状态", async () => {
const { management, activeRoom, calls } = createHarness();
await management.members.toggle();
Expand Down
21 changes: 3 additions & 18 deletions worker/src/api/channels.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { ApiError } from '../errors.js';
import { resolveAvatarKeyUpdate } from '../avatar-policy.js';
import { errorResponse, parseJsonRequest, publicFileUrl } from '../utils.js';
import { activeUserSql } from '../user-status.js';
import { hardDeleteChannel } from '../data/channel-deletion.ts';

function normalizeMemberIds(payload) {
const source = Array.isArray(payload.memberUserIds)
Expand Down Expand Up @@ -339,15 +340,7 @@ export function registerChannelRoutes(app) {
return errorResponse('general 系统群组不能删除');
}

await c.env.DB.prepare(
`UPDATE channels
SET deleted_at = CURRENT_TIMESTAMP
WHERE id = ?
AND kind IN ('public', 'private')
AND deleted_at IS NULL`
)
.bind(channelId)
.run();
await hardDeleteChannel(c.env.DB, channelId);

return c.json({ ok: true });
});
Expand All @@ -367,15 +360,7 @@ export function registerChannelRoutes(app) {
return errorResponse('general 系统群组不能删除');
}

await c.env.DB.prepare(
`UPDATE channels
SET deleted_at = CURRENT_TIMESTAMP
WHERE id = ?
AND kind IN ('public', 'private')
AND deleted_at IS NULL`
)
.bind(channelId)
.run();
await hardDeleteChannel(c.env.DB, channelId);

return c.json({ ok: true });
});
Expand Down
36 changes: 36 additions & 0 deletions worker/src/data/channel-deletion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
interface Statement {
bind(...values: number[]): Statement;
}

interface Database {
prepare(sql: string): Statement;
batch(statements: Statement[]): Promise<{ meta: { changes: number } }[]>;
}

// API 和历史群组 GC 共用这一事务,避免不同入口遗漏关联记录或继续占用群名。
export async function hardDeleteChannel(db: Database, channelId: number) {
const target = `SELECT id FROM channels
WHERE id = ? AND kind IN ('public', 'private') AND name != 'general'`;
const [, messages, members, , channel] = await db.batch([
// 文件键先持久化再删消息;R2 由已有队列分批清理,失败或进程中断也不会丢失任务。
db.prepare(
`INSERT OR IGNORE INTO pending_r2_delete (object_key)
SELECT attachment_key FROM messages
WHERE channel_id IN (${target}) AND attachment_key IS NOT NULL AND attachment_key != ''
UNION
SELECT avatar_key FROM channels
WHERE id IN (${target}) AND avatar_key IS NOT NULL AND avatar_key != ''`,
).bind(channelId, channelId),
db.prepare(`DELETE FROM messages WHERE channel_id IN (${target})`).bind(channelId),
db.prepare(`DELETE FROM channel_members WHERE channel_id IN (${target})`).bind(channelId),
// 已读游标没有级联外键,必须先显式删除;置顶、同步事件和 Telegram 映射由外键级联。
db.prepare(`DELETE FROM message_reads WHERE channel_id IN (${target})`).bind(channelId),
db.prepare(`DELETE FROM channels WHERE id IN (${target})`).bind(channelId),
]);

return {
channelsDeleted: channel.meta.changes,
channelMessagesDeleted: messages.meta.changes,
channelMembersDeleted: members.meta.changes,
};
}
Loading
Loading