@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,483 @@
|
|
|
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
|
+
// Story 回写导出器(Yjs 多人协作 §5.2 回写 / §7.1 Story 行 / §10.2 持久来源,
|
|
19
|
+
// 任务 21):onStoreDocument 快照落库后,把 entity:story room 的权威 Y.Doc
|
|
20
|
+
// 回写 Story 业务列——description(Text 列 {html, markdown} JSON 串)+ 8 字段
|
|
21
|
+
// (name/state/priority/assigneeId/startDate/targetDate/labelIds/parentId,
|
|
22
|
+
// 与 web 写端 STORY_COLLAB_FIELDS 一致,交接锚点 M①)+ StoryActivity 活动
|
|
23
|
+
// (§10.2:归属作者 userId + 变更流水 metadata;StoryActivity 无 actorType
|
|
24
|
+
// 字段——BugActivity 独有,计划复审口径,零 schema 改动)。
|
|
25
|
+
//
|
|
26
|
+
// 交接锚点 M 逐条落实:
|
|
27
|
+
// ① 8 字段 + description 全覆盖(labels 是 StoryLabel[] 关系表——diff 同步
|
|
28
|
+
// 子行增删,非单列 update);
|
|
29
|
+
// ② 同事务内 story.update 后用「回读的 updatedAt」显式设 CollabDocument.updatedAt
|
|
30
|
+
// (两行各自 new Date() 有毫秒差 → T14 的 doc.updatedAt <= existing.updatedAt
|
|
31
|
+
// 判定误判旁路写入 → 重种子化炸掉刚导出的协同历史);
|
|
32
|
+
// ③ labels diff 同步(M③,同①);
|
|
33
|
+
// ④ startDate/targetDate 时区口径:Y 侧 yyyy-MM-dd 字符串 ↔ DB UTC 午夜
|
|
34
|
+
// Date(见 dateFromYmd/ymdFromDate 注释),与 web 直写路径
|
|
35
|
+
// `new Date("yyyy-MM-dd")` 的解析行为一致,往返对称。
|
|
36
|
+
//
|
|
37
|
+
// 挂载模式参照 T16(exporters/knowledge.ts):注册表 kind 路由 + 存在性复查
|
|
38
|
+
// (幽灵 room 双重防御的第二道)+ 归属统计。快照无字段值(key undefined)=
|
|
39
|
+
// 「Y 无意见」→ 不触碰该列;显式 null = 清空。防御性 FK 复核(parent/assignee/
|
|
40
|
+
// label 引用不存在时跳过该字段并 warn,防整事务被 FK 违反炸掉)。
|
|
41
|
+
//
|
|
42
|
+
// 系统身份口径:直连 prisma 写业务列与活动,不经 owner-only serverFn
|
|
43
|
+
// (brief 步骤 2/3/4 授权,与 knowledge exporter 一致)。共享写入口
|
|
44
|
+
// writeStoryColumns 同时被 /internal/apply 的离线直落路径(internal-apply.ts)
|
|
45
|
+
// 复用——同一 diff/活动/touch 语义单源。
|
|
46
|
+
//
|
|
47
|
+
// DOM 纪律:yDocToContent 依赖浏览器 DOM 全局;ensureServerDom 懒加载 jsdom
|
|
48
|
+
// 注入(复用 knowledge 导出器的实现)。
|
|
49
|
+
|
|
50
|
+
import type { CollabRoomName } from "@allbluecn/collab-core/rooms";
|
|
51
|
+
import { buildRoomName } from "@allbluecn/collab-core/rooms";
|
|
52
|
+
import { yDocToContent } from "@allbluecn/collab-core/tiptap-export";
|
|
53
|
+
import { createKnowledgeExtensions } from "@allbluecn/collab-core/knowledge-schema";
|
|
54
|
+
import { createKnowledgeDocAdditions } from "@allbluecn/collab-core/knowledge-additions";
|
|
55
|
+
import type * as Y from "yjs";
|
|
56
|
+
import {
|
|
57
|
+
computeAuthorAttribution,
|
|
58
|
+
registerExporter,
|
|
59
|
+
registerRoomGuard,
|
|
60
|
+
type CollabAuthorStat,
|
|
61
|
+
} from "../exporters";
|
|
62
|
+
import { ensureServerDom } from "./knowledge";
|
|
63
|
+
|
|
64
|
+
// ── Y 结构契约常量(锚点 L;与 web bindings/fields.ts 镜像,apps 不可互 import)──
|
|
65
|
+
|
|
66
|
+
/** 字段值所在根 Y.Map 的 key(web 写端 COLLAB_FIELDS_MAP_KEY 的镜像) */
|
|
67
|
+
// 枚举白名单(web 侧 validator 镜像,apps 不互 import——变更需双侧同步)
|
|
68
|
+
const COLLAB_STORY_STATE_VALUES = new Set(["backlog", "todo", "in_progress", "done", "cancelled"]);
|
|
69
|
+
const COLLAB_STORY_PRIORITY_VALUES = new Set(["urgent", "high", "medium", "low", "none"]);
|
|
70
|
+
|
|
71
|
+
export const COLLAB_FIELDS_MAP_KEY = "fields";
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 协同字段清单(web 写端 STORY_COLLAB_FIELDS 的镜像,交接锚点 M①)。
|
|
75
|
+
* 两侧必须同步维护——exporter 漏字段 = 协同编辑在落库时丢失。
|
|
76
|
+
*/
|
|
77
|
+
export const COLLAB_STORY_FIELDS = [
|
|
78
|
+
"name",
|
|
79
|
+
"state",
|
|
80
|
+
"priority",
|
|
81
|
+
"assigneeId",
|
|
82
|
+
"startDate",
|
|
83
|
+
"targetDate",
|
|
84
|
+
"labelIds",
|
|
85
|
+
"parentId",
|
|
86
|
+
] as const;
|
|
87
|
+
|
|
88
|
+
export type CollabStoryField = (typeof COLLAB_STORY_FIELDS)[number];
|
|
89
|
+
|
|
90
|
+
/** 字段 patch(只含出现的 key;undefined key = Y 无意见不触碰) */
|
|
91
|
+
export type StoryFieldsPatch = Partial<Record<CollabStoryField, unknown>>;
|
|
92
|
+
|
|
93
|
+
// ── 值转换(往返对称,M④)─────────────────────────────────────────────
|
|
94
|
+
|
|
95
|
+
/** yyyy-MM-dd(Y 写端 DateEditor 的 format 产物)→ UTC 午夜 Date */
|
|
96
|
+
export function dateFromYmd(value: string): Date | null {
|
|
97
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
|
|
98
|
+
const date = new Date(`${value}T00:00:00.000Z`);
|
|
99
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Date → yyyy-MM-dd(UTC 口径;与 dateFromYmd 往返对称) */
|
|
103
|
+
export function ymdFromDate(date: Date): string {
|
|
104
|
+
return date.toISOString().slice(0, 10);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 解析 Story.description(Text 列)为 {html, markdown}。
|
|
109
|
+
* 与 web components/story/types.ts parseStoryDescription 及 server/collab/seed.ts
|
|
110
|
+
* extractStoryDescriptionHtml 同一口径的镜像(apps 不可互 import):JSON 串
|
|
111
|
+
* {html, markdown} → 原值;历史裸串 → {html: 裸串, markdown: 裸串};null → 空轨。
|
|
112
|
+
*/
|
|
113
|
+
export function parseStoryDescription(
|
|
114
|
+
description: string | null,
|
|
115
|
+
): { html: string; markdown: string } {
|
|
116
|
+
if (!description) return { html: "", markdown: "" };
|
|
117
|
+
try {
|
|
118
|
+
const parsed = JSON.parse(description) as { html?: unknown; markdown?: unknown };
|
|
119
|
+
if (typeof parsed.html === "string") {
|
|
120
|
+
const markdown = typeof parsed.markdown === "string" ? parsed.markdown : parsed.html;
|
|
121
|
+
return { html: parsed.html, markdown };
|
|
122
|
+
}
|
|
123
|
+
} catch {
|
|
124
|
+
// 历史裸串兜底
|
|
125
|
+
}
|
|
126
|
+
return { html: description, markdown: description };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 编辑器空文档产物判定(与 seed.ts extractStoryDescriptionHtml 的「无内容」
|
|
131
|
+
* 口径一致):description HTML 为空产物时业务列写 null(旁路清空语义),
|
|
132
|
+
* 非 null 时写 serializeStoryDescription 的 JSON 串。bug/case 导出器复用
|
|
133
|
+
* (Bug.description 与 Story.description 存储同构)。
|
|
134
|
+
*/
|
|
135
|
+
export function isEmptyEditorHtml(html: string): boolean {
|
|
136
|
+
const trimmed = html.trim();
|
|
137
|
+
return trimmed === "" || trimmed === "<p></p>" || trimmed === "<p><br></p>";
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** 与 web 种子化完全同一扩展组合(默认集 + 追加集)——漂移 = round-trip 丢内容 */
|
|
141
|
+
export function storyDocExtensions() {
|
|
142
|
+
return [...createKnowledgeExtensions(), ...createKnowledgeDocAdditions()];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ── 共享写入口:diff → 业务列 + 活动 + 快照 touch ─────────────────────
|
|
146
|
+
|
|
147
|
+
type PrismaClient = typeof import("@allbluecn/database");
|
|
148
|
+
/** $transaction 回调的 tx 类型(story-transfer.ts 同款推导) */
|
|
149
|
+
export type StoryTx = Parameters<Parameters<PrismaClient["prisma"]["$transaction"]>[0]>[0];
|
|
150
|
+
|
|
151
|
+
/** description + 字段 patch 的统一入参(undefined = 不触碰该面) */
|
|
152
|
+
export interface StoryColumnWrite {
|
|
153
|
+
/** description 目标 HTML(写端 parseStoryDescription 产物);undefined 不触碰 */
|
|
154
|
+
descriptionHtml?: string;
|
|
155
|
+
/** description 目标 markdown(与 html 同轨成对;缺省回退 html) */
|
|
156
|
+
descriptionMarkdown?: string;
|
|
157
|
+
/** 字段 patch;undefined / 空对象不触碰 */
|
|
158
|
+
fields?: StoryFieldsPatch;
|
|
159
|
+
/** 活动归属作者(null = 无归属不写活动,宁缺勿错——knowledge 先例) */
|
|
160
|
+
actor: string | null;
|
|
161
|
+
/** 活动附加 metadata(exporter 传 perAuthor/totalBytes 归属统计) */
|
|
162
|
+
activityExtra?: Record<string, unknown>;
|
|
163
|
+
/**
|
|
164
|
+
* 锚点 M②:true(exporter)= 同事务显式 touch CollabDocument.updatedAt 为
|
|
165
|
+
* story 回读值(防 T14 误判旁路写触发重种子化);false(internal-apply 离线
|
|
166
|
+
* 直落)= 不触碰——旁路写必须让业务列反超快照,重种子化兜底才有正确输入。
|
|
167
|
+
*/
|
|
168
|
+
touchSnapshot: boolean;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 协同活动动作名(web 端 activity-timeline 对未知 action 回退原样展示) */
|
|
172
|
+
export const COLLAB_STORY_UPDATE_ACTION = "collab_update";
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* 把「Y/patch 目标态」diff 进 Story 业务列(单事务内调用):
|
|
176
|
+
* 存在性复查 → FK 防御复核 → diff 建数据(无变化即止,不 bump updatedAt)
|
|
177
|
+
* → story.update → StoryActivity(归属作者 + changedFields 流水)→
|
|
178
|
+
* 可选 CollabDocument.updatedAt 显式 touch(M②)。
|
|
179
|
+
* 供 story exporter(Y 全量态)与 internal-apply 离线直落(patch 增量)复用。
|
|
180
|
+
*/
|
|
181
|
+
export async function writeStoryColumns(
|
|
182
|
+
tx: StoryTx,
|
|
183
|
+
opts: { storyId: string; roomName: string } & StoryColumnWrite,
|
|
184
|
+
): Promise<void> {
|
|
185
|
+
const row = await tx.story.findUnique({
|
|
186
|
+
where: { id: opts.storyId },
|
|
187
|
+
select: {
|
|
188
|
+
name: true,
|
|
189
|
+
state: true,
|
|
190
|
+
priority: true,
|
|
191
|
+
assigneeId: true,
|
|
192
|
+
startDate: true,
|
|
193
|
+
targetDate: true,
|
|
194
|
+
parentId: true,
|
|
195
|
+
description: true,
|
|
196
|
+
labels: { select: { labelId: true } },
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
// 幽灵兜底(首道防线是 store/load 守卫):实体已删则整体跳过
|
|
200
|
+
if (!row) return;
|
|
201
|
+
|
|
202
|
+
const data: Record<string, unknown> = {};
|
|
203
|
+
const changedFields: string[] = [];
|
|
204
|
+
// 内容(描述/标题)是否变更——活动写 content_edited 时间锚(stale 窄口径判定源)
|
|
205
|
+
let contentEdited = false;
|
|
206
|
+
|
|
207
|
+
// description({html, markdown} JSON 串;空产物 → null)。两侧都按「空产物」
|
|
208
|
+
// 归一比较,防空房间反复 store 产出幻影 diff(bump updatedAt + 空活动)。
|
|
209
|
+
if (opts.descriptionHtml !== undefined) {
|
|
210
|
+
const html = opts.descriptionHtml;
|
|
211
|
+
const markdown = opts.descriptionMarkdown ?? html;
|
|
212
|
+
const current = parseStoryDescription(row.description);
|
|
213
|
+
const currentEmpty =
|
|
214
|
+
current.html.trim() === "" || isEmptyEditorHtml(current.html);
|
|
215
|
+
const newEmpty = isEmptyEditorHtml(html);
|
|
216
|
+
const changed = newEmpty ? !currentEmpty : current.html !== html;
|
|
217
|
+
if (changed) {
|
|
218
|
+
changedFields.push("description");
|
|
219
|
+
data.description = newEmpty ? null : JSON.stringify({ html, markdown });
|
|
220
|
+
// 内容编辑时间锚(测试用例 stale 判定专用,窄口径=描述/标题)
|
|
221
|
+
contentEdited = true;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const fields = opts.fields ?? {};
|
|
226
|
+
const has = (key: CollabStoryField) => fields[key] !== undefined;
|
|
227
|
+
|
|
228
|
+
// name(空值防御:web 直写路径 min(1),Y 侧异常空串不落库)
|
|
229
|
+
if (has("name")) {
|
|
230
|
+
const name = fields.name;
|
|
231
|
+
if (typeof name === "string" && name.trim() !== "") {
|
|
232
|
+
if (name !== row.name) {
|
|
233
|
+
changedFields.push("name");
|
|
234
|
+
data.name = name;
|
|
235
|
+
contentEdited = true;
|
|
236
|
+
}
|
|
237
|
+
} else {
|
|
238
|
+
console.warn(`[collab-exporters] story 字段 name 非法(${typeof name}),跳过 storyId=${opts.storyId}`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// state/priority 白名单(web story-crud validator 镜像,apps 不互 import):
|
|
243
|
+
// Y 字段可经绕过 validator 的路径写入(internal-apply/离线 patch),导出兜底收敛
|
|
244
|
+
if (has("state") && typeof fields.state === "string" && fields.state !== row.state) {
|
|
245
|
+
if (!COLLAB_STORY_STATE_VALUES.has(fields.state)) {
|
|
246
|
+
console.warn(`[collab-exporters] story 字段 state 非法(${fields.state}),跳过 storyId=${opts.storyId}`);
|
|
247
|
+
} else {
|
|
248
|
+
changedFields.push("state");
|
|
249
|
+
data.state = fields.state;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (has("priority") && typeof fields.priority === "string" && fields.priority !== row.priority) {
|
|
253
|
+
if (!COLLAB_STORY_PRIORITY_VALUES.has(fields.priority)) {
|
|
254
|
+
console.warn(`[collab-exporters] story 字段 priority 非法(${fields.priority}),跳过 storyId=${opts.storyId}`);
|
|
255
|
+
} else {
|
|
256
|
+
changedFields.push("priority");
|
|
257
|
+
data.priority = fields.priority;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// assigneeId(FK 防御:引用不存在时跳过,防 P2003 炸整事务)。写入用关系
|
|
262
|
+
// 形态(Prisma checked input:标量 FK 与嵌套关系写不可混用)
|
|
263
|
+
if (has("assigneeId")) {
|
|
264
|
+
const assigneeId = fields.assigneeId as string | null;
|
|
265
|
+
if (assigneeId !== row.assigneeId) {
|
|
266
|
+
if (assigneeId !== null) {
|
|
267
|
+
const user = await tx.user.findUnique({ where: { id: assigneeId }, select: { id: true } });
|
|
268
|
+
if (!user) {
|
|
269
|
+
console.warn(`[collab-exporters] story assigneeId 引用不存在(${assigneeId}),跳过 storyId=${opts.storyId}`);
|
|
270
|
+
} else {
|
|
271
|
+
changedFields.push("assigneeId");
|
|
272
|
+
data.assignee = { connect: { id: assigneeId } };
|
|
273
|
+
}
|
|
274
|
+
} else {
|
|
275
|
+
changedFields.push("assigneeId");
|
|
276
|
+
data.assignee = { disconnect: true };
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// startDate / targetDate(M④:yyyy-MM-dd ↔ UTC 午夜,往返对称)
|
|
282
|
+
for (const key of ["startDate", "targetDate"] as const) {
|
|
283
|
+
if (!has(key)) continue;
|
|
284
|
+
const raw = fields[key] as string | null;
|
|
285
|
+
if (raw === null) {
|
|
286
|
+
if (row[key] !== null) {
|
|
287
|
+
changedFields.push(key);
|
|
288
|
+
data[key] = null;
|
|
289
|
+
}
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const date = typeof raw === "string" ? dateFromYmd(raw) : null;
|
|
293
|
+
if (!date) {
|
|
294
|
+
console.warn(`[collab-exporters] story 字段 ${key} 非日期串(${String(raw)}),跳过 storyId=${opts.storyId}`);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (row[key]?.getTime() !== date.getTime()) {
|
|
298
|
+
changedFields.push(key);
|
|
299
|
+
data[key] = date;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// labelIds(M③:StoryLabel[] 关系表 diff 同步子行;FK 防御过滤已删标签)
|
|
304
|
+
if (has("labelIds")) {
|
|
305
|
+
const raw = fields.labelIds;
|
|
306
|
+
if (Array.isArray(raw)) {
|
|
307
|
+
const target = [...new Set(raw.filter((id): id is string => typeof id === "string"))];
|
|
308
|
+
const current = row.labels.map((l) => l.labelId);
|
|
309
|
+
const sameSet =
|
|
310
|
+
target.length === current.length && target.every((id) => current.includes(id));
|
|
311
|
+
if (!sameSet) {
|
|
312
|
+
const existing = await tx.label.findMany({
|
|
313
|
+
where: { id: { in: target } },
|
|
314
|
+
select: { id: true },
|
|
315
|
+
});
|
|
316
|
+
const valid = new Set(existing.map((l) => l.id));
|
|
317
|
+
const missing = target.filter((id) => !valid.has(id));
|
|
318
|
+
if (missing.length > 0) {
|
|
319
|
+
console.warn(
|
|
320
|
+
`[collab-exporters] story labelIds 引用不存在的标签(${missing.join(",")}),已过滤 storyId=${opts.storyId}`,
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
const toCreate = target.filter((id) => valid.has(id) && !current.includes(id));
|
|
324
|
+
const toDelete = current.filter((id) => !target.includes(id));
|
|
325
|
+
if (toCreate.length > 0 || toDelete.length > 0) {
|
|
326
|
+
changedFields.push("labelIds");
|
|
327
|
+
data.labels = {
|
|
328
|
+
...(toDelete.length > 0 && { deleteMany: { labelId: { in: toDelete } } }),
|
|
329
|
+
...(toCreate.length > 0 && { create: toCreate.map((labelId) => ({ labelId })) }),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
} else {
|
|
334
|
+
console.warn(`[collab-exporters] story 字段 labelIds 非数组,跳过 storyId=${opts.storyId}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// parentId(自环/FK 防御;关系形态 connect/disconnect)
|
|
339
|
+
if (has("parentId")) {
|
|
340
|
+
const parentId = fields.parentId as string | null;
|
|
341
|
+
if (parentId !== row.parentId) {
|
|
342
|
+
if (parentId !== null) {
|
|
343
|
+
if (parentId === opts.storyId) {
|
|
344
|
+
console.warn(`[collab-exporters] story parentId 自环,跳过 storyId=${opts.storyId}`);
|
|
345
|
+
} else {
|
|
346
|
+
const parent = await tx.story.findUnique({
|
|
347
|
+
where: { id: parentId },
|
|
348
|
+
select: { id: true },
|
|
349
|
+
});
|
|
350
|
+
if (!parent) {
|
|
351
|
+
console.warn(`[collab-exporters] story parentId 引用不存在(${parentId}),跳过 storyId=${opts.storyId}`);
|
|
352
|
+
} else {
|
|
353
|
+
changedFields.push("parentId");
|
|
354
|
+
data.parent = { connect: { id: parentId } };
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
} else {
|
|
358
|
+
changedFields.push("parentId");
|
|
359
|
+
data.parent = { disconnect: true };
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// 无 diff 即止:不 bump updatedAt(避免无谓的重种子化判定输入)
|
|
365
|
+
if (changedFields.length === 0) return;
|
|
366
|
+
|
|
367
|
+
const updated = await tx.story.update({
|
|
368
|
+
where: { id: opts.storyId },
|
|
369
|
+
data,
|
|
370
|
+
select: { updatedAt: true },
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
// §10.2 活动(归属作者 + 变更流水):actor null 不写(宁缺勿错)
|
|
374
|
+
// StoryActivity.userId 必填:actor 为 null(SDK/系统写入)时无归属,宁缺勿错
|
|
375
|
+
if (contentEdited && opts.actor) {
|
|
376
|
+
await tx.storyActivity.create({
|
|
377
|
+
data: {
|
|
378
|
+
storyId: opts.storyId,
|
|
379
|
+
userId: opts.actor,
|
|
380
|
+
action: "content_edited",
|
|
381
|
+
field: null,
|
|
382
|
+
oldValue: null,
|
|
383
|
+
newValue: null,
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
if (opts.actor) {
|
|
388
|
+
await tx.storyActivity.create({
|
|
389
|
+
data: {
|
|
390
|
+
storyId: opts.storyId,
|
|
391
|
+
userId: opts.actor,
|
|
392
|
+
action: COLLAB_STORY_UPDATE_ACTION,
|
|
393
|
+
metadata: {
|
|
394
|
+
source: "collab",
|
|
395
|
+
summary: "更新了需求",
|
|
396
|
+
changedFields,
|
|
397
|
+
...(opts.activityExtra ?? {}),
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// 锚点 M②:同事务显式 touch 快照 updatedAt = story 回读值(逐字节相等 →
|
|
404
|
+
// T14 的 `doc.updatedAt <= existing.updatedAt` 直读判定成立,不误触发重种子化)。
|
|
405
|
+
// 快照行尚不存在(首次落库 export 先于快照 upsert)时 updateMany 计 0,跳过
|
|
406
|
+
// ——随后的快照 upsert 以全新 updatedAt 建行,天然 ≥ story.updatedAt。
|
|
407
|
+
if (opts.touchSnapshot) {
|
|
408
|
+
await tx.collabDocument.updateMany({
|
|
409
|
+
where: { roomName: opts.roomName },
|
|
410
|
+
data: { updatedAt: updated.updatedAt },
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ── 导出器主体 ────────────────────────────────────────────────────────
|
|
416
|
+
|
|
417
|
+
/** 幽灵 room 守卫:Story 行仍存在 → true(Story 硬删,无软删位) */
|
|
418
|
+
async function assertStoryRoomAlive(
|
|
419
|
+
room: Extract<CollabRoomName, { kind: "entity-story" }>,
|
|
420
|
+
): Promise<boolean> {
|
|
421
|
+
const db = await import("@allbluecn/database");
|
|
422
|
+
const story = await db.prisma.story.findUnique({
|
|
423
|
+
where: { id: room.storyId },
|
|
424
|
+
select: { id: true },
|
|
425
|
+
});
|
|
426
|
+
return story != null;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* 从 Y.Doc 读取 8 字段 patch(只收 COLLAB_STORY_FIELDS 内出现的 key;
|
|
431
|
+
* 意外多余 key 忽略——客户端契约外的值不落库)。
|
|
432
|
+
*/
|
|
433
|
+
export function readFieldsPatch(doc: Y.Doc): StoryFieldsPatch {
|
|
434
|
+
const map = doc.getMap<unknown>(COLLAB_FIELDS_MAP_KEY);
|
|
435
|
+
const patch: StoryFieldsPatch = {};
|
|
436
|
+
for (const key of COLLAB_STORY_FIELDS) {
|
|
437
|
+
const value = map.get(key);
|
|
438
|
+
if (value !== undefined) patch[key] = value;
|
|
439
|
+
}
|
|
440
|
+
return patch;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async function exportStory(input: {
|
|
444
|
+
room: CollabRoomName;
|
|
445
|
+
doc: Y.Doc;
|
|
446
|
+
authorStats: CollabAuthorStat[];
|
|
447
|
+
}): Promise<void> {
|
|
448
|
+
const room = input.room as Extract<CollabRoomName, { kind: "entity-story" }>;
|
|
449
|
+
const db = await import("@allbluecn/database");
|
|
450
|
+
// 回写前复核实体存在(防已删实体被回写复活——锚点 J 第二道防线)
|
|
451
|
+
const alive = await db.prisma.story.findUnique({
|
|
452
|
+
where: { id: room.storyId },
|
|
453
|
+
select: { id: true },
|
|
454
|
+
});
|
|
455
|
+
if (!alive) return;
|
|
456
|
+
|
|
457
|
+
await ensureServerDom();
|
|
458
|
+
// description:default fragment → {html, markdown}(与种子化同一扩展组合)
|
|
459
|
+
const content = yDocToContent(input.doc, storyDocExtensions());
|
|
460
|
+
const fields = readFieldsPatch(input.doc);
|
|
461
|
+
|
|
462
|
+
// per-author 占比(§10.2,共享助手单源):随活动 metadata 落流水
|
|
463
|
+
const { primary, totalBytes, perAuthor } = computeAuthorAttribution(input.authorStats);
|
|
464
|
+
|
|
465
|
+
await db.prisma.$transaction((tx) =>
|
|
466
|
+
writeStoryColumns(tx, {
|
|
467
|
+
storyId: room.storyId,
|
|
468
|
+
roomName: buildRoomName({ kind: "entity-story", storyId: room.storyId }),
|
|
469
|
+
descriptionHtml: content.html,
|
|
470
|
+
descriptionMarkdown: content.markdown,
|
|
471
|
+
fields,
|
|
472
|
+
actor: primary,
|
|
473
|
+
activityExtra: { perAuthor, totalBytes },
|
|
474
|
+
touchSnapshot: true,
|
|
475
|
+
}),
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** 注册 Story 导出器 + 幽灵 room 守卫(生产经 startCollabServerFromEnv 调用) */
|
|
480
|
+
export function registerStoryCollab(): void {
|
|
481
|
+
registerExporter("entity-story", exportStory);
|
|
482
|
+
registerRoomGuard("entity-story", assertStoryRoomAlive);
|
|
483
|
+
}
|
package/src/exporters.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
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
|
+
// 回写适配器注册表(§3.2 onStoreDocument 末段 / §5.2 回写导出器):
|
|
19
|
+
// 快照落库后按 room kind 分发,把 Y.Doc 导出为业务格式回写业务列
|
|
20
|
+
// (TipTap 系 → html/markdown、画布 → LeaferJSONPackage 等)。
|
|
21
|
+
//
|
|
22
|
+
// P2 起逐模块接入(首站知识库见 ./exporters/knowledge.ts),接入方调
|
|
23
|
+
// registerExporter(kind, exporter) 即可,无需改动 persistence。
|
|
24
|
+
// 同文件维护 room 装载守卫注册表(registerRoomGuard,交接锚点 J:已删
|
|
25
|
+
// 实体的幽灵 room 不得装载/落库/回写)。
|
|
26
|
+
|
|
27
|
+
import type { CollabRoomName } from "@allbluecn/collab-core/rooms";
|
|
28
|
+
import type * as Y from "yjs";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 归属统计行(§10.2「per-author 字节/操作占比」):由 persistence 在
|
|
32
|
+
* onStoreDocument flush 批次上统计,随导出器入参下发。authorId=null 为
|
|
33
|
+
* 未能归属的更新(尽力归属的失败态)。
|
|
34
|
+
*/
|
|
35
|
+
export interface CollabAuthorStat {
|
|
36
|
+
authorId: string | null;
|
|
37
|
+
/** 该作者的 update 条数 */
|
|
38
|
+
updates: number;
|
|
39
|
+
/** 该作者 update 的字节量(占比分母含未归属部分) */
|
|
40
|
+
bytes: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* per-author 占比明细行(活动 metadata.perAuthor 的存储形态)。⚠ 类型别名
|
|
45
|
+
* 而非 interface:Prisma InputJsonObject 的赋值依赖隐式索引签名,interface
|
|
46
|
+
* 不具备(type alias 具备)——改动前先跑 `npx tsc --noEmit` 验证落库路径。
|
|
47
|
+
*/
|
|
48
|
+
export type CollabPerAuthorEntry = {
|
|
49
|
+
authorId: string | null;
|
|
50
|
+
updates: number;
|
|
51
|
+
bytes: number;
|
|
52
|
+
/** 字节占比(4 位小数;totalBytes=0 时为 0) */
|
|
53
|
+
share: number;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** 归属统计汇总:主作者 + 总字节 + per-author 明细(活动 metadata 单一形态) */
|
|
57
|
+
export interface CollabAuthorAttribution {
|
|
58
|
+
/** 主作者(字节占比最高者,平局比条数);全批次无归属时 null(宁缺勿错) */
|
|
59
|
+
primary: string | null;
|
|
60
|
+
/** 批次总字节(占比分母含未归属部分) */
|
|
61
|
+
totalBytes: number;
|
|
62
|
+
perAuthor: CollabPerAuthorEntry[];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 归属统计汇总(§10.2;knowledge/story/bug/case/design 五处导出器的同构
|
|
67
|
+
* 四段式单源化):主作者 = 已归属(authorId 非 null)行按 bytes 降序、
|
|
68
|
+
* updates 降序取首;全部无归属 → null(调用方按「宁缺勿错」跳过活动)。
|
|
69
|
+
*/
|
|
70
|
+
export function computeAuthorAttribution(authorStats: CollabAuthorStat[]): CollabAuthorAttribution {
|
|
71
|
+
const attributed = authorStats.filter((s) => s.authorId != null);
|
|
72
|
+
const totalBytes = authorStats.reduce((sum, s) => sum + s.bytes, 0);
|
|
73
|
+
const primary =
|
|
74
|
+
attributed
|
|
75
|
+
.slice()
|
|
76
|
+
.sort((a, b) => b.bytes - a.bytes || b.updates - a.updates)[0]?.authorId ?? null;
|
|
77
|
+
const perAuthor: CollabPerAuthorEntry[] = authorStats.map((s) => ({
|
|
78
|
+
authorId: s.authorId,
|
|
79
|
+
updates: s.updates,
|
|
80
|
+
bytes: s.bytes,
|
|
81
|
+
share: totalBytes > 0 ? Number((s.bytes / totalBytes).toFixed(4)) : 0,
|
|
82
|
+
}));
|
|
83
|
+
return { primary, totalBytes, perAuthor };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 回写导出器:收「类型化 room + 服务端权威 Y.Doc + 本轮归属统计」,自行读取所需内容 */
|
|
87
|
+
export type CollabExporter = (input: {
|
|
88
|
+
room: CollabRoomName;
|
|
89
|
+
doc: Y.Doc;
|
|
90
|
+
authorStats: CollabAuthorStat[];
|
|
91
|
+
}) => Promise<void>;
|
|
92
|
+
|
|
93
|
+
/** room kind → 导出器;每 kind 至多一个(后注册覆盖先注册) */
|
|
94
|
+
const registry = new Map<CollabRoomName["kind"], CollabExporter>();
|
|
95
|
+
|
|
96
|
+
/** 注册(或替换)某 room kind 的导出器(P2 起各模块接入时调用) */
|
|
97
|
+
export function registerExporter(
|
|
98
|
+
kind: CollabRoomName["kind"],
|
|
99
|
+
exporter: CollabExporter,
|
|
100
|
+
): void {
|
|
101
|
+
registry.set(kind, exporter);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 清空注册表(测试隔离用) */
|
|
105
|
+
export function resetExporters(): void {
|
|
106
|
+
registry.clear();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* room 装载/落库守卫(任务 16,交接锚点 J):校验 room 对应业务实体是否仍
|
|
111
|
+
* 存在(未删除)。返回 false = 实体已不存在(幽灵 room),装载方应返回空
|
|
112
|
+
* doc 并断开连接、落库方应整体跳过(防已删实体被内存态/回写复活)。
|
|
113
|
+
* guard 查询失败按 fail-open 处理(放行 + 记日志)——协作可用性优先,与
|
|
114
|
+
* persistence 的整体故障口径一致。
|
|
115
|
+
*/
|
|
116
|
+
export type CollabRoomGuard<K extends CollabRoomName["kind"]> = (
|
|
117
|
+
room: Extract<CollabRoomName, { kind: K }>,
|
|
118
|
+
) => Promise<boolean>;
|
|
119
|
+
|
|
120
|
+
/** room kind → 守卫;每 kind 至多一个(后注册覆盖先注册)。存储为宽签名,调用侧按 kind 分发 */
|
|
121
|
+
const guardRegistry = new Map<CollabRoomName["kind"], (room: CollabRoomName) => Promise<boolean>>();
|
|
122
|
+
|
|
123
|
+
/** 注册(或替换)某 room kind 的装载守卫 */
|
|
124
|
+
export function registerRoomGuard<K extends CollabRoomName["kind"]>(
|
|
125
|
+
kind: K,
|
|
126
|
+
guard: CollabRoomGuard<K>,
|
|
127
|
+
): void {
|
|
128
|
+
// 守卫收窄子集(Extract)→ 存储宽联合:参数逆变方向的收窄注册,
|
|
129
|
+
// 运行时仅以同 kind room 调用(registry 按 kind 键分发)
|
|
130
|
+
guardRegistry.set(kind, guard as (room: CollabRoomName) => Promise<boolean>);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 清空守卫注册表(测试隔离用) */
|
|
134
|
+
export function resetRoomGuards(): void {
|
|
135
|
+
guardRegistry.clear();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 执行 room 守卫。未注册该 kind = 实体存在性不归 collab 管(如 presence/
|
|
140
|
+
* share room),一律放行;guard 抛错 fail-open(放行 + 记日志)。
|
|
141
|
+
*/
|
|
142
|
+
export async function runRoomGuard(room: CollabRoomName): Promise<boolean> {
|
|
143
|
+
const guard = guardRegistry.get(room.kind);
|
|
144
|
+
if (!guard) return true;
|
|
145
|
+
try {
|
|
146
|
+
return await guard(room);
|
|
147
|
+
} catch (err) {
|
|
148
|
+
console.error(`[collab-exporters] room 守卫查询失败(fail-open 放行)kind=${room.kind}:`, err);
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 快照落库后分发导出器。未注册该 kind 时为零成本 no-op;
|
|
155
|
+
* 导出器抛错只记日志不上抛——回写是持久化的下游增强,
|
|
156
|
+
* 失败不能阻断快照落库本身(业务列下次落库仍会重试)。
|
|
157
|
+
*/
|
|
158
|
+
export async function runExporters(
|
|
159
|
+
room: CollabRoomName,
|
|
160
|
+
doc: Y.Doc,
|
|
161
|
+
authorStats: CollabAuthorStat[] = [],
|
|
162
|
+
): Promise<void> {
|
|
163
|
+
const exporter = registry.get(room.kind);
|
|
164
|
+
if (!exporter) return;
|
|
165
|
+
try {
|
|
166
|
+
await exporter({ room, doc, authorStats });
|
|
167
|
+
} catch (err) {
|
|
168
|
+
console.error(
|
|
169
|
+
`[collab-exporters] 导出失败 kind=${room.kind},业务列回写跳过(下次落库重试):`,
|
|
170
|
+
err,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
}
|