@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.
- 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
package/README.md
CHANGED
|
@@ -1,3 +1,127 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @allbluecn/collab-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
AllBlue 多人协作的独立 WebSocket 服务(Yjs + Hocuspocus 4.7),规格见协作计划 §3(服务结构)/§4.2(ticket 验签)。
|
|
4
|
+
|
|
5
|
+
- **鉴权**:连接时校验 `@allbluecn/collab-core/ticket` 的 HMAC ticket(验签 + exp + `ticket.room === 连接 room`),通过后按 `role` 落 `readOnly`(view 连接的写入被服务端丢弃并 nack,不广播)。
|
|
6
|
+
- **内部应用通道**(§5.3 写入路由协议,任务 17):`POST /internal/apply`(与 WS 同端口;内部 HMAC 信封见 `@allbluecn/collab-core/internal`,域 `collab-internal-apply:v1`,ts 偏移 >60s 拒)。web 写入门卫在 CollabDocument 存在时把旁路 content 写入转发到此:room 在线 → 系统 client(userId=actor)整文档 replace 应用到 Y 并广播,落库走 onStoreDocument 统一链路;room 离线 → 直接落库业务列(视为旁路写,重种子化兜底);实体已删 → 409。非内部路由的原 HTTP 行为(`Welcome to Hocuspocus!`)不受监听器置换影响。
|
|
7
|
+
- **share room 上限**:单 `share:{token}` room 连接上限 **50**(§9),超限拒绝新连接(拒绝语义同鉴权失败,客户端收 `authenticationFailed`,reason `room-limit`);`COLLAB_SHARE_ROOM_LIMIT` 可配置(0 = 不设上限),非 share room 不受限。
|
|
8
|
+
- **room 注册表**:复用 `@allbluecn/collab-core/rooms` 的 `parseRoomName`(本 app 是纯服务端,直接 import 全部子路径,无客户端隔离约束)。
|
|
9
|
+
- **指标**:`src/metrics.ts` 周期打印连接数 / room 数 / update 体积(`COLLAB_METRICS=off` 关闭)。
|
|
10
|
+
- ⚠️ **单实例边界**:room 文档与 awareness 存单进程内存,多实例部署不共享(横向扩容前须 extension-redis,见 `src/index.ts` 顶注释)。任何部署形态(PM2/Docker/Fly/Railway)都必须保持 **`instances: 1`,禁 cluster 多实例**。
|
|
11
|
+
|
|
12
|
+
## 运行形态(依赖解析决策)
|
|
13
|
+
|
|
14
|
+
`@allbluecn/collab-core` 的 exports 为 **src/*.ts 源码直出**,Node 不能裸跑 .ts,因此:
|
|
15
|
+
|
|
16
|
+
| 场景 | 命令 | 说明 |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| 本地 dev | `pnpm dev`(= `tsx src/index.ts`) | tsx 直跑 TS 源码 |
|
|
19
|
+
| 构建 | `pnpm build`(= esbuild bundle → `dist/index.mjs`) | collab-core 源码随包打入;`@hocuspocus/*`、`yjs`、`@allbluecn/database` external |
|
|
20
|
+
| 生产启动 | `pnpm start`(= `node dist/index.mjs`) | 跑构建产物 |
|
|
21
|
+
|
|
22
|
+
## 环境变量
|
|
23
|
+
|
|
24
|
+
| 变量 | 必填 | 默认 | 说明 |
|
|
25
|
+
|---|---|---|---|
|
|
26
|
+
| `COLLAB_SECRET` | ✅ | — | 与 web 签发端共享的 HMAC 密钥,缺失拒绝启动 |
|
|
27
|
+
| `COLLAB_PORT` | — | `3010` | 监听端口(worktree 并行开发约定 3030) |
|
|
28
|
+
| `DATABASE_URL` | ✅* | — | 持久层落库连接串;仅 `COLLAB_PERSISTENCE=off` 时可缺 |
|
|
29
|
+
| `COLLAB_PERSISTENCE` | — | on | `off` 退回纯内存(重启丢协同快照);开启但缺 `DATABASE_URL` 显式失败 |
|
|
30
|
+
| `COLLAB_SHARE_ROOM_LIMIT` | — | `50` | 单 share room 连接上限(0 = 不设上限) |
|
|
31
|
+
| `COLLAB_METRICS` | — | on | `off` 关闭周期指标日志 |
|
|
32
|
+
| `COLLAB_METRICS_INTERVAL_MS` | — | `60000` | 指标打印周期 |
|
|
33
|
+
| `COLLAB_WEB_URL` | — | — | collab → web 的向量索引重建通知目标(协同落库回写后 fire-and-forget POST `/api/internal/collab-reindex`,HMAC 同 COLLAB_SECRET);缺省时索引滞后直至配置,协作与内容回写不受影响 |
|
|
34
|
+
|
|
35
|
+
\* 生产必填:协作快照/审计是产品承诺,默认开启持久层。
|
|
36
|
+
|
|
37
|
+
env 模板见 `apps/collab/.env.example`(git 入库,写项目根口径 3010)与仓根 `.env.example`。⚠ tsx 直跑不自动加载 `.env`——本地 dev 统一走根 `scripts/dev.sh` 注入(COLLAB_SECRET/COLLAB_PORT/DATABASE_URL);绕过 dev.sh 单跑需自行 export。
|
|
38
|
+
|
|
39
|
+
## 本地开发
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
# 根目录一键起三服务(web 3000 + admin 3001 + collab 3010/3030)
|
|
43
|
+
pnpm dev
|
|
44
|
+
|
|
45
|
+
# 单独起 collab(env 由根 dev.sh 注入;绕过 dev.sh 单跑需自行 export COLLAB_* 与 DATABASE_URL)
|
|
46
|
+
pnpm --filter @allbluecn/collab-server dev
|
|
47
|
+
|
|
48
|
+
# 真实 WS 集成测试(Server port 0 随机端口 + HocuspocusProvider,覆盖鉴权五场景 + share room 上限)
|
|
49
|
+
pnpm --filter @allbluecn/collab-server test:run
|
|
50
|
+
|
|
51
|
+
# 验证服务存活(Hocuspocus 内置 HTTP 响应)
|
|
52
|
+
curl http://localhost:3010 # → "Welcome to Hocuspocus!"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## 部署
|
|
56
|
+
|
|
57
|
+
### 自托管(node-server / PM2 / Docker)
|
|
58
|
+
|
|
59
|
+
同机与 web 部署、nginx 做反代。**WebSocket 升级必须透传**(`Upgrade`/`Connection` 头),且反代读超时要大于 awareness 心跳间隔(Hocuspocus 连接期每 <30s 有消息,nginx 默认 60s 够用,压长更稳):
|
|
60
|
+
|
|
61
|
+
```nginx
|
|
62
|
+
# collab 独立子域方案(推荐):wss://collab.example.com → 127.0.0.1:3010
|
|
63
|
+
server {
|
|
64
|
+
server_name collab.example.com;
|
|
65
|
+
listen 443 ssl;
|
|
66
|
+
# ssl_certificate /etc/letsencrypt/live/collab.example.com/fullchain.pem;
|
|
67
|
+
# ssl_certificate_key /etc/letsencrypt/live/collab.example.com/privkey.pem;
|
|
68
|
+
|
|
69
|
+
location / {
|
|
70
|
+
proxy_pass http://127.0.0.1:3010;
|
|
71
|
+
proxy_http_version 1.1;
|
|
72
|
+
proxy_set_header Upgrade $http_upgrade; # WS 升级必需
|
|
73
|
+
proxy_set_header Connection "upgrade"; # WS 升级必需
|
|
74
|
+
proxy_set_header Host $host;
|
|
75
|
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
76
|
+
proxy_read_timeout 300s; # > awareness 心跳窗口(30s)
|
|
77
|
+
proxy_send_timeout 300s;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
```nginx
|
|
83
|
+
# 同域路径方案:location /collab → 3010(web 侧 VITE_COLLAB_WS_URL 配 wss://example.com/collab)
|
|
84
|
+
location /collab {
|
|
85
|
+
proxy_pass http://127.0.0.1:3010;
|
|
86
|
+
proxy_http_version 1.1;
|
|
87
|
+
proxy_set_header Upgrade $http_upgrade;
|
|
88
|
+
proxy_set_header Connection "upgrade";
|
|
89
|
+
proxy_read_timeout 300s;
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
PM2 形态(**单实例,禁 cluster**——room/awareness 在进程内存):
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
pm2 start dist/index.mjs --name allblue-collab -i 1 --time
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Vercel 生产(web 在 Vercel,collab 独立部署)
|
|
100
|
+
|
|
101
|
+
collab 是有状态 WebSocket 长连接服务,**不能跑在 Vercel 函数上**;独立部署到自有 VPS / Fly.io / Railway,配独立子域:
|
|
102
|
+
|
|
103
|
+
- 域名:`collab.你的域名` → collab 实例;web 端 env 配 `VITE_COLLAB_WS_URL=wss://collab.你的域名`(**生产必须 wss**,https 页面下 ws 会被浏览器 mixed-content 拦截)。
|
|
104
|
+
- Fly.io:`fly launch --no-deploy` 生成 `fly.toml` 后改 `internal_port = 3010`,Fly 边缘自动终止 TLS(浏览器 `wss://` 到实例是普通 tcp/ws);region 固定、`min_machines_running = 1`,**不开多实例**(见单实例边界)。模板参考 Fly 官方 Node 入门(https://fly.io/docs/languages-and-frameworks/node/),可直接用其内置 node builder,也可用 `apps/collab/Dockerfile`(build context 仍为仓库根,见下「Docker 镜像」)。
|
|
105
|
+
- Railway:Node service 用 `apps/collab/Dockerfile`(build context=仓库根)或 Nixpacks(start 命令 `pnpm --filter @allbluecn/collab-server start`),Variables 配 `COLLAB_SECRET`/`DATABASE_URL`,TCP Proxy 暴露 3010 并绑定 `collab.*` 自定义域(Railway 自动 TLS);**Horizontal Scale = 1**。
|
|
106
|
+
- web 服务端 → collab 的 HTTP 内部通道配 `COLLAB_INTERNAL_URL`(同机 `http://127.0.0.1:3010`;Fly/Railway 内网用 `http://<internal-host>:3010`,勿绕公网)。
|
|
107
|
+
|
|
108
|
+
### Docker 镜像
|
|
109
|
+
|
|
110
|
+
Dockerfile 位于 `apps/collab/Dockerfile`(仓根无 Dockerfile),**build context 为仓库根**(workspace 级文件 COPY + `COPY . .`)。三阶段:deps → builder → runner,esbuild 产物 + tini 前台启动。构建(**在仓库根执行**,`-f` 指定文件):
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
docker build -t allblue-collab -f apps/collab/Dockerfile .
|
|
114
|
+
docker run -e COLLAB_SECRET=... -e DATABASE_URL=... -p 3010:3010 allblue-collab
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
> ✅ **三缺口已修复(followup,本机 docker build 实测通过)**:
|
|
118
|
+
> 1. deps 阶段 partial workspace → `COPY --parents` 展开全部 9 个 importer 的 package.json(与 lockfile 对账),`--frozen-lockfile` 不再报漂移。
|
|
119
|
+
> 2. builder 阶段先 `pnpm --filter @allbluecn/database exec prisma generate` 再 typecheck/test/build(collab 消费 generated client 类型面)。
|
|
120
|
+
> 3. `@allbluecn/database` 移出 esbuild external(Prisma 7 prisma-client generator Rust-free,纯 TS 可打包)→ `dist/index.mjs` 自包含持久层,不再依赖 Node 运行时类型剥离。
|
|
121
|
+
|
|
122
|
+
### 部署后自检
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
curl https://collab.你的域名 # → "Welcome to Hocuspocus!"(TLS + 反代链路通)
|
|
126
|
+
# web 端打开任一协同文档,浏览器 DevTools → Network → WS → 101 Switching Protocols
|
|
127
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@allbluecn/collab-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.7",
|
|
4
|
+
"license": "AGPL-3.0-or-later",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"description": "AllBlue Hocuspocus WebSocket 协作服务(Yjs 多人协同;主形态为 web 后端内嵌模块,独立启动为退役回退)",
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"exports": {
|
|
15
|
+
".": "./src/index.ts",
|
|
16
|
+
"./embed": "./src/embed.ts"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@allbluecn/collab-core": "0.2.1",
|
|
20
|
+
"@allbluecn/database": "0.14.11",
|
|
21
|
+
"@hocuspocus/server": "^4.7.0",
|
|
22
|
+
"@tiptap/core": "3.31.3",
|
|
23
|
+
"@tiptap/extension-emoji": "3.31.3",
|
|
24
|
+
"@tiptap/extension-highlight": "3.31.3",
|
|
25
|
+
"@tiptap/extension-horizontal-rule": "3.31.3",
|
|
26
|
+
"@tiptap/extension-image": "3.31.3",
|
|
27
|
+
"@tiptap/extension-list": "3.31.3",
|
|
28
|
+
"@tiptap/extension-mathematics": "3.31.3",
|
|
29
|
+
"@tiptap/extension-mention": "3.31.3",
|
|
30
|
+
"@tiptap/extension-subscript": "3.31.3",
|
|
31
|
+
"@tiptap/extension-superscript": "3.31.3",
|
|
32
|
+
"@tiptap/extension-table": "3.31.3",
|
|
33
|
+
"@tiptap/extension-text-align": "3.31.3",
|
|
34
|
+
"@tiptap/extension-text-style": "3.31.3",
|
|
35
|
+
"@tiptap/extension-unique-id": "3.31.3",
|
|
36
|
+
"@tiptap/markdown": "3.31.3",
|
|
37
|
+
"@tiptap/pm": "3.31.3",
|
|
38
|
+
"@tiptap/starter-kit": "3.31.3",
|
|
39
|
+
"@tiptap/suggestion": "3.31.3",
|
|
40
|
+
"@tiptap/y-tiptap": "3.0.7",
|
|
41
|
+
"jsdom": "^30.1.3",
|
|
42
|
+
"katex": "0.18.7",
|
|
43
|
+
"yjs": "^13.6.33"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@hocuspocus/provider": "^4.7.0",
|
|
47
|
+
"@types/jsdom": "^28.0.3",
|
|
48
|
+
"@types/node": "^26.6.6",
|
|
49
|
+
"esbuild": "^0.28.2",
|
|
50
|
+
"tsx": "^4.20.0",
|
|
51
|
+
"typescript": "~6.0.3",
|
|
52
|
+
"vitest": "^5.0.5",
|
|
53
|
+
"@eslint/js": "^9.39.4",
|
|
54
|
+
"eslint": "^9",
|
|
55
|
+
"eslint-plugin-unused-imports": "^4.4.1",
|
|
56
|
+
"typescript-eslint": "^8.70.1"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"dev": "tsx src/index.ts",
|
|
60
|
+
"build": "esbuild src/index.ts --bundle --platform=node --format=esm --outfile=dist/index.mjs --external:@hocuspocus/server --external:@hocuspocus/provider --external:yjs --external:jsdom --external:katex --external:@tiptap/* --external:*.wasm",
|
|
61
|
+
"start": "node dist/index.mjs",
|
|
62
|
+
"test": "vitest",
|
|
63
|
+
"test:run": "vitest run",
|
|
64
|
+
"typecheck": "tsc --noEmit",
|
|
65
|
+
"lint": "eslint"
|
|
66
|
+
}
|
|
6
67
|
}
|
|
@@ -0,0 +1,93 @@
|
|
|
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
|
+
// CollabClient 映射层单元测试(纯内存,不触库)。重点覆盖 2026-10-25 审计
|
|
19
|
+
// A07 修复的归属语义:已缓存 null(guest/无归属)≠ 未缓存(无映射记录)——
|
|
20
|
+
// 「宁缺勿错」要求 null 与成员 id 混存时归属为 null,而非错误归属到成员。
|
|
21
|
+
|
|
22
|
+
import { describe, expect, test } from "vitest";
|
|
23
|
+
import { collectClientWrites, forgetRoomClients, resolveAuthorId } from "../clients";
|
|
24
|
+
|
|
25
|
+
const ROOM = "doc:knowledge:clients-unit";
|
|
26
|
+
|
|
27
|
+
describe("resolveAuthorId(尽力归属,宁缺勿错)", () => {
|
|
28
|
+
test("无任何缓存 → null", () => {
|
|
29
|
+
forgetRoomClients(ROOM);
|
|
30
|
+
expect(resolveAuthorId(ROOM, [1, 2])).toBeNull();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("单一成员归属", () => {
|
|
34
|
+
forgetRoomClients(ROOM);
|
|
35
|
+
collectClientWrites(ROOM, [100], "user-a");
|
|
36
|
+
expect(resolveAuthorId(ROOM, [100])).toBe("user-a");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("同批次多 clientID 同一成员 → 归属该成员", () => {
|
|
40
|
+
forgetRoomClients(ROOM);
|
|
41
|
+
collectClientWrites(ROOM, [200, 201], "user-a");
|
|
42
|
+
expect(resolveAuthorId(ROOM, [200, 201])).toBe("user-a");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("两个不同成员 → 归属冲突 null", () => {
|
|
46
|
+
forgetRoomClients(ROOM);
|
|
47
|
+
collectClientWrites(ROOM, [300], "user-a");
|
|
48
|
+
collectClientWrites(ROOM, [301], "user-b");
|
|
49
|
+
expect(resolveAuthorId(ROOM, [300, 301])).toBeNull();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("仅已缓存 null(guest)→ null(非 undefined 逃逸)", () => {
|
|
53
|
+
forgetRoomClients(ROOM);
|
|
54
|
+
collectClientWrites(ROOM, [400], null);
|
|
55
|
+
expect(resolveAuthorId(ROOM, [400])).toBeNull();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("已缓存 null 与成员 id 混存 → null(修复点:不再错误归属到成员)", () => {
|
|
59
|
+
forgetRoomClients(ROOM);
|
|
60
|
+
collectClientWrites(ROOM, [500], "user-a");
|
|
61
|
+
collectClientWrites(ROOM, [501], null); // guest 连接
|
|
62
|
+
expect(resolveAuthorId(ROOM, [500, 501])).toBeNull();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("未缓存 clientID 不参与判定:成员 + 未知来源 → 尽力归属成员", () => {
|
|
66
|
+
forgetRoomClients(ROOM);
|
|
67
|
+
collectClientWrites(ROOM, [600], "user-a");
|
|
68
|
+
expect(resolveAuthorId(ROOM, [600, 601])).toBe("user-a");
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("forgetRoomClients 释放后归属失效", () => {
|
|
72
|
+
collectClientWrites(ROOM, [700], "user-a");
|
|
73
|
+
forgetRoomClients(ROOM);
|
|
74
|
+
expect(resolveAuthorId(ROOM, [700])).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("collectClientWrites(缓存 + 去重)", () => {
|
|
79
|
+
test("未变化不重复出行,变化以新值重写", () => {
|
|
80
|
+
forgetRoomClients(ROOM);
|
|
81
|
+
expect(collectClientWrites(ROOM, [800], "user-a")).toHaveLength(1);
|
|
82
|
+
expect(collectClientWrites(ROOM, [800], "user-a")).toHaveLength(0); // 去重
|
|
83
|
+
const changed = collectClientWrites(ROOM, [800], "user-b");
|
|
84
|
+
expect(changed).toHaveLength(1);
|
|
85
|
+
expect(changed[0]!.userId).toBe("user-b");
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("clientId 落库为 BigInt(uint32 域)", () => {
|
|
89
|
+
forgetRoomClients(ROOM);
|
|
90
|
+
const rows = collectClientWrites(ROOM, [4_294_967_295], "user-a");
|
|
91
|
+
expect(rows[0]!.clientId).toBe(4_294_967_295n);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -0,0 +1,227 @@
|
|
|
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
|
+
// 嵌入形态冒烟(P4 服务形态统一 任务 30):对标 DSH「webserver 唯一监听面 +
|
|
19
|
+
// WS 同端口」——Hocuspocus 挂到宿主既有 HTTP server 的 /collab 路径,同端口
|
|
20
|
+
// WS upgrade 路径分流后 Yjs 同步往返可用;standalone 回退入口受
|
|
21
|
+
// COLLAB_STANDALONE=1 门禁;crossws hooks 门面(nitro 宿主消费面)装配冒烟。
|
|
22
|
+
|
|
23
|
+
import { createServer, type Server as HttpServer } from "node:http";
|
|
24
|
+
import type { IncomingMessage } from "node:http";
|
|
25
|
+
import type { Duplex } from "node:stream";
|
|
26
|
+
import { afterAll, afterEach, describe, expect, it } from "vitest";
|
|
27
|
+
import * as Y from "yjs";
|
|
28
|
+
import { HocuspocusProvider } from "@hocuspocus/provider";
|
|
29
|
+
import {
|
|
30
|
+
attachCollabUpgradeListener,
|
|
31
|
+
createCollabCrosswsHooks,
|
|
32
|
+
DEFAULT_COLLAB_WS_PATH,
|
|
33
|
+
} from "../embed";
|
|
34
|
+
import {
|
|
35
|
+
assertStandaloneStartupAllowed,
|
|
36
|
+
createCollabServer,
|
|
37
|
+
type CollabServerInstance,
|
|
38
|
+
} from "../index";
|
|
39
|
+
import { issueTicket, TEST_SECRET, waitUntil } from "./test-utils";
|
|
40
|
+
|
|
41
|
+
/** 本文件打开的全部宿主 server(afterAll 收口) */
|
|
42
|
+
const httpServers: HttpServer[] = [];
|
|
43
|
+
const collabInstances: CollabServerInstance[] = [];
|
|
44
|
+
const providers: HocuspocusProvider[] = [];
|
|
45
|
+
|
|
46
|
+
function listenHttp(): Promise<{ server: HttpServer; port: number }> {
|
|
47
|
+
const server = createServer((_req, res) => {
|
|
48
|
+
// 非 upgrade HTTP 面仅作占位(嵌入形态宿主即 web 服务本体)
|
|
49
|
+
res.writeHead(404).end();
|
|
50
|
+
});
|
|
51
|
+
httpServers.push(server);
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
server.listen(0, "127.0.0.1", () => {
|
|
54
|
+
const addr = server.address();
|
|
55
|
+
if (addr === null || typeof addr === "string") {
|
|
56
|
+
throw new Error("listenHttp:端口分配失败");
|
|
57
|
+
}
|
|
58
|
+
resolve({ server, port: addr.port });
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 宿主 server 起一个 /other 路径的诱饵 upgrade 监听器(路径分流反证) */
|
|
64
|
+
function attachDecoyUpgrade(
|
|
65
|
+
server: HttpServer,
|
|
66
|
+
): { hits: () => number; handle(req: IncomingMessage, socket: Duplex, head: Buffer): void } {
|
|
67
|
+
let hits = 0;
|
|
68
|
+
const handle = (request: IncomingMessage, socket: Duplex, head: Buffer) => {
|
|
69
|
+
const path = (request.url ?? "").split("?")[0];
|
|
70
|
+
if (path !== "/other") return;
|
|
71
|
+
hits += 1;
|
|
72
|
+
socket.write("HTTP/1.1 404 Not Found\r\nconnection: close\r\n\r\n");
|
|
73
|
+
socket.destroy();
|
|
74
|
+
};
|
|
75
|
+
server.on("upgrade", handle);
|
|
76
|
+
return { hits: () => hits, handle };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface ConnectedProvider {
|
|
80
|
+
provider: HocuspocusProvider;
|
|
81
|
+
doc: Y.Doc;
|
|
82
|
+
ready: Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function connectProvider(wsUrl: string, room: string): ConnectedProvider {
|
|
86
|
+
const doc = new Y.Doc();
|
|
87
|
+
const provider = new HocuspocusProvider({
|
|
88
|
+
url: wsUrl,
|
|
89
|
+
name: room,
|
|
90
|
+
token: issueTicket(room),
|
|
91
|
+
document: doc,
|
|
92
|
+
});
|
|
93
|
+
const ready = new Promise<void>((resolve, reject) => {
|
|
94
|
+
provider.on("synced", () => resolve());
|
|
95
|
+
provider.on("authenticationFailed", ({ reason }: { reason: string }) =>
|
|
96
|
+
reject(new Error(`鉴权失败:${reason}`)),
|
|
97
|
+
);
|
|
98
|
+
});
|
|
99
|
+
providers.push(provider);
|
|
100
|
+
return { provider, doc, ready };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
afterEach(() => {
|
|
104
|
+
for (const provider of providers.splice(0)) provider.destroy();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
afterAll(async () => {
|
|
108
|
+
for (const instance of collabInstances.splice(0)) {
|
|
109
|
+
await Promise.race([instance.server.destroy(), new Promise((r) => setTimeout(r, 5000))]);
|
|
110
|
+
}
|
|
111
|
+
for (const server of httpServers.splice(0)) {
|
|
112
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
describe("嵌入形态(externalServer 监听器置换)", () => {
|
|
117
|
+
it("同端口 /collab 路径 upgrade → 双 provider Yjs 同步往返", async () => {
|
|
118
|
+
const { server, port } = await listenHttp();
|
|
119
|
+
const instance = createCollabServer({
|
|
120
|
+
secret: TEST_SECRET,
|
|
121
|
+
metrics: false,
|
|
122
|
+
externalServer: server,
|
|
123
|
+
wsPath: DEFAULT_COLLAB_WS_PATH,
|
|
124
|
+
});
|
|
125
|
+
collabInstances.push(instance);
|
|
126
|
+
// 内部 httpServer 不监听:嵌入形态只有宿主一个监听面
|
|
127
|
+
expect(instance.server.httpServer.listening).toBe(false);
|
|
128
|
+
|
|
129
|
+
const room = "doc:knowledge:embed-smoke";
|
|
130
|
+
const a = connectProvider(`ws://127.0.0.1:${port}${DEFAULT_COLLAB_WS_PATH}`, room);
|
|
131
|
+
const b = connectProvider(`ws://127.0.0.1:${port}${DEFAULT_COLLAB_WS_PATH}`, room);
|
|
132
|
+
await Promise.all([a.ready, b.ready]);
|
|
133
|
+
|
|
134
|
+
// 双向同步往返:A 写 → B 收;B 写 → A 收
|
|
135
|
+
a.doc.getText("t").insert(0, "embed-a");
|
|
136
|
+
await waitUntil(() => b.doc.getText("t").toString() === "embed-a", "A→B 同步");
|
|
137
|
+
b.doc.getText("t").insert(0, "embed-b|");
|
|
138
|
+
await waitUntil(() => a.doc.getText("t").toString() === "embed-b|embed-a", "B→A 同步");
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("非 /collab 路径的 upgrade 不进 Hocuspocus(路径分流,留给宿主其他监听器)", async () => {
|
|
142
|
+
const { server, port } = await listenHttp();
|
|
143
|
+
const decoy = attachDecoyUpgrade(server);
|
|
144
|
+
const instance = createCollabServer({
|
|
145
|
+
secret: TEST_SECRET,
|
|
146
|
+
metrics: false,
|
|
147
|
+
externalServer: server,
|
|
148
|
+
});
|
|
149
|
+
collabInstances.push(instance);
|
|
150
|
+
|
|
151
|
+
const room = "doc:knowledge:embed-split";
|
|
152
|
+
const rejected = connectProvider(`ws://127.0.0.1:${port}/other`, room);
|
|
153
|
+
// /other 命中诱饵(404 断开)→ provider 无法完成鉴权链路
|
|
154
|
+
await waitUntil(() => decoy.hits() >= 1, "诱饵监听器命中 /other");
|
|
155
|
+
await new Promise<void>((resolve) => {
|
|
156
|
+
const timer = setTimeout(resolve, 1500);
|
|
157
|
+
rejected.provider.on("authenticated", () => {
|
|
158
|
+
clearTimeout(timer);
|
|
159
|
+
resolve();
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
expect(rejected.provider.isAuthenticated).not.toBe(true);
|
|
163
|
+
// Hocuspocus 未收到任何连接(room 文档未装载)
|
|
164
|
+
expect(instance.server.hocuspocus.documents.size).toBe(0);
|
|
165
|
+
|
|
166
|
+
// 同端口 /collab 正常可达(分流正确性反证)
|
|
167
|
+
const ok = connectProvider(`ws://127.0.0.1:${port}${DEFAULT_COLLAB_WS_PATH}`, room);
|
|
168
|
+
await ok.ready;
|
|
169
|
+
expect(ok.provider.isAuthenticated).toBe(true);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("attachCollabUpgradeListener:内部 httpServer 无 upgrade 监听器时显式失败(上游结构漂移防线)", async () => {
|
|
173
|
+
const { server } = await listenHttp();
|
|
174
|
+
const instance = createCollabServer({ secret: TEST_SECRET, metrics: false });
|
|
175
|
+
collabInstances.push(instance);
|
|
176
|
+
instance.server.httpServer.removeAllListeners("upgrade");
|
|
177
|
+
expect(() => attachCollabUpgradeListener(instance.server, server)).toThrow(
|
|
178
|
+
/没有 upgrade 监听器/,
|
|
179
|
+
);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe("standalone 回退形态门禁(退役裁决)", () => {
|
|
184
|
+
it("COLLAB_STANDALONE=1 放行,其余拒绝", () => {
|
|
185
|
+
expect(() => assertStandaloneStartupAllowed({})).toThrow(/已退役/);
|
|
186
|
+
expect(() => assertStandaloneStartupAllowed({ COLLAB_STANDALONE: "0" })).toThrow(
|
|
187
|
+
/已退役/,
|
|
188
|
+
);
|
|
189
|
+
expect(() =>
|
|
190
|
+
assertStandaloneStartupAllowed({ COLLAB_STANDALONE: "1" }),
|
|
191
|
+
).not.toThrow();
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
describe("crossws hooks 门面(nitro 宿主消费面)", () => {
|
|
196
|
+
it("open 建 ClientConnection、message/close/error 安全消费(与 Server.ts 内部装配同构冒烟)", async () => {
|
|
197
|
+
const instance = createCollabServer({ secret: TEST_SECRET, metrics: false });
|
|
198
|
+
collabInstances.push(instance);
|
|
199
|
+
const hooks = createCollabCrosswsHooks(instance.server.hocuspocus);
|
|
200
|
+
|
|
201
|
+
const closed: Array<{ code?: number; reason?: string }> = [];
|
|
202
|
+
const peer = {
|
|
203
|
+
id: "peer-smoke",
|
|
204
|
+
websocket: {
|
|
205
|
+
send: (_data: unknown) => {},
|
|
206
|
+
close: (code?: number, reason?: string) => {
|
|
207
|
+
closed.push({ code, reason });
|
|
208
|
+
},
|
|
209
|
+
readyState: 1,
|
|
210
|
+
},
|
|
211
|
+
request: new Request("http://localhost/collab"),
|
|
212
|
+
};
|
|
213
|
+
// open:建 ClientConnection(服务端不主动发帧——等客户端首条消息,与
|
|
214
|
+
// Server.ts 内部装配行为一致)
|
|
215
|
+
hooks.open(peer);
|
|
216
|
+
const connection = (peer as { _hocuspocus?: object })._hocuspocus;
|
|
217
|
+
expect(connection).toBeDefined();
|
|
218
|
+
// message:乱码帧不炸进程(ClientConnection handleMessage 兜底)
|
|
219
|
+
expect(() =>
|
|
220
|
+
hooks.message(peer, { uint8Array: () => new Uint8Array([1, 2, 3]) }),
|
|
221
|
+
).not.toThrow();
|
|
222
|
+
// error:peer 级错误只记日志
|
|
223
|
+
expect(() => hooks.error(peer, new Error("ws error"))).not.toThrow();
|
|
224
|
+
// close:连接清理(挂起文档连接关闭 + ping 定时器清除)
|
|
225
|
+
expect(() => hooks.close(peer, { code: 1000, reason: "done" })).not.toThrow();
|
|
226
|
+
});
|
|
227
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
// vitest setupFiles:persistence 集成测试直连共享开发库(§5.1 三模型),
|
|
19
|
+
// 需要在 @allbluecn/database 被 import 前拿到 DATABASE_URL。
|
|
20
|
+
// dev 库连接串在仓根 .env(apps/collab 无自己的 .env),Node 24 内置
|
|
21
|
+
// process.loadEnvFile 加载;已显式注入时不覆盖。缺失不在此处报错——
|
|
22
|
+
// 由 @allbluecn/database 的 requireDatabaseUrl 显式失败(可读错误)。
|
|
23
|
+
|
|
24
|
+
import { resolve } from "node:path";
|
|
25
|
+
|
|
26
|
+
if (!process.env.DATABASE_URL) {
|
|
27
|
+
try {
|
|
28
|
+
// vitest 的 cwd 是 apps/collab,仓根在两级之上
|
|
29
|
+
process.loadEnvFile(resolve(process.cwd(), "../../.env"));
|
|
30
|
+
} catch {
|
|
31
|
+
// 无仓根 .env(如 CI 注入 env var 的场景):交给 requireDatabaseUrl 报错
|
|
32
|
+
}
|
|
33
|
+
}
|