@allbluecn/collab-server 0.0.0-stage → 0.1.7

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.
Files changed (39) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +126 -2
  3. package/package.json +64 -3
  4. package/src/__tests__/clients.test.ts +93 -0
  5. package/src/__tests__/embed.test.ts +227 -0
  6. package/src/__tests__/env-setup.ts +33 -0
  7. package/src/__tests__/exporters-bug.test.ts +552 -0
  8. package/src/__tests__/exporters-case.test.ts +356 -0
  9. package/src/__tests__/exporters-design.test.ts +356 -0
  10. package/src/__tests__/exporters-knowledge.test.ts +366 -0
  11. package/src/__tests__/exporters-stats.test.ts +105 -0
  12. package/src/__tests__/exporters-story.test.ts +519 -0
  13. package/src/__tests__/internal-apply-channel.test.ts +233 -0
  14. package/src/__tests__/internal-apply-race.test.ts +165 -0
  15. package/src/__tests__/internal-apply.test.ts +418 -0
  16. package/src/__tests__/multiplex.test.ts +166 -0
  17. package/src/__tests__/persistence-retry.test.ts +262 -0
  18. package/src/__tests__/persistence.test.ts +302 -0
  19. package/src/__tests__/server.test.ts +145 -0
  20. package/src/__tests__/share-room-limit.test.ts +183 -0
  21. package/src/__tests__/shutdown.test.ts +130 -0
  22. package/src/__tests__/test-utils.ts +176 -0
  23. package/src/auth.ts +84 -0
  24. package/src/clients.ts +133 -0
  25. package/src/embed.ts +156 -0
  26. package/src/exporters/bug.ts +454 -0
  27. package/src/exporters/case.ts +317 -0
  28. package/src/exporters/design.ts +268 -0
  29. package/src/exporters/entity-shared.ts +75 -0
  30. package/src/exporters/knowledge.ts +259 -0
  31. package/src/exporters/story.ts +483 -0
  32. package/src/exporters.ts +173 -0
  33. package/src/index.ts +354 -0
  34. package/src/internal-apply-limit.ts +99 -0
  35. package/src/internal-apply.ts +888 -0
  36. package/src/metrics.ts +82 -0
  37. package/src/persistence.ts +409 -0
  38. package/src/rooms.ts +32 -0
  39. package/src/share-room-limit.ts +73 -0
package/src/metrics.ts ADDED
@@ -0,0 +1,82 @@
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
+ // 协作服务周期指标:连接数 / room 数 / update 次数与体积,setInterval 周期打印。
19
+ // 连接数与 room 数每次 tick 从 Hocuspocus 实例实时读(权威),update 计数经
20
+ // onChange extension 累积。timer unref() 不阻塞进程退出;COLLAB_METRICS=off 可关。
21
+
22
+ import type { Extension, Hocuspocus } from "@hocuspocus/server";
23
+
24
+ export interface CollabMetricsSnapshot {
25
+ connections: number;
26
+ documents: number;
27
+ updates: number;
28
+ updateBytes: number;
29
+ }
30
+
31
+ export interface CollabMetrics {
32
+ /** 装配进 Server extensions 的指标采集 extension */
33
+ extension(): Extension;
34
+ snapshot(instance: Hocuspocus): CollabMetricsSnapshot;
35
+ start(instance: Hocuspocus, intervalMs: number, log?: (line: string) => void): void;
36
+ stop(): void;
37
+ }
38
+
39
+ export function createMetrics(): CollabMetrics {
40
+ let updates = 0;
41
+ let updateBytes = 0;
42
+ let timer: ReturnType<typeof setInterval> | undefined;
43
+
44
+ return {
45
+ extension(): Extension {
46
+ return {
47
+ extensionName: "collab-metrics",
48
+ async onChange({ update }) {
49
+ updates += 1;
50
+ updateBytes += update.byteLength;
51
+ },
52
+ };
53
+ },
54
+
55
+ snapshot(instance: Hocuspocus): CollabMetricsSnapshot {
56
+ return {
57
+ connections: instance.getConnectionsCount(),
58
+ documents: instance.getDocumentsCount(),
59
+ updates,
60
+ updateBytes,
61
+ };
62
+ },
63
+
64
+ start(instance, intervalMs, log = (line) => console.log(line)) {
65
+ this.stop();
66
+ timer = setInterval(() => {
67
+ const s = this.snapshot(instance);
68
+ log(
69
+ `[collab-metrics] connections=${s.connections} documents=${s.documents} updates=${s.updates} updateBytes=${s.updateBytes}`,
70
+ );
71
+ }, intervalMs);
72
+ timer.unref?.();
73
+ },
74
+
75
+ stop() {
76
+ if (timer) {
77
+ clearInterval(timer);
78
+ timer = undefined;
79
+ }
80
+ },
81
+ };
82
+ }
@@ -0,0 +1,409 @@
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
+ // 持久层 extension(§3.2 / §5.1):快照落库 + CollabUpdate 日志 + 归属映射 + 清理。
19
+ //
20
+ // 数据流:onChange(每条入站 update,可写连接独占——view 连接在协议层已被
21
+ // 拒写)提取来源 clientID → CollabClient 映射 upsert(尽力归属)→ 日志行进
22
+ // 内存缓冲;onStoreDocument(Hocuspocus 内置 debounce,配置 2000ms)一次性
23
+ // 写 CollabDocument.state(encodeStateAsUpdate 全量快照,upsert by roomName)
24
+ // + flush 缓冲中的 CollabUpdate 日志 + 分发回写导出器(随发归属统计,
25
+ // §10.2)+ 节流顺带 squash。
26
+ //
27
+ // 幽灵 room 防御(任务 16,交接锚点 J):onLoadDocument 与 onStoreDocument
28
+ // 都先经业务守卫(exporters 注册表 registerRoomGuard)——实体已不存在的
29
+ // room 拒绝装载(空 doc + permissionDenied 终结连接)且不落快照(防已删
30
+ // 实体被内存态重建/回写复活)。
31
+ //
32
+ // 清理双保险:onStoreDocument 节流顺带 + 进程内 setInterval 兜底扫描(同一
33
+ // 清理函数)。兜底覆盖「挂起 room」——有 Y.Doc 但永不触发 storeDocument
34
+ // (如只读围观、纯 awareness 连接)时清理照常推进,不依赖写入事件。
35
+ //
36
+ // 故障口径:落库失败只记日志不上抛——协作会话的可用性优先于持久化
37
+ // (P1 权衡;未 flush 的日志行保留在缓冲,随下次 storeDocument 重试)。
38
+ //
39
+ // @allbluecn/database 经动态 import 惰性加载:persistence 未启用时
40
+ // createCollabServer 不触碰 prisma(零 DATABASE_URL 环境可纯内存运行)。
41
+
42
+ import type { Extension } from "@hocuspocus/server";
43
+ import type { CollabRoomName } from "@allbluecn/collab-core/rooms";
44
+ import * as Y from "yjs";
45
+ import {
46
+ clientIdsFromUpdate,
47
+ collectClientWrites,
48
+ forgetRoomClients,
49
+ resolveAuthorId,
50
+ upsertCollabClients,
51
+ } from "./clients";
52
+ import { readInternalApplyActor } from "./internal-apply";
53
+ import { forgetBugActivityHints } from "./exporters/bug";
54
+ import { CollabAuthError, type CollabContext } from "./auth";
55
+ import { resolveRoomName } from "./rooms";
56
+ import { runExporters, runRoomGuard, type CollabAuthorStat } from "./exporters";
57
+
58
+ /** 快照 debounce:Hocuspocus 内置配置(§3.2「配置 2s」),经 CollabServerConfig.debounceMs 下传 */
59
+ export const SNAPSHOT_DEBOUNCE_MS = 2000;
60
+
61
+ /** CollabUpdate 日志与 CollabClient 的保留窗口(§5.1:30 天) */
62
+ export const COLLAB_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
63
+
64
+ /** 兜底定时器 / onStoreDocument 顺带 squash 的默认扫描间隔 */
65
+ export const DEFAULT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
66
+
67
+ /** 单 room 日志缓冲条数上界(每击键一条量级 × 2s debounce——上界只应在 DB 长时间不可达时触顶) */
68
+ export const DEFAULT_LOG_BUFFER_MAX_ROWS = 2000;
69
+
70
+ export interface CollabPersistenceOptions {
71
+ /** 清理扫描间隔(兜底定时器周期 + onStoreDocument 顺带节流阈值);缺省 1 小时 */
72
+ cleanupIntervalMs?: number;
73
+ /**
74
+ * 单 room 日志缓冲条数上界(缺省 DEFAULT_LOG_BUFFER_MAX_ROWS);DB 长时间
75
+ * 不可达时缓冲无限累积的内存防线——超限丢弃最旧并 warn,快照路径仍能
76
+ * 恢复终态(日志缺段可接受)。
77
+ */
78
+ logBufferMaxRows?: number;
79
+ }
80
+
81
+ export interface CollabSquashResult {
82
+ /** 删除的超窗口 CollabUpdate 行数 */
83
+ updates: number;
84
+ /** 删除的 seenAt 过期 CollabClient 行数 */
85
+ clients: number;
86
+ }
87
+
88
+ /** 日志缓冲行:update 字节 + 落库时已解析的尽力归属 */
89
+ interface BufferedUpdate {
90
+ update: Uint8Array;
91
+ authorId: string | null;
92
+ }
93
+
94
+ /**
95
+ * Prisma Bytes 入参要求 Uint8Array<ArrayBuffer>;Hocuspocus/yjs 的 update
96
+ * 是 ArrayBufferLike 视图,复制为独立 ArrayBuffer 视图再落库。
97
+ */
98
+ function toStorableBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
99
+ return new Uint8Array(bytes);
100
+ }
101
+
102
+ /** 惰性 prisma 句柄(首次落库才建连) */
103
+ let dbPromise: Promise<typeof import("@allbluecn/database")> | null = null;
104
+ function getDb(): Promise<typeof import("@allbluecn/database")> {
105
+ dbPromise ??= import("@allbluecn/database");
106
+ return dbPromise;
107
+ }
108
+
109
+ /**
110
+ * squash 清理(幂等):删除超保留窗口的 CollabUpdate 日志与 seenAt 过期的
111
+ * CollabClient 映射。CollabDocument 快照不删——合并态已含全部历史信息,
112
+ * 日志只是版本历史/审计的数据源(P5 版本功能届时另定归档口径)。
113
+ * 供 onStoreDocument 顺带节流、兜底定时器与测试直接调用。
114
+ */
115
+ export async function squashExpiredCollabData(
116
+ now: Date = new Date(),
117
+ ): Promise<CollabSquashResult> {
118
+ const cutoff = new Date(now.getTime() - COLLAB_RETENTION_MS);
119
+ const db = await getDb();
120
+ const [updates, clients] = await Promise.all([
121
+ db.prisma.collabUpdate.deleteMany({ where: { createdAt: { lt: cutoff } } }),
122
+ db.prisma.collabClient.deleteMany({ where: { seenAt: { lt: cutoff } } }),
123
+ ]);
124
+ return { updates: updates.count, clients: clients.count };
125
+ }
126
+
127
+ /**
128
+ * 清理兜底定时器:进程内低频扫描(缺省每小时)跑同一 squash 清理,
129
+ * 覆盖永不触发 storeDocument 的挂起 room。timer unref() 不阻塞进程退出,
130
+ * 返回 stop(幂等,可重复调用)。
131
+ */
132
+ export function startCleanupSweeper(
133
+ intervalMs: number = DEFAULT_CLEANUP_INTERVAL_MS,
134
+ job: () => Promise<CollabSquashResult> = squashExpiredCollabData,
135
+ ): () => void {
136
+ const timer = setInterval(() => {
137
+ job().catch((err) => {
138
+ console.error("[collab-persistence] 兜底清理扫描失败(下轮重试):", err);
139
+ });
140
+ }, intervalMs);
141
+ timer.unref?.();
142
+ let stopped = false;
143
+ return () => {
144
+ if (stopped) return;
145
+ stopped = true;
146
+ clearInterval(timer);
147
+ };
148
+ }
149
+
150
+ /** 持久层句柄:createCollabServer 暴露给宿主(进程退出前停扫描) */
151
+ export interface CollabPersistenceHandle {
152
+ /** 停止兜底定时器(幂等) */
153
+ stop(): void;
154
+ }
155
+
156
+ /**
157
+ * 装配持久层 extension。与 createCollabServer 的关系:
158
+ * config.persistence 传入本工厂,extension 追加进 Server extensions,
159
+ * start() 启动兜底定时器并把 stop 句柄挂到实例(宿主退出前调用)。
160
+ */
161
+ export function createPersistence(options: CollabPersistenceOptions = {}): {
162
+ extension: Extension<CollabContext>;
163
+ start: () => CollabPersistenceHandle;
164
+ } {
165
+ const cleanupIntervalMs = options.cleanupIntervalMs ?? DEFAULT_CLEANUP_INTERVAL_MS;
166
+ const logBufferMaxRows = options.logBufferMaxRows ?? DEFAULT_LOG_BUFFER_MAX_ROWS;
167
+ let lastSquashAt = 0;
168
+ let stopSweeper: (() => void) | null = null;
169
+
170
+ /** roomName → 待 flush 日志(onStoreDocument 成功落库后才 take,失败保留重试) */
171
+ const logBuffer = new Map<string, BufferedUpdate[]>();
172
+ /** 缓冲超限 warn 一次的 room 集合(成功 flush 后复位,同 room 不刷屏) */
173
+ const bufferOverflowWarned = new Set<string>();
174
+
175
+ /**
176
+ * 幽灵 room 名册(任务 16,交接锚点 J):装载/落库守卫检出实体已不存在的
177
+ * room 记入此册,后续 storeDocument 整体跳过——防已删实体的内存态被
178
+ * unload 路径的末次 storeDocument 重建为快照行。实体 id 不可复用(cuid/
179
+ * 软删永不复活),故进程生命周期内不摘除;仅设容量上界(DEFERRED 清单:
180
+ * 大量批量删除场景防无界增长)——超限驱逐最老条目,最坏代价是对被驱逐
181
+ * room 重跑一次守卫查询(查库确认不存在后重新入册),无正确性风险。
182
+ */
183
+ const deadRooms = new Map<string, true>();
184
+ const DEAD_ROOMS_CAPACITY = 10_000;
185
+ const rememberDeadRoom = (roomName: string) => {
186
+ if (deadRooms.size >= DEAD_ROOMS_CAPACITY && !deadRooms.has(roomName)) {
187
+ const oldest = deadRooms.keys().next().value;
188
+ if (oldest !== undefined) deadRooms.delete(oldest);
189
+ }
190
+ deadRooms.set(roomName, true);
191
+ };
192
+
193
+ /**
194
+ * room 存活判定:dead 名册命中即幽灵;否则执行业务守卫(知识库 = 实体
195
+ * 存在且未软删)。onStoreDocument 与 onLoadDocument 共用。
196
+ */
197
+ const isRoomAlive = async (
198
+ documentName: string,
199
+ room: CollabRoomName,
200
+ ): Promise<boolean> => {
201
+ if (deadRooms.has(documentName)) return false;
202
+ return runRoomGuard(room);
203
+ };
204
+
205
+ /** flush 批次 → per-author 字节/操作占比(§10.2;null 归属单列) */
206
+ function computeAuthorStats(batch: BufferedUpdate[]): CollabAuthorStat[] {
207
+ const byAuthor = new Map<string | null, { updates: number; bytes: number }>();
208
+ for (const row of batch) {
209
+ const cur = byAuthor.get(row.authorId) ?? { updates: 0, bytes: 0 };
210
+ cur.updates += 1;
211
+ cur.bytes += row.update.byteLength;
212
+ byAuthor.set(row.authorId, cur);
213
+ }
214
+ return [...byAuthor].map(([authorId, stat]) => ({ authorId, ...stat }));
215
+ }
216
+
217
+ // 系统写入归属(任务 17):internal-apply 的旁路写入以 internal origin
218
+ // 事务进行且无连接 context——优先读 origin 的 actor;其余路径(有连接
219
+ // context 的正常编辑)照旧按 context 解析。归属失败降级 null(尽力归属)。
220
+ const userIdOf = (
221
+ transactionOrigin: unknown,
222
+ context: CollabContext | undefined,
223
+ ): string | null =>
224
+ readInternalApplyActor(transactionOrigin) ??
225
+ (context ? (context.user.kind === "guest" ? null : context.user.sub) : null);
226
+
227
+ const extension: Extension<CollabContext> = {
228
+ extensionName: "collab-persistence",
229
+
230
+ // 连接期映射主路径:provider 建连即同步 awareness(本地 state {}),
231
+ // 首条 awareness 到达即建立 clientID → userId(§10.2),先于任何编辑。
232
+ async onAwarenessUpdate({ documentName, connection, added, updated }) {
233
+ // 无主 awareness(对端超时摘除)不含新身份,跳过
234
+ if (!connection) return;
235
+ const room = resolveRoomName(documentName);
236
+ if (!room) return;
237
+ try {
238
+ const rows = collectClientWrites(
239
+ documentName,
240
+ [...added, ...updated],
241
+ userIdOf(undefined, connection.context),
242
+ );
243
+ await upsertCollabClients(rows);
244
+ } catch (err) {
245
+ console.error(`[collab-persistence] 映射 upsert 失败 room=${documentName}:`, err);
246
+ }
247
+ },
248
+
249
+ // 编辑路径:每条入站 update 记来源 clientID(映射兜底回填)+ 缓冲日志行。
250
+ // authorId 此刻经内存映射解析(collectClientWrites 刚回填,必然命中);
251
+ // internal-apply 的系统写入经 origin 直接归属 actor(任务 17);
252
+ // 纯 delete-set 的 update 无来源 clientID,跳过(无归属可记,状态不丢——
253
+ // 快照按全量 encodeStateAsUpdate 落库)。⚠ 审计口径缝隙(已声明接受):
254
+ // 该类操作不进 CollabUpdate 日志——版本历史/审计的数据源缺「纯删除」
255
+ // 流水,快照终态与业务回写不受影响。
256
+ async onChange({ documentName, transactionOrigin, context, update }) {
257
+ const room = resolveRoomName(documentName);
258
+ if (!room) return;
259
+ try {
260
+ const clientIds = clientIdsFromUpdate(update);
261
+ if (clientIds.length === 0) return;
262
+ const rows = collectClientWrites(
263
+ documentName,
264
+ clientIds,
265
+ userIdOf(transactionOrigin, context),
266
+ );
267
+ await upsertCollabClients(rows);
268
+ const buffer = logBuffer.get(documentName) ?? [];
269
+ buffer.push({ update, authorId: resolveAuthorId(documentName, clientIds) });
270
+ // 容量上界(故障口径的内存防线):DB 长时间不可达时每击键一条的
271
+ // 缓冲无界累积——超限丢弃最旧(快照终态仍可恢复,日志缺段可接受)
272
+ if (buffer.length > logBufferMaxRows) {
273
+ buffer.shift();
274
+ if (!bufferOverflowWarned.has(documentName)) {
275
+ bufferOverflowWarned.add(documentName);
276
+ console.warn(
277
+ `[collab-persistence] 日志缓冲超上界(${logBufferMaxRows}),丢弃最旧 room=${documentName}` +
278
+ "(落库恢复前持续丢最旧日志行;快照终态不受影响)",
279
+ );
280
+ }
281
+ }
282
+ logBuffer.set(documentName, buffer);
283
+ } catch (err) {
284
+ console.error(`[collab-persistence] 日志缓冲失败 room=${documentName}:`, err);
285
+ }
286
+ },
287
+
288
+ // 幽灵 room 装载防御(任务 16,交接锚点 J):实体已不存在 → 不应用任何
289
+ // 快照(空 doc)并整体拒绝装载。断开走框架抛错路径——load 期连接尚未
290
+ // 注册进 document.connections(addConnection 在 createDocument 之后),
291
+ // 此处 closeConnections 关不到东西;抛错触发 createDocument 的 catch
292
+ // (closeConnections + unloadDocument)+ 外层 permissionDenied 回执,
293
+ // room 不留在内存、客户端收到 authenticationFailed 终结同步等待。
294
+ //
295
+ // 快照回读(设计口径,非缺陷——审计 A07「只写不读」已排除):本服务的
296
+ // onLoadDocument 刻意不读 CollabDocument.state。重启恢复链路由 web 侧
297
+ // 承接:getCollabSnapshotFn(apps/web/src/server/serverFns/collab-snapshot.ts)
298
+ // 比较 business.updatedAt ≤ snapshot.updatedAt 时把持久化快照 base64
299
+ // 下发,客户端 useCollabDoc 在建连前 Y.applyUpdate 预水合,yjs 双向同步
300
+ // 协议把快照态灌回服务端空 doc(T14 重种子化判定也在该 serverFn 内)。
301
+ // 服务端再读一层会与该判定双头写同一 room(陈旧快照覆盖新业务列的
302
+ // 重种子化结果),故保持单点回读。
303
+ async onLoadDocument({ documentName }) {
304
+ const room = resolveRoomName(documentName);
305
+ if (!room) return;
306
+ if (await isRoomAlive(documentName, room)) return;
307
+ rememberDeadRoom(documentName);
308
+ console.warn(`[collab-persistence] 实体已不存在,拒绝装载幽灵 room=${documentName}`);
309
+ throw new CollabAuthError(`实体已删除或不存在(room=${documentName})`);
310
+ },
311
+
312
+ // 快照落库(Hocuspocus debounce 触发):全量快照 upsert → flush 日志 →
313
+ // 导出器分发 → 节流顺带 squash。任一步失败只记日志,协作不中断。
314
+ async onStoreDocument({ document, documentName, instance }) {
315
+ const room: CollabRoomName | null = resolveRoomName(documentName);
316
+ if (!room) return;
317
+ // store 级守卫复查(同 load 级守卫):拦截「实体在 room 存活期间被删」
318
+ // 的场景——web 删除只清快照行,活 room 的下一次落库在此检出幽灵并
319
+ // 断开,不落快照、不回写(成本:注册了守卫的 room 每 store 一次
320
+ // 窄投影查询,store 为 2s debounce 级别,非每击键)。
321
+ if (!(await isRoomAlive(documentName, room))) {
322
+ if (!deadRooms.has(documentName)) {
323
+ rememberDeadRoom(documentName);
324
+ console.warn(`[collab-persistence] 落库时检出实体已删,断开幽灵 room=${documentName}`);
325
+ instance.closeConnections(documentName);
326
+ }
327
+ return;
328
+ }
329
+ try {
330
+ const db = await getDb();
331
+ // 快照成功后 flush 日志批次:先取走再写(flush 期间的新编辑落新数组,
332
+ // 不与本批次混批);createMany 失败则把批次回填队首后上抛外层统一记日志
333
+ // ——回填仅圈定在本 try 内,其后步骤(导出器/快照)失败不回填
334
+ // (批次已落库,误回填会造成重复行)。
335
+ const batch = logBuffer.get(documentName);
336
+ if (batch && batch.length > 0) {
337
+ logBuffer.set(documentName, []);
338
+ try {
339
+ await db.prisma.collabUpdate.createMany({
340
+ data: batch.map((row) => ({
341
+ roomName: documentName,
342
+ update: toStorableBytes(row.update),
343
+ authorId: row.authorId,
344
+ })),
345
+ });
346
+ bufferOverflowWarned.delete(documentName);
347
+ } catch (err) {
348
+ // createMany 单语句原子(成功全成/失败全败),整批回填不重不漏;
349
+ // 失败批次时序旧于 flush 期间新缓冲的行,拼在队首保住先后顺序
350
+ logBuffer.set(documentName, [...batch, ...(logBuffer.get(documentName) ?? [])]);
351
+ throw err;
352
+ }
353
+ }
354
+ // 回写导出器(§3.2 末段 / §5.2):随发本 flush 批次的归属统计
355
+ // (§10.2 per-author 字节/操作占比);无注册 = no-op。
356
+ // ⚠️ 导出器先于快照落库(任务 17 修正):业务列 updatedAt 先行、
357
+ // 快照随后刷新,保证 T14 报告声明的安全不变式
358
+ // 「KnowledgeDocument.updatedAt ≤ CollabDocument.updatedAt」——
359
+ // 协同会话后的下次打开不误判旁路写入触发重种子化(反序则每轮 store
360
+ // 都让业务列反超快照,重种子化永续误触发)。导出成功而快照落库失败时
361
+ // 业务列较新,下次打开按旁路写重种子化自愈,语义仍正确。
362
+ await runExporters(room, document, computeAuthorStats(batch ?? []));
363
+ const state = toStorableBytes(Y.encodeStateAsUpdate(document));
364
+ await db.prisma.collabDocument.upsert({
365
+ where: { roomName: documentName },
366
+ create: { roomName: documentName, state },
367
+ update: { state },
368
+ });
369
+ // 顺带 squash(节流:距上次清理超过扫描间隔才执行)
370
+ if (Date.now() - lastSquashAt >= cleanupIntervalMs) {
371
+ lastSquashAt = Date.now();
372
+ await squashExpiredCollabData();
373
+ }
374
+ } catch (err) {
375
+ console.error(`[collab-persistence] 落库失败 room=${documentName}:`, err);
376
+ }
377
+ },
378
+
379
+ // 文档卸载:释放内存映射与残留日志缓冲(长驻进程防缓慢累积);
380
+ // 卸载路径本身会先触发最后一次 onStoreDocument,缓冲此时已 flush。
381
+ // 同路释放待出队 bug 活动 hint:幽灵检出(store 提前 return 不出队)/
382
+ // 长期无 store 的 room 依赖本路径防滞留(bug.ts Map 无跨 room 过期机制)。
383
+ async beforeUnloadDocument({ documentName }) {
384
+ forgetRoomClients(documentName);
385
+ logBuffer.delete(documentName);
386
+ bufferOverflowWarned.delete(documentName);
387
+ forgetBugActivityHints(documentName);
388
+ },
389
+
390
+ // 兜底双保险之二:Server 销毁时停扫描(宿主调 handle.stop 之外的兜底)
391
+ async onDestroy() {
392
+ stopSweeper?.();
393
+ stopSweeper = null;
394
+ },
395
+ };
396
+
397
+ function start(): CollabPersistenceHandle {
398
+ stopSweeper?.();
399
+ stopSweeper = startCleanupSweeper(cleanupIntervalMs);
400
+ return {
401
+ stop: () => {
402
+ stopSweeper?.();
403
+ stopSweeper = null;
404
+ },
405
+ };
406
+ }
407
+
408
+ return { extension, start };
409
+ }
package/src/rooms.ts ADDED
@@ -0,0 +1,32 @@
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
+ // room 注册表解析层:服务端唯一入口,复用 collab-core 的 parseRoomName
19
+ // (不在本 app 再写一份镜像——apps/collab 是纯服务端,可直接 import 全部子路径)。
20
+ // 解析失败返回 null,由 auth.ts 统一转 CollabAuthError 拒连(fail-closed)。
21
+ //
22
+ // 任务 6(persistence)的 onLoadDocument 归属校验也从此处取类型化 room,
23
+ // 按 kind 反查实体属主——本文件是「room 名 → 结构」的接缝。
24
+
25
+ import { parseRoomName, type CollabRoomName } from "@allbluecn/collab-core/rooms";
26
+
27
+ /** 解析 §3.1 注册表 room 名;格式不符返回 null(调用方一律拒绝) */
28
+ export function resolveRoomName(
29
+ documentName: string,
30
+ ): CollabRoomName | null {
31
+ return parseRoomName(documentName);
32
+ }
@@ -0,0 +1,73 @@
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
+ // §9 share room 连接上限:单 share room 连接数达上限后拒绝新连接
19
+ // (规格先例:web 端 share-events SSE 的 per-design 上限治理
20
+ // apps/web/src/lib/share-events.ts——仅参照口径,不共享实现)。
21
+ //
22
+ // 计数与拒绝语义:
23
+ // - 在 onAuthenticate 鉴权通过后检查(无效 ticket 不占名额;拒绝走任务 5
24
+ // 的 CollabAuthError 路径 → 客户端 authenticationFailed 收 reason)。
25
+ // - 计数读 hocuspocus.documents.get(room).getConnectionsCount()——连接在
26
+ // auth 后的 setUpNewConnection 才注册,本检查恰好先于注册执行,语义即
27
+ // 「已占名额数 ≥ 上限则拒新」。并发 auth 存在极小 TOCTOU 窗口(两个连接
28
+ // 同时通过检查),对「分享页 presence 读态」场景可接受,不做排队锁。
29
+ // - 非 share: 前缀 room(实体/文档/presence room)不受此上限约束。
30
+ //
31
+ // 参数取最小结构面(documents Map 值只要 getConnectionsCount)而非完整
32
+ // Hocuspocus 类型:调用方传真实实例,测试传桩件,不与框架类型锁死。
33
+
34
+ import { CollabAuthError } from "./auth";
35
+ import { resolveRoomName } from "./rooms";
36
+
37
+ /** 单 share room 连接上限默认值(§9:50) */
38
+ export const DEFAULT_SHARE_ROOM_LIMIT = 50;
39
+
40
+ /**
41
+ * 解析 COLLAB_SHARE_ROOM_LIMIT:缺省/空 → 默认 50;0 → 不设上限;
42
+ * 非法(负数/非整数/非数字)抛错——配置缺失必须显式失败。
43
+ */
44
+ export function parseShareRoomLimit(raw: string | undefined): number {
45
+ if (raw === undefined || raw.trim() === "") return DEFAULT_SHARE_ROOM_LIMIT;
46
+ const value = Number(raw);
47
+ if (!Number.isInteger(value) || value < 0) {
48
+ throw new Error(
49
+ `COLLAB_SHARE_ROOM_LIMIT 非法(${raw}):须为非负整数(0 表示不设上限)`,
50
+ );
51
+ }
52
+ return value;
53
+ }
54
+
55
+ /**
56
+ * share room 容量守卫:超限 throw CollabAuthError("room-limit")
57
+ * (Hocuspocus 转写 permissionDenied 下发,客户端退避 offline)。
58
+ * limit ≤ 0 视为不设上限;非 share room 直接放行。
59
+ */
60
+ export function assertShareRoomCapacity(
61
+ hocuspocus: { documents: Map<string, { getConnectionsCount(): number }> },
62
+ documentName: string,
63
+ limit: number,
64
+ ): void {
65
+ if (limit <= 0) return;
66
+ const room = resolveRoomName(documentName);
67
+ if (!room || room.kind !== "share") return;
68
+ const count =
69
+ hocuspocus.documents.get(documentName)?.getConnectionsCount() ?? 0;
70
+ if (count >= limit) {
71
+ throw new CollabAuthError("room-limit");
72
+ }
73
+ }