@allbluecn/collab-server 0.0.0-stage → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +126 -2
- package/package.json +64 -3
- package/src/__tests__/clients.test.ts +93 -0
- package/src/__tests__/embed.test.ts +227 -0
- package/src/__tests__/env-setup.ts +33 -0
- package/src/__tests__/exporters-bug.test.ts +552 -0
- package/src/__tests__/exporters-case.test.ts +356 -0
- package/src/__tests__/exporters-design.test.ts +356 -0
- package/src/__tests__/exporters-knowledge.test.ts +366 -0
- package/src/__tests__/exporters-stats.test.ts +105 -0
- package/src/__tests__/exporters-story.test.ts +519 -0
- package/src/__tests__/internal-apply-channel.test.ts +233 -0
- package/src/__tests__/internal-apply-race.test.ts +165 -0
- package/src/__tests__/internal-apply.test.ts +418 -0
- package/src/__tests__/multiplex.test.ts +166 -0
- package/src/__tests__/persistence-retry.test.ts +262 -0
- package/src/__tests__/persistence.test.ts +302 -0
- package/src/__tests__/server.test.ts +145 -0
- package/src/__tests__/share-room-limit.test.ts +183 -0
- package/src/__tests__/shutdown.test.ts +130 -0
- package/src/__tests__/test-utils.ts +176 -0
- package/src/auth.ts +84 -0
- package/src/clients.ts +133 -0
- package/src/embed.ts +156 -0
- package/src/exporters/bug.ts +454 -0
- package/src/exporters/case.ts +317 -0
- package/src/exporters/design.ts +268 -0
- package/src/exporters/entity-shared.ts +75 -0
- package/src/exporters/knowledge.ts +259 -0
- package/src/exporters/story.ts +483 -0
- package/src/exporters.ts +173 -0
- package/src/index.ts +354 -0
- package/src/internal-apply-limit.ts +99 -0
- package/src/internal-apply.ts +888 -0
- package/src/metrics.ts +82 -0
- package/src/persistence.ts +409 -0
- package/src/rooms.ts +32 -0
- package/src/share-room-limit.ts +73 -0
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// AllBlue - 理想之海
|
|
3
|
+
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
+
//
|
|
5
|
+
// This program is free software: you can redistribute it and/or modify
|
|
6
|
+
// it under the terms of the GNU Affero General Public License as published by
|
|
7
|
+
// the Free Software Foundation, either version 3 of the License, or
|
|
8
|
+
// (at your option) any later version.
|
|
9
|
+
//
|
|
10
|
+
// This program is distributed in the hope that it will be useful,
|
|
11
|
+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
12
|
+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
13
|
+
// GNU Affero General Public License for more details.
|
|
14
|
+
//
|
|
15
|
+
// You should have received a copy of the GNU Affero General Public License
|
|
16
|
+
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
17
|
+
|
|
18
|
+
// 内部应用通道集成测试(Yjs 多人协作 §5.3 写入路由协议,任务 17):
|
|
19
|
+
// 真实 WS + 真实共享开发库(任务 6/16 模式),全部 test-exp- 前缀精确清理。
|
|
20
|
+
//
|
|
21
|
+
// §5.3 逐条对齐(复审定稿语义):
|
|
22
|
+
// 1. HTTP 通道挂载(Hocuspocus 同端口 request 监听器置换):非内部路由委托
|
|
23
|
+
// 回 Hocuspocus 默认响应,WS 升级不受影响(其余用例全部真连 provider 隐证)
|
|
24
|
+
// 2. 信封(R7):坏签名/过期 ts/未来 ts → 401;载荷非法 → 400
|
|
25
|
+
// 3. room 在线 → 应用到 Y 并广播(provider 收到替换后内容,整文档 replace
|
|
26
|
+
// 语义——DB 旁路写是权威时刻,规格接受覆盖协同者中间态),落库走
|
|
27
|
+
// onStoreDocument 统一链路:导出器回写 content + 归属 actor(系统 client)
|
|
28
|
+
// + 快照顺序不变式(KnowledgeDocument.updatedAt ≤ CollabDocument.updatedAt,
|
|
29
|
+
// T14 报告声明、T17 落实)
|
|
30
|
+
// 4. room 离线 → collab 直接落库业务列(patch.content 原样)+ 触发重索引通知
|
|
31
|
+
// + 不触碰快照行(视为旁路写,重种子化兜底:doc.updatedAt > 快照 updatedAt)
|
|
32
|
+
// 5. 幽灵 room(实体已删)→ 409 拒绝且不落库(web 侧降级直写后由属主校验
|
|
33
|
+
// 自然报「未找到或无权限」)
|
|
34
|
+
// 6. 双写不互吞:非协同客户端改标题(web 门卫元数据直写语义的 DB 侧模拟)+
|
|
35
|
+
// 协同客户端改正文(provider Y 编辑)→ 两者都保留
|
|
36
|
+
|
|
37
|
+
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
|
38
|
+
import * as http from "node:http";
|
|
39
|
+
import * as Y from "yjs";
|
|
40
|
+
import { buildRoomName } from "@allbluecn/collab-core/rooms";
|
|
41
|
+
import {
|
|
42
|
+
INTERNAL_DOMAIN_APPLY,
|
|
43
|
+
INTERNAL_SIGNATURE_HEADER,
|
|
44
|
+
signInternalRequest,
|
|
45
|
+
} from "@allbluecn/collab-core/internal";
|
|
46
|
+
import { seedYDocFromHtml } from "@allbluecn/collab-core/tiptap-export";
|
|
47
|
+
import { yDocToProsemirrorJSON } from "@tiptap/y-tiptap";
|
|
48
|
+
import { createKnowledgeExtensions } from "@allbluecn/collab-core/knowledge-schema";
|
|
49
|
+
import { createKnowledgeDocAdditions } from "@allbluecn/collab-core/knowledge-additions";
|
|
50
|
+
import { prisma } from "@allbluecn/database";
|
|
51
|
+
import {
|
|
52
|
+
TEST_SECRET,
|
|
53
|
+
connectProvider,
|
|
54
|
+
issueTicket,
|
|
55
|
+
sleep,
|
|
56
|
+
startCollabServer,
|
|
57
|
+
waitUntil,
|
|
58
|
+
type ProviderSession,
|
|
59
|
+
type StartedServer,
|
|
60
|
+
} from "./test-utils";
|
|
61
|
+
import {
|
|
62
|
+
ensureServerDom,
|
|
63
|
+
registerKnowledgeCollab,
|
|
64
|
+
resetKnowledgeReindexNotifier,
|
|
65
|
+
setKnowledgeReindexNotifier,
|
|
66
|
+
} from "../exporters/knowledge";
|
|
67
|
+
import { INTERNAL_APPLY_MAX_BODY_BYTES } from "../internal-apply";
|
|
68
|
+
import { resetExporters, resetRoomGuards } from "../exporters";
|
|
69
|
+
|
|
70
|
+
/** 测试资源前缀(docId / userId / kbId / AuditLog.resourceId 共用) */
|
|
71
|
+
const PREFIX = "test-exp-";
|
|
72
|
+
/** room 名清理前缀 */
|
|
73
|
+
const ROOM_LIKE = `doc:knowledge:${PREFIX}`;
|
|
74
|
+
|
|
75
|
+
interface TestDoc {
|
|
76
|
+
userId: string;
|
|
77
|
+
kbId: string;
|
|
78
|
+
docId: string;
|
|
79
|
+
room: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const trackedRooms: string[] = [];
|
|
83
|
+
const trackedDocs: TestDoc[] = [];
|
|
84
|
+
|
|
85
|
+
function rand(): string {
|
|
86
|
+
return Math.random().toString(36).slice(2, 10);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 建知识库测试行:User → KnowledgeBase → KnowledgeDocument(软删字段全默认) */
|
|
90
|
+
async function createDocFixture(content: unknown): Promise<TestDoc> {
|
|
91
|
+
const suffix = rand();
|
|
92
|
+
const userId = `${PREFIX}user-${suffix}`;
|
|
93
|
+
const kbId = `${PREFIX}kb-${suffix}`;
|
|
94
|
+
const docId = `${PREFIX}doc-${suffix}`;
|
|
95
|
+
await prisma.user.create({
|
|
96
|
+
data: {
|
|
97
|
+
id: userId,
|
|
98
|
+
email: `${suffix}@collab-apply.test`,
|
|
99
|
+
username: `collab-apply-${suffix}`,
|
|
100
|
+
password: "test-only",
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
await prisma.knowledgeBase.create({
|
|
104
|
+
data: { id: kbId, name: "内部通道测试库", userId },
|
|
105
|
+
});
|
|
106
|
+
await prisma.knowledgeDocument.create({
|
|
107
|
+
data: { id: docId, kbId, title: "内部通道测试文档", createdBy: userId, content: content as object },
|
|
108
|
+
});
|
|
109
|
+
const room = buildRoomName({ kind: "knowledge-doc", docId });
|
|
110
|
+
trackedRooms.push(room);
|
|
111
|
+
const doc = { userId, kbId, docId, room };
|
|
112
|
+
trackedDocs.push(doc);
|
|
113
|
+
return doc;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function cleanOwnRows(): Promise<void> {
|
|
117
|
+
await prisma.collabUpdate.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
|
|
118
|
+
await prisma.collabClient.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
|
|
119
|
+
await prisma.collabDocument.deleteMany({ where: { roomName: { startsWith: ROOM_LIKE } } });
|
|
120
|
+
await prisma.auditLog.deleteMany({ where: { resourceId: { startsWith: PREFIX }, action: "document.collab_update" } });
|
|
121
|
+
await prisma.knowledgeDocument.deleteMany({ where: { id: { startsWith: PREFIX } } });
|
|
122
|
+
await prisma.knowledgeBase.deleteMany({ where: { id: { startsWith: PREFIX } } });
|
|
123
|
+
await prisma.user.deleteMany({ where: { id: { startsWith: PREFIX } } });
|
|
124
|
+
const residue =
|
|
125
|
+
(await prisma.collabDocument.count({ where: { roomName: { startsWith: ROOM_LIKE } } })) +
|
|
126
|
+
(await prisma.collabUpdate.count({ where: { roomName: { startsWith: ROOM_LIKE } } })) +
|
|
127
|
+
(await prisma.knowledgeDocument.count({ where: { id: { startsWith: PREFIX } } })) +
|
|
128
|
+
(await prisma.user.count({ where: { id: { startsWith: PREFIX } } }));
|
|
129
|
+
expect(residue).toBe(0);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 与种子化同一扩展组合把 HTML 变成 Y update(建快照行用) */
|
|
133
|
+
function htmlToState(html: string): Uint8Array<ArrayBuffer> {
|
|
134
|
+
const yDoc = seedYDocFromHtml(html, [
|
|
135
|
+
...createKnowledgeExtensions(),
|
|
136
|
+
...createKnowledgeDocAdditions(),
|
|
137
|
+
]);
|
|
138
|
+
return new Uint8Array(Y.encodeStateAsUpdate(yDoc));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 内部应用请求(信封签名;payload 缺省给完整合法值,按需覆盖) */
|
|
142
|
+
async function postApply(
|
|
143
|
+
ctx: StartedServer,
|
|
144
|
+
payload: Record<string, unknown>,
|
|
145
|
+
opts: { secret?: string; ts?: number; omitSignature?: boolean } = {},
|
|
146
|
+
): Promise<Response> {
|
|
147
|
+
const signed = signInternalRequest({
|
|
148
|
+
secret: opts.secret ?? TEST_SECRET,
|
|
149
|
+
domain: INTERNAL_DOMAIN_APPLY,
|
|
150
|
+
payload,
|
|
151
|
+
now: opts.ts,
|
|
152
|
+
});
|
|
153
|
+
const headers: Record<string, string> = { "content-type": "application/json" };
|
|
154
|
+
if (!opts.omitSignature) {
|
|
155
|
+
headers[INTERNAL_SIGNATURE_HEADER] = signed.headers[INTERNAL_SIGNATURE_HEADER]!;
|
|
156
|
+
}
|
|
157
|
+
return fetch(`http://127.0.0.1:${ctx.port}/internal/apply`, {
|
|
158
|
+
method: "POST",
|
|
159
|
+
headers,
|
|
160
|
+
body: signed.body,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function applyPayload(fixture: TestDoc, html: string): Record<string, unknown> {
|
|
165
|
+
return {
|
|
166
|
+
roomName: fixture.room,
|
|
167
|
+
docId: fixture.docId,
|
|
168
|
+
actor: fixture.userId,
|
|
169
|
+
patch: { content: { html, markdown: html } },
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** 轮询 DB 断言(异步落库无法同步等待) */
|
|
174
|
+
async function pollDb(check: () => Promise<boolean>, label: string, timeoutMs = 8000): Promise<void> {
|
|
175
|
+
const deadline = Date.now() + timeoutMs;
|
|
176
|
+
while (!(await check())) {
|
|
177
|
+
if (Date.now() > deadline) throw new Error(`pollDb 超时(${label})`);
|
|
178
|
+
await sleep(50);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 原生 node:http POST(I2 用):fetch 不允许手工指定 content-length,
|
|
184
|
+
* 体积守卫的声明头/谎报/缺失三态需要原生客户端驱动。
|
|
185
|
+
*/
|
|
186
|
+
function rawPost(
|
|
187
|
+
port: number,
|
|
188
|
+
headers: Record<string, string | number>,
|
|
189
|
+
body?: Buffer,
|
|
190
|
+
): Promise<{ status: number; body: string }> {
|
|
191
|
+
return new Promise((resolve, reject) => {
|
|
192
|
+
const req = http.request(
|
|
193
|
+
{ host: "127.0.0.1", port, path: "/internal/apply", method: "POST", headers },
|
|
194
|
+
(res) => {
|
|
195
|
+
const chunks: Buffer[] = [];
|
|
196
|
+
res.on("data", (c: Buffer) => chunks.push(c));
|
|
197
|
+
res.on("end", () =>
|
|
198
|
+
resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }),
|
|
199
|
+
);
|
|
200
|
+
},
|
|
201
|
+
);
|
|
202
|
+
// 响应后服务端断开未消费的残余上传可触发,此时响应已到手
|
|
203
|
+
req.on("error", () => {});
|
|
204
|
+
if (body) req.end(body);
|
|
205
|
+
else req.end();
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
describe("/internal/apply(web → collab 旁路写入转发,真实 WS + 真实库)", () => {
|
|
210
|
+
let ctx: StartedServer;
|
|
211
|
+
let session: ProviderSession | null = null;
|
|
212
|
+
let reindexSpy: ReturnType<typeof vi.fn<(docId: string) => Promise<void>>>;
|
|
213
|
+
|
|
214
|
+
beforeEach(async () => {
|
|
215
|
+
await ensureServerDom();
|
|
216
|
+
registerKnowledgeCollab();
|
|
217
|
+
reindexSpy = vi.fn<(docId: string) => Promise<void>>().mockResolvedValue(undefined);
|
|
218
|
+
setKnowledgeReindexNotifier(reindexSpy);
|
|
219
|
+
ctx = await startCollabServer({ persistence: {}, debounceMs: 300 });
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
afterEach(async () => {
|
|
223
|
+
session?.destroy();
|
|
224
|
+
session = null;
|
|
225
|
+
await ctx?.stop();
|
|
226
|
+
resetExporters();
|
|
227
|
+
resetRoomGuards();
|
|
228
|
+
resetKnowledgeReindexNotifier();
|
|
229
|
+
await cleanOwnRows();
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
test("非内部路由委托回 Hocuspocus 默认响应(监听器置换不破坏既有 HTTP 面)", async () => {
|
|
233
|
+
const res = await fetch(`http://127.0.0.1:${ctx.port}/`);
|
|
234
|
+
expect(res.status).toBe(200);
|
|
235
|
+
expect(await res.text()).toContain("Hocuspocus");
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
test("信封负例:坏签名 / 过期 ts / 未来 ts → 401,库零写入", async () => {
|
|
239
|
+
const fixture = await createDocFixture({ html: "<p>初始</p>", markdown: "初始" });
|
|
240
|
+
const before = await prisma.knowledgeDocument.findUnique({ where: { id: fixture.docId } });
|
|
241
|
+
|
|
242
|
+
const bad = await postApply(ctx, applyPayload(fixture, "<p>x</p>"), { secret: "wrong-secret" });
|
|
243
|
+
const expired = await postApply(ctx, applyPayload(fixture, "<p>x</p>"), { ts: Math.floor(Date.now() / 1000) - 61 });
|
|
244
|
+
const future = await postApply(ctx, applyPayload(fixture, "<p>x</p>"), { ts: Math.floor(Date.now() / 1000) + 61 });
|
|
245
|
+
const missing = await postApply(ctx, applyPayload(fixture, "<p>x</p>"), { omitSignature: true });
|
|
246
|
+
|
|
247
|
+
expect(bad.status).toBe(401);
|
|
248
|
+
expect(expired.status).toBe(401);
|
|
249
|
+
expect(future.status).toBe(401);
|
|
250
|
+
expect(missing.status).toBe(401);
|
|
251
|
+
const after = await prisma.knowledgeDocument.findUnique({ where: { id: fixture.docId } });
|
|
252
|
+
expect(after!.updatedAt).toEqual(before!.updatedAt);
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
test("载荷非法:未知 room / docId 与 room 不符 / content 缺 html → 400", async () => {
|
|
256
|
+
const fixture = await createDocFixture({ html: "<p>初始</p>", markdown: "初始" });
|
|
257
|
+
|
|
258
|
+
const unknownRoom = await postApply(ctx, {
|
|
259
|
+
...applyPayload(fixture, "<p>x</p>"),
|
|
260
|
+
roomName: "doc:knowledge:does-not-exist",
|
|
261
|
+
});
|
|
262
|
+
const docIdMismatch = await postApply(ctx, {
|
|
263
|
+
...applyPayload(fixture, "<p>x</p>"),
|
|
264
|
+
docId: "other-doc",
|
|
265
|
+
});
|
|
266
|
+
const noHtml = await postApply(ctx, {
|
|
267
|
+
...applyPayload(fixture, "<p>x</p>"),
|
|
268
|
+
patch: { content: { markdown: "only-md" } },
|
|
269
|
+
});
|
|
270
|
+
const presenceRoom = await postApply(ctx, {
|
|
271
|
+
...applyPayload(fixture, "<p>x</p>"),
|
|
272
|
+
roomName: "presence:team:someone",
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
expect(unknownRoom.status).toBe(400);
|
|
276
|
+
expect(docIdMismatch.status).toBe(400);
|
|
277
|
+
expect(noHtml.status).toBe(400);
|
|
278
|
+
expect(presenceRoom.status).toBe(400);
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
test("room 在线:应用到 Y 并广播 + onStoreDocument 统一落库(归属 actor + 顺序不变式)", async () => {
|
|
282
|
+
const fixture = await createDocFixture({ html: "<p>初始</p>", markdown: "初始" });
|
|
283
|
+
// 模拟协同已开启:先有快照行(客户端 provider 装载即得该态)
|
|
284
|
+
await prisma.collabDocument.create({
|
|
285
|
+
data: { roomName: fixture.room, state: htmlToState("<p>初始</p>") },
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
session = await connectProvider(ctx.url, fixture.room, issueTicket(fixture.room));
|
|
289
|
+
|
|
290
|
+
const res = await postApply(ctx, applyPayload(fixture, "<p>外部权威写入</p>"));
|
|
291
|
+
expect(res.status).toBe(202);
|
|
292
|
+
expect(await res.json()).toMatchObject({ applied: "ydoc", connections: 1 });
|
|
293
|
+
|
|
294
|
+
// 广播:provider 的 Y 文档被整文档替换(初始内容消失、外部内容到达)
|
|
295
|
+
await waitUntil(() => {
|
|
296
|
+
const json = yDocToProsemirrorJSON(session!.provider.document as Y.Doc, "default");
|
|
297
|
+
return JSON.stringify(json).includes("外部权威写入");
|
|
298
|
+
}, "provider 未收到内部应用的广播");
|
|
299
|
+
const json = yDocToProsemirrorJSON(session!.provider.document as Y.Doc, "default");
|
|
300
|
+
expect(JSON.stringify(json)).not.toContain("初始");
|
|
301
|
+
|
|
302
|
+
// 落库走 onStoreDocument 统一链路(internal-apply 显式调度 debounced store)
|
|
303
|
+
await pollDb(async () => {
|
|
304
|
+
const doc = await prisma.knowledgeDocument.findUnique({ where: { id: fixture.docId } });
|
|
305
|
+
return JSON.stringify(doc?.content).includes("外部权威写入");
|
|
306
|
+
}, "导出器未回写 content");
|
|
307
|
+
|
|
308
|
+
// 归属(系统 client,userId=actor):日志行 + CollabClient 映射 + 审计主作者
|
|
309
|
+
const updateRow = await prisma.collabUpdate.findFirst({ where: { roomName: fixture.room } });
|
|
310
|
+
expect(updateRow?.authorId).toBe(fixture.userId);
|
|
311
|
+
const clientRows = await prisma.collabClient.findMany({ where: { roomName: fixture.room, userId: fixture.userId } });
|
|
312
|
+
expect(clientRows.length).toBeGreaterThan(0);
|
|
313
|
+
const audit = await prisma.auditLog.findFirst({
|
|
314
|
+
where: { resourceId: fixture.docId, action: "document.collab_update" },
|
|
315
|
+
});
|
|
316
|
+
expect(audit?.userId).toBe(fixture.userId);
|
|
317
|
+
|
|
318
|
+
// 顺序不变式(T14 报告声明 / T17 落实):业务列 updatedAt ≤ 快照 updatedAt
|
|
319
|
+
// ——协同会话后的下次打开不再误判旁路写入触发重种子化
|
|
320
|
+
const doc = await prisma.knowledgeDocument.findUnique({ where: { id: fixture.docId } });
|
|
321
|
+
const snap = await prisma.collabDocument.findUnique({ where: { roomName: fixture.room } });
|
|
322
|
+
expect(doc!.updatedAt.getTime()).toBeLessThanOrEqual(snap!.updatedAt.getTime());
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
test("room 离线:直接落库业务列(content 原样)+ 触发重索引 + 快照行不触碰(旁路写 → 重种子化判定成立)", async () => {
|
|
326
|
+
const fixture = await createDocFixture({ html: "<p>旧内容</p>", markdown: "旧内容" });
|
|
327
|
+
const oldState = htmlToState("<p>旧内容</p>");
|
|
328
|
+
await prisma.collabDocument.create({ data: { roomName: fixture.room, state: oldState } });
|
|
329
|
+
const snapBefore = await prisma.collabDocument.findUnique({ where: { roomName: fixture.room } });
|
|
330
|
+
|
|
331
|
+
const patchContent = { html: "<p>非协同客户端的保存</p>", markdown: "非协同客户端的保存" };
|
|
332
|
+
// applyPayload 的 patch.content 原样入库(与 web 直写同语义)——这里直接
|
|
333
|
+
// 传完整 content 对象验证「原样」而非经 helper 转形
|
|
334
|
+
const res = await postApply(ctx, { ...applyPayload(fixture, patchContent.html), patch: { content: patchContent } });
|
|
335
|
+
expect(res.status).toBe(202);
|
|
336
|
+
expect(await res.json()).toMatchObject({ applied: "db" });
|
|
337
|
+
|
|
338
|
+
const doc = await prisma.knowledgeDocument.findUnique({ where: { id: fixture.docId } });
|
|
339
|
+
expect(doc!.content).toEqual(patchContent);
|
|
340
|
+
// 快照行不触碰(重种子化兜底接管)
|
|
341
|
+
const snapAfter = await prisma.collabDocument.findUnique({ where: { roomName: fixture.room } });
|
|
342
|
+
expect(Buffer.from(snapAfter!.state).equals(Buffer.from(oldState))).toBe(true);
|
|
343
|
+
expect(snapAfter!.updatedAt).toEqual(snapBefore!.updatedAt);
|
|
344
|
+
// 旁路写判定:业务列较新(collab-snapshot 的 T14 比较输入)
|
|
345
|
+
expect(doc!.updatedAt.getTime()).toBeGreaterThan(snapAfter!.updatedAt.getTime());
|
|
346
|
+
// 内容变更的索引口径单源:离线直落同样触发重建通知
|
|
347
|
+
expect(reindexSpy).toHaveBeenCalledTimes(1);
|
|
348
|
+
expect(reindexSpy).toHaveBeenCalledWith(fixture.docId);
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
test("幽灵 room(实体已删)→ 409 拒绝且不落库", async () => {
|
|
352
|
+
const fixture = await createDocFixture({ html: "<p>将删</p>", markdown: "将删" });
|
|
353
|
+
await prisma.knowledgeDocument.update({ where: { id: fixture.docId }, data: { isDeleted: true } });
|
|
354
|
+
|
|
355
|
+
const res = await postApply(ctx, applyPayload(fixture, "<p>x</p>"));
|
|
356
|
+
expect(res.status).toBe(409);
|
|
357
|
+
const doc = await prisma.knowledgeDocument.findUnique({ where: { id: fixture.docId } });
|
|
358
|
+
expect(JSON.stringify(doc!.content)).toContain("将删");
|
|
359
|
+
expect(reindexSpy).not.toHaveBeenCalled();
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
test("双写不互吞:非协同客户端改标题 + 协同客户端改正文 → 两者都保留", async () => {
|
|
363
|
+
const fixture = await createDocFixture({ html: "<p>起点</p>", markdown: "起点" });
|
|
364
|
+
|
|
365
|
+
// 非协同客户端改标题(web 门卫元数据直写语义的 DB 侧模拟:title 不归 Y)
|
|
366
|
+
await prisma.knowledgeDocument.update({
|
|
367
|
+
where: { id: fixture.docId },
|
|
368
|
+
data: { title: "非协同改的标题" },
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
// 协同客户端改正文(provider Y 编辑 → 广播 → onStoreDocument 回写 content)
|
|
372
|
+
session = await connectProvider(ctx.url, fixture.room, issueTicket(fixture.room));
|
|
373
|
+
const frag = session.provider.document.getXmlFragment("default");
|
|
374
|
+
session.provider.document.transact(() => {
|
|
375
|
+
frag.delete(0, frag.length);
|
|
376
|
+
const paragraph = new Y.XmlElement("paragraph");
|
|
377
|
+
const text = new Y.XmlText();
|
|
378
|
+
text.insert(0, "协同客户端的正文");
|
|
379
|
+
paragraph.insert(0, [text]);
|
|
380
|
+
frag.insert(0, [paragraph]);
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
await pollDb(async () => {
|
|
384
|
+
const doc = await prisma.knowledgeDocument.findUnique({ where: { id: fixture.docId } });
|
|
385
|
+
return JSON.stringify(doc?.content).includes("协同客户端的正文");
|
|
386
|
+
}, "协同正文未回写");
|
|
387
|
+
|
|
388
|
+
const doc = await prisma.knowledgeDocument.findUnique({ where: { id: fixture.docId } });
|
|
389
|
+
expect(doc!.title).toBe("非协同改的标题");
|
|
390
|
+
expect(JSON.stringify(doc!.content)).toContain("协同客户端的正文");
|
|
391
|
+
expect(JSON.stringify(doc!.content)).not.toContain("起点");
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
test("I2:声明 content-length 超上限 → 413 零读体(验签前的内存 DoS 守卫)", async () => {
|
|
395
|
+
const res = await rawPost(
|
|
396
|
+
ctx.port,
|
|
397
|
+
{ "content-length": String(INTERNAL_APPLY_MAX_BODY_BYTES + 1) },
|
|
398
|
+
Buffer.alloc(16),
|
|
399
|
+
);
|
|
400
|
+
expect(res.status).toBe(413);
|
|
401
|
+
expect(JSON.parse(res.body)).toEqual({ error: "payload too large" });
|
|
402
|
+
expect(reindexSpy).not.toHaveBeenCalled();
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
test("I2:缺失 content-length(chunked)的流式超限 → 413 截断", async () => {
|
|
406
|
+
const oversized = Buffer.alloc(INTERNAL_APPLY_MAX_BODY_BYTES + 1024, 0x61);
|
|
407
|
+
const res = await rawPost(ctx.port, {}, oversized);
|
|
408
|
+
expect(res.status).toBe(413);
|
|
409
|
+
expect(JSON.parse(res.body)).toEqual({ error: "payload too large" });
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
test("I2:正常体积请求不受影响(体积守卫后照常进入验签)", async () => {
|
|
413
|
+
const res = await rawPost(ctx.port, { "content-length": 10 }, Buffer.alloc(10));
|
|
414
|
+
// 无签名 → 401(到达信封验签层,证明未误伤正常请求)
|
|
415
|
+
expect(res.status).toBe(401);
|
|
416
|
+
});
|
|
417
|
+
});
|
|
418
|
+
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// AllBlue - 理想之海
|
|
3
|
+
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
+
//
|
|
5
|
+
// This program is free software: you can redistribute it and/or modify
|
|
6
|
+
// it under the terms of the GNU Affero General Public License as published by
|
|
7
|
+
// the Free Software Foundation, either version 3 of the License, or
|
|
8
|
+
// (at your option) any later version.
|
|
9
|
+
//
|
|
10
|
+
// This program is distributed in the hope that it will be useful,
|
|
11
|
+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
12
|
+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
13
|
+
// GNU Affero General Public License for more details.
|
|
14
|
+
//
|
|
15
|
+
// You should have received a copy of the GNU Affero General Public License
|
|
16
|
+
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
17
|
+
|
|
18
|
+
// §6 步骤 4.5 多路复用实测(P1 关键决策):HocuspocusProviderWebsocket
|
|
19
|
+
// 共享单连接 vs 每 room 独立连接。2025-07 上游有共享连接 race condition
|
|
20
|
+
// issue——本文件在 4.7 真服务(port 0 内存随机端口)上实测:双 provider
|
|
21
|
+
// 共享一条 WebSocket,并发建连/断开 20 轮 + 即建即断竞态,断言无卡死、
|
|
22
|
+
// 无串 room、共享连接存活。
|
|
23
|
+
// 已证 4.7 语义:① 共享连接按 effectiveName 键控,同一 room 同时只允许
|
|
24
|
+
// 一个 provider(重复 attach 抛错);② 服务端 room 文档在最后一个连接
|
|
25
|
+
// detach 后立即卸载(room 内容跨轮不保留,断言只能用当轮标记)。
|
|
26
|
+
// 结论供 apps/web/src/lib/collab/provider.ts 顶注释引用(实测日期见 git)。
|
|
27
|
+
|
|
28
|
+
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
|
29
|
+
import * as Y from "yjs";
|
|
30
|
+
import {
|
|
31
|
+
HocuspocusProvider,
|
|
32
|
+
HocuspocusProviderWebsocket,
|
|
33
|
+
} from "@hocuspocus/provider";
|
|
34
|
+
import {
|
|
35
|
+
issueTicket,
|
|
36
|
+
sleep,
|
|
37
|
+
startCollabServer,
|
|
38
|
+
waitUntil,
|
|
39
|
+
type StartedServer,
|
|
40
|
+
} from "./test-utils";
|
|
41
|
+
|
|
42
|
+
const ROOM_A = "doc:knowledge:mx-a";
|
|
43
|
+
const ROOM_B = "doc:knowledge:mx-b";
|
|
44
|
+
|
|
45
|
+
/** 本用例所有打开过的 provider(afterEach 兜底销毁,防用例间残留 attach) */
|
|
46
|
+
const openProviders: HocuspocusProvider[] = [];
|
|
47
|
+
|
|
48
|
+
/** 单 provider 挂到共享 WebSocket,等待 authenticated + synced */
|
|
49
|
+
function connectShared(
|
|
50
|
+
websocket: HocuspocusProviderWebsocket,
|
|
51
|
+
room: string,
|
|
52
|
+
): { provider: HocuspocusProvider; doc: Y.Doc; ready: Promise<void> } {
|
|
53
|
+
const doc = new Y.Doc();
|
|
54
|
+
const provider = new HocuspocusProvider({
|
|
55
|
+
websocketProvider: websocket,
|
|
56
|
+
name: room,
|
|
57
|
+
token: issueTicket(room),
|
|
58
|
+
document: doc,
|
|
59
|
+
});
|
|
60
|
+
const ready = new Promise<void>((resolve, reject) => {
|
|
61
|
+
provider.on("synced", () => resolve());
|
|
62
|
+
provider.on("authenticationFailed", ({ reason }: { reason: string }) =>
|
|
63
|
+
reject(new Error(`${room} 鉴权失败:${reason}`)),
|
|
64
|
+
);
|
|
65
|
+
});
|
|
66
|
+
provider.attach();
|
|
67
|
+
openProviders.push(provider);
|
|
68
|
+
return { provider, doc, ready };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 双 room 并发建连 → 双双 ready → 各写标记 → 等本地回环 → 断言互不串 */
|
|
72
|
+
async function assertIsolatedRound(
|
|
73
|
+
websocket: HocuspocusProviderWebsocket,
|
|
74
|
+
round: number,
|
|
75
|
+
opts: { destroyAfter: boolean; settleMs: number },
|
|
76
|
+
): Promise<void> {
|
|
77
|
+
const [pairA, pairB] = [
|
|
78
|
+
connectShared(websocket, ROOM_A),
|
|
79
|
+
connectShared(websocket, ROOM_B),
|
|
80
|
+
];
|
|
81
|
+
await Promise.all([pairA.ready, pairB.ready]);
|
|
82
|
+
|
|
83
|
+
pairA.doc.getText("t").insert(0, `A${round}`);
|
|
84
|
+
pairB.doc.getText("t").insert(0, `B${round}`);
|
|
85
|
+
await waitUntil(
|
|
86
|
+
() => pairA.doc.getText("t").toString().includes(`A${round}`),
|
|
87
|
+
`round ${round} room A 本地回环`,
|
|
88
|
+
);
|
|
89
|
+
await waitUntil(
|
|
90
|
+
() => pairB.doc.getText("t").toString().includes(`B${round}`),
|
|
91
|
+
`round ${round} room B 本地回环`,
|
|
92
|
+
);
|
|
93
|
+
// 串 room = 对方的更新经服务端广播落到自己 doc(此处双活,写已互达)
|
|
94
|
+
expect(pairA.doc.getText("t").toString()).not.toContain(`B${round}`);
|
|
95
|
+
expect(pairB.doc.getText("t").toString()).not.toContain(`A${round}`);
|
|
96
|
+
|
|
97
|
+
if (opts.destroyAfter) {
|
|
98
|
+
pairA.provider.destroy();
|
|
99
|
+
pairB.provider.destroy();
|
|
100
|
+
}
|
|
101
|
+
if (opts.settleMs > 0) await sleep(opts.settleMs);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
describe("多路复用实测:HocuspocusProviderWebsocket 共享单连接(4.7)", () => {
|
|
105
|
+
let started: StartedServer;
|
|
106
|
+
let websocket: HocuspocusProviderWebsocket;
|
|
107
|
+
|
|
108
|
+
beforeAll(async () => {
|
|
109
|
+
started = await startCollabServer();
|
|
110
|
+
websocket = new HocuspocusProviderWebsocket({
|
|
111
|
+
url: started.url,
|
|
112
|
+
// 显式关 jitter,保证多轮行为可复现
|
|
113
|
+
jitter: false,
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
afterEach(async () => {
|
|
118
|
+
while (openProviders.length > 0) openProviders.pop()?.destroy();
|
|
119
|
+
// detach/CloseMessage 是异步下发,留一拍让 providerMap 清干净
|
|
120
|
+
await sleep(50);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
afterAll(async () => {
|
|
124
|
+
websocket?.destroy();
|
|
125
|
+
await started?.stop();
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("共享单连接双 room 双活:鉴权各自通过、内容不串 room", async () => {
|
|
129
|
+
await assertIsolatedRound(websocket, 0, { destroyAfter: false, settleMs: 0 });
|
|
130
|
+
// 双活保持到断言结束(afterEach 统一销毁)
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("并发建连/断开 20 轮:无卡死、room 不串、共享连接存活", async () => {
|
|
134
|
+
for (let round = 1; round <= 20; round++) {
|
|
135
|
+
// 轮间几乎不留间隙,让下一轮 attach 踩在上一个 detach 处理途中
|
|
136
|
+
await assertIsolatedRound(websocket, round, {
|
|
137
|
+
destroyAfter: true,
|
|
138
|
+
settleMs: round % 5 === 0 ? 20 : 0,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// 风暴后共享连接仍可用(无卡死的正面证明):再连一轮并完成回环
|
|
143
|
+
await assertIsolatedRound(websocket, 9999, {
|
|
144
|
+
destroyAfter: false,
|
|
145
|
+
settleMs: 0,
|
|
146
|
+
});
|
|
147
|
+
}, 30000);
|
|
148
|
+
|
|
149
|
+
it("即建即断竞态 10 轮:不抛错、不卡死、连接存活", async () => {
|
|
150
|
+
// 2025-07 issue 的高发路径:attach 后未等 ready 立即 destroy,
|
|
151
|
+
// 与 socket 重连/消息队列清理互相踩踏
|
|
152
|
+
for (let round = 1; round <= 10; round++) {
|
|
153
|
+
const a = connectShared(websocket, ROOM_A);
|
|
154
|
+
const b = connectShared(websocket, ROOM_B);
|
|
155
|
+
a.provider.destroy();
|
|
156
|
+
b.provider.destroy();
|
|
157
|
+
if (round % 3 === 0) await sleep(10);
|
|
158
|
+
}
|
|
159
|
+
await sleep(100);
|
|
160
|
+
// 风暴后仍能完成一轮正常建连 + 回环
|
|
161
|
+
await assertIsolatedRound(websocket, 8888, {
|
|
162
|
+
destroyAfter: false,
|
|
163
|
+
settleMs: 0,
|
|
164
|
+
});
|
|
165
|
+
}, 30000);
|
|
166
|
+
});
|