@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.
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/index.ts ADDED
@@ -0,0 +1,354 @@
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 文档与 awareness 状态存于单进程内存,
19
+ // **多实例部署不共享**(横向扩容前须 extension-redis 等共享层,本期不实施)。
20
+ // 口径对齐 apps/web/src/server/lib/rate-limit.ts 的单实例边界声明。
21
+ //
22
+ // 服务形态(P4 服务形态统一 任务 30):**内嵌 web 后端为主形态**——
23
+ // createCollabServer({ externalServer, wsPath }) 把 WS upgrade 挂到宿主进程
24
+ // 既有 HTTP server 的 /collab 路径(见 embed.ts);本文件的独立启动入口
25
+ // (startStandalone,CLI 直跑)自任务 30 起为**退役回退形态**,仅显式
26
+ // COLLAB_STANDALONE=1 放行。嵌入侧消费统一走 @allbluecn/collab-server/embed。
27
+ //
28
+ // dev 回退运行:COLLAB_STANDALONE=1 tsx src/index.ts(collab-core exports 为
29
+ // src/*.ts 源码直出,Node 不能裸跑 .ts);prod:esbuild 打包(见 package.json
30
+ // build)后 node dist/index.mjs。
31
+
32
+ import type { Server as HttpServer } from "node:http";
33
+ import { Server } from "@hocuspocus/server";
34
+ import { pathToFileURL } from "node:url";
35
+ import { authenticateConnection, type CollabContext } from "./auth";
36
+ import { createMetrics, type CollabMetrics } from "./metrics";
37
+ import {
38
+ createPersistence,
39
+ SNAPSHOT_DEBOUNCE_MS,
40
+ type CollabPersistenceHandle,
41
+ type CollabPersistenceOptions,
42
+ } from "./persistence";
43
+ import {
44
+ assertShareRoomCapacity,
45
+ DEFAULT_SHARE_ROOM_LIMIT,
46
+ parseShareRoomLimit,
47
+ } from "./share-room-limit";
48
+ import { attachInternalApplyChannel } from "./internal-apply";
49
+ import {
50
+ createHttpReindexNotifier,
51
+ registerKnowledgeCollab,
52
+ setKnowledgeReindexNotifier,
53
+ } from "./exporters/knowledge";
54
+ import { registerStoryCollab } from "./exporters/story";
55
+ import { registerBugCollab } from "./exporters/bug";
56
+ import { registerCaseCollab } from "./exporters/case";
57
+ import { registerDesignCollab } from "./exporters/design";
58
+ import {
59
+ attachCollabUpgradeListener,
60
+ DEFAULT_COLLAB_WS_PATH,
61
+ } from "./embed";
62
+
63
+ export interface CollabServerConfig {
64
+ /** COLLAB_SECRET(与 web 签发端共享的 HMAC 密钥),空串拒绝启动 */
65
+ secret: string;
66
+ /** 监听端口(仅 standalone 形态消费);缺省 3010(worktree 约定 3030) */
67
+ port?: number;
68
+ /**
69
+ * 嵌入形态:宿主既有 HTTP server(node:http.Server)。提供后本函数把
70
+ * WS upgrade 挂到该 server 的 wsPath 路径(监听器置换,见 embed.ts),
71
+ * 内部 httpServer 不监听;port 配置被忽略。
72
+ */
73
+ externalServer?: HttpServer;
74
+ /** 嵌入形态的 WS 分流路径;缺省 /collab(仅 externalServer 存在时消费) */
75
+ wsPath?: string;
76
+ /** 周期指标;false 关闭(测试),缺省 60s */
77
+ metrics?: { intervalMs: number } | false;
78
+ /**
79
+ * 持久层(§5.1 三模型:快照/日志/归属);缺省 false——纯内存运行
80
+ * (零 DATABASE_URL 环境与既有测试路径不受影响),env 编排显式开启。
81
+ */
82
+ persistence?: CollabPersistenceOptions | false;
83
+ /**
84
+ * §9 share room 连接上限(仅 `share:` 前缀 room 计数);缺省
85
+ * DEFAULT_SHARE_ROOM_LIMIT(50),0 = 不设上限。
86
+ */
87
+ shareRoomLimit?: number;
88
+ /** onStoreDocument debounce(Hocuspocus 内置配置);缺省 2000(§3.2) */
89
+ debounceMs?: number;
90
+ }
91
+
92
+ export interface CollabServerInstance {
93
+ server: Server<CollabContext>;
94
+ metrics: CollabMetrics | null;
95
+ /** 持久层句柄(stop 停兜底清理扫描);未启用持久层时 null */
96
+ persistence: CollabPersistenceHandle | null;
97
+ }
98
+
99
+ export const DEFAULT_COLLAB_PORT = 3010;
100
+ export const DEFAULT_METRICS_INTERVAL_MS = 60_000;
101
+
102
+ /** 装配协作服务(不监听——listen 由调用方控制,测试用 port 0) */
103
+ export function createCollabServer(config: CollabServerConfig): CollabServerInstance {
104
+ if (config.secret.length === 0) {
105
+ throw new Error("createCollabServer:COLLAB_SECRET 不能为空(配置缺失必须显式失败)");
106
+ }
107
+
108
+ const metrics = config.metrics === false ? null : createMetrics();
109
+ const persistence = config.persistence ? createPersistence(config.persistence) : null;
110
+
111
+ const server = new Server<CollabContext>({
112
+ port: config.port ?? DEFAULT_COLLAB_PORT,
113
+ stopOnSignals: false,
114
+ quiet: true,
115
+ debounce: config.debounceMs ?? SNAPSHOT_DEBOUNCE_MS,
116
+ extensions: [
117
+ ...(metrics ? [metrics.extension()] : []),
118
+ ...(persistence ? [persistence.extension] : []),
119
+ ],
120
+ async onAuthenticate({ token, documentName, connectionConfig, instance }) {
121
+ const context = authenticateConnection(token, documentName, config.secret);
122
+ // §9 share room 容量守卫:鉴权通过后检查(无效 ticket 不占名额),
123
+ // 超限走 CollabAuthError 拒绝路径(客户端 authenticationFailed)
124
+ assertShareRoomCapacity(
125
+ instance,
126
+ documentName,
127
+ config.shareRoomLimit ?? DEFAULT_SHARE_ROOM_LIMIT,
128
+ );
129
+ // readOnly 必须落在 connectionConfig 上才驱动服务端拒写
130
+ // (view 连接的 update 被丢弃并 nack,不广播、不踢线);
131
+ // context 携带同一事实,供 onLoadDocument/onStateless 等 hook 使用。
132
+ connectionConfig.readOnly = context.readOnly;
133
+ return context;
134
+ },
135
+ });
136
+
137
+ // §5.3 内部应用通道(任务 17):/internal/apply 挂在同端口 HTTP 面
138
+ // (监听器置换,非内部路由原样委托);信封与连接鉴权共用 COLLAB_SECRET。
139
+ // 嵌入形态下内部 httpServer 不监听,web 侧 write-guard 走进程内直调
140
+ // (本通道仅 standalone 回退形态消费)。
141
+ attachInternalApplyChannel(server, config.secret);
142
+
143
+ // 嵌入形态(任务 30):WS upgrade 挂宿主 server 的 /collab 路径
144
+ if (config.externalServer) {
145
+ attachCollabUpgradeListener(
146
+ server,
147
+ config.externalServer,
148
+ config.wsPath ?? DEFAULT_COLLAB_WS_PATH,
149
+ );
150
+ }
151
+
152
+ return {
153
+ server,
154
+ metrics,
155
+ persistence: persistence ? persistence.start() : null,
156
+ };
157
+ }
158
+
159
+ // ── env 配置解析(standalone 回退形态与 web 内嵌共用;任务 30 抽取)──────
160
+
161
+ /** env 解析产物(port 不在内——COLLAB_PORT 仅 standalone 回退形态消费) */
162
+ export interface CollabEnvSettings {
163
+ secret: string;
164
+ metricsEnabled: boolean;
165
+ metricsIntervalMs: number;
166
+ persistenceEnabled: boolean;
167
+ shareRoomLimit: number;
168
+ }
169
+
170
+ /**
171
+ * 读取并校验 COLLAB_* env(除 COLLAB_PORT 外的全量装配参数)。非法值/缺失
172
+ * 关键项显式抛错(配置缺失必须显式失败——静默降级会无声丢快照/刷屏指标日志)。
173
+ */
174
+ export function parseCollabEnvSettings(
175
+ env: NodeJS.ProcessEnv = process.env,
176
+ ): CollabEnvSettings {
177
+ const secret = env.COLLAB_SECRET ?? "";
178
+ if (secret.length === 0) {
179
+ throw new Error("parseCollabEnvSettings:缺少 COLLAB_SECRET env,协作服务拒绝装配");
180
+ }
181
+
182
+ const metricsEnabled = env.COLLAB_METRICS !== "off";
183
+ // 与 COLLAB_PORT 同款显式校验:非法值(NaN/非正数)必须在装配期显式失败
184
+ // ——setInterval(fn, NaN) 被 Node 规约为 1ms 间隔,指标日志每毫秒刷屏
185
+ const metricsIntervalMs = Number(
186
+ env.COLLAB_METRICS_INTERVAL_MS ?? DEFAULT_METRICS_INTERVAL_MS,
187
+ );
188
+ if (!Number.isInteger(metricsIntervalMs) || metricsIntervalMs <= 0) {
189
+ throw new Error(
190
+ `parseCollabEnvSettings:COLLAB_METRICS_INTERVAL_MS 非法(${env.COLLAB_METRICS_INTERVAL_MS})`,
191
+ );
192
+ }
193
+
194
+ // §9 share room 连接上限(默认 50;0 = 不设上限),非法值显式失败
195
+ const shareRoomLimit = parseShareRoomLimit(env.COLLAB_SHARE_ROOM_LIMIT);
196
+
197
+ // 持久层缺省开启(协作服务的快照/审计是产品承诺);显式 off 退回纯内存。
198
+ // 开启但缺 DATABASE_URL 时显式失败——静默降级会无声丢快照(配置缺失必须显式失败)。
199
+ const persistenceEnabled = env.COLLAB_PERSISTENCE !== "off";
200
+ if (persistenceEnabled && !env.DATABASE_URL) {
201
+ throw new Error(
202
+ "parseCollabEnvSettings:COLLAB_PERSISTENCE 开启但缺少 DATABASE_URL env" +
203
+ "(快照无处落库)。请配置 DATABASE_URL 或显式设置 COLLAB_PERSISTENCE=off" +
204
+ "(纯内存模式,重启丢协同快照)。",
205
+ );
206
+ }
207
+
208
+ return { secret, metricsEnabled, metricsIntervalMs, persistenceEnabled, shareRoomLimit };
209
+ }
210
+
211
+ /**
212
+ * 回写导出器 + room 守卫注册(§5.2 回写,任务 16/21):生产装配显式调用。
213
+ * 仅持久层开启时调用——导出器/守卫直连业务库,纯内存模式无库可查。
214
+ * 向量索引重建通知由调用方按形态装配:standalone 走 COLLAB_WEB_URL HTTP
215
+ * (fire-and-forget loopback);web 内嵌走进程内直调(embed 侧注册,免 HTTP)。
216
+ */
217
+ export function registerCollabExporters(): void {
218
+ registerKnowledgeCollab();
219
+ registerStoryCollab();
220
+ registerBugCollab();
221
+ registerCaseCollab();
222
+ registerDesignCollab();
223
+ }
224
+
225
+ // ── standalone 回退形态(退役;COLLAB_STANDALONE=1 门禁)─────────────────
226
+
227
+ /** 独立启动形态门禁:非显式 COLLAB_STANDALONE=1 一律拒绝(任务 30 退役裁决) */
228
+ export function assertStandaloneStartupAllowed(
229
+ env: NodeJS.ProcessEnv = process.env,
230
+ ): void {
231
+ if (env.COLLAB_STANDALONE !== "1") {
232
+ throw new Error(
233
+ "startStandalone:独立启动形态已退役(P4 服务形态统一 任务 30)。" +
234
+ "collab 现为 web 后端内嵌模块(同端口 /collab 路径分流,pnpm dev 两进程即含协作)。" +
235
+ "如需临时回退独立形态,请显式设置 COLLAB_STANDALONE=1 并自行启动 apps/collab。",
236
+ );
237
+ }
238
+ }
239
+
240
+ /** 读取 env 并以独立形态启动(退役回退入口;CLI 仅 COLLAB_STANDALONE=1 放行) */
241
+ export async function startStandalone(
242
+ env: NodeJS.ProcessEnv = process.env,
243
+ ): Promise<CollabServerInstance> {
244
+ const settings = parseCollabEnvSettings(env);
245
+ const port = Number(env.COLLAB_PORT ?? DEFAULT_COLLAB_PORT);
246
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
247
+ throw new Error(`startStandalone:COLLAB_PORT 非法(${env.COLLAB_PORT})`);
248
+ }
249
+
250
+ const instance = createCollabServer({
251
+ secret: settings.secret,
252
+ port,
253
+ metrics: settings.metricsEnabled ? { intervalMs: settings.metricsIntervalMs } : false,
254
+ persistence: settings.persistenceEnabled ? {} : false,
255
+ shareRoomLimit: settings.shareRoomLimit,
256
+ });
257
+ // 回写导出器 + room 守卫注册(§5.2 回写,任务 16/21):生产入口显式装配。
258
+ if (settings.persistenceEnabled) {
259
+ registerCollabExporters();
260
+ // 向量索引重建通知(fire-and-forget HTTP → web):未配置 COLLAB_WEB_URL
261
+ // 时导出器内 warn-once 降级为 no-op(协作与内容回写不受影响)
262
+ if (env.COLLAB_WEB_URL) {
263
+ setKnowledgeReindexNotifier(
264
+ createHttpReindexNotifier(env.COLLAB_WEB_URL, settings.secret),
265
+ );
266
+ }
267
+ }
268
+ await instance.server.listen();
269
+ console.log(
270
+ `[collab] Hocuspocus 协作服务已启动(standalone 回退形态,退役计划中)port=${instance.server.address.port} metrics=${settings.metricsEnabled ? `on(${settings.metricsIntervalMs}ms)` : "off"} persistence=${settings.persistenceEnabled ? "on" : "off"} shareRoomLimit=${settings.shareRoomLimit <= 0 ? "off" : settings.shareRoomLimit}`,
271
+ );
272
+ if (instance.metrics && settings.metricsEnabled) {
273
+ instance.metrics.start(instance.server.hocuspocus, settings.metricsIntervalMs);
274
+ }
275
+ return instance;
276
+ }
277
+
278
+ const isMain =
279
+ process.argv[1] !== undefined &&
280
+ import.meta.url === pathToFileURL(process.argv[1]).href;
281
+
282
+ /** 优雅停机有界超时:destroy 挂起(如 DB 不可达拖住末次 flush)时的强制退出底线 */
283
+ export const GRACEFUL_SHUTDOWN_TIMEOUT_MS = 10_000;
284
+
285
+ /**
286
+ * 优雅停机(SIGTERM/SIGINT 共用):停指标 → destroy Hocuspocus(停收新连接
287
+ * → 关全部连接并立即执行挂起的 onStoreDocument——末次快照 + CollabUpdate
288
+ * 日志缓冲 flush → 卸载文档 → onDestroy 停兜底扫描)→ 停持久层句柄 →
289
+ * 退出。destroy 有界超时兜底(flush 卡死时强制退出,部署层不无限等待);
290
+ * 二次信号立即退出(重复 SIGTERM = 运维明确要立刻走)。
291
+ */
292
+ export async function shutdownCollabServer(
293
+ instance: CollabServerInstance | null,
294
+ opts: {
295
+ signal: string;
296
+ timeoutMs?: number;
297
+ /** 测试注入(缺省 process.exit) */
298
+ exit?: (code: number) => void;
299
+ },
300
+ ): Promise<void> {
301
+ const exit = opts.exit ?? ((code: number) => process.exit(code));
302
+ const timeoutMs = opts.timeoutMs ?? GRACEFUL_SHUTDOWN_TIMEOUT_MS;
303
+ console.log(`[collab] 收到 ${opts.signal},优雅关闭中...`);
304
+ const hardExit = setTimeout(() => {
305
+ console.error(`[collab] 优雅关闭超过 ${timeoutMs}ms,强制退出(快照可能未 flush)`);
306
+ exit(0);
307
+ }, timeoutMs);
308
+ try {
309
+ instance?.metrics?.stop();
310
+ if (instance) {
311
+ await instance.server.destroy();
312
+ }
313
+ } catch (err) {
314
+ console.error("[collab] 优雅关闭失败(强制退出):", err);
315
+ clearTimeout(hardExit);
316
+ exit(0);
317
+ return;
318
+ }
319
+ clearTimeout(hardExit);
320
+ instance?.persistence?.stop();
321
+ console.log("[collab] 已关闭(快照与日志缓冲已 flush)");
322
+ exit(0);
323
+ }
324
+
325
+ if (isMain) {
326
+ let instance: CollabServerInstance | null = null;
327
+ let shuttingDown = false;
328
+ // 退役门禁(任务 30):非显式 COLLAB_STANDALONE=1 拒绝独立启动,
329
+ // 引导使用 web 内嵌形态(pnpm dev 已含协作)。
330
+ try {
331
+ assertStandaloneStartupAllowed();
332
+ } catch (err) {
333
+ console.error("[collab]", err instanceof Error ? err.message : err);
334
+ process.exit(1);
335
+ }
336
+ startStandalone()
337
+ .then((started) => {
338
+ instance = started;
339
+ })
340
+ .catch((err) => {
341
+ console.error("[collab] 启动失败:", err);
342
+ process.exit(1);
343
+ });
344
+ const onSignal = (signal: string) => {
345
+ if (shuttingDown) {
346
+ console.warn(`[collab] 再次收到 ${signal},立即强制退出`);
347
+ process.exit(0);
348
+ }
349
+ shuttingDown = true;
350
+ void shutdownCollabServer(instance, { signal });
351
+ };
352
+ process.on("SIGINT", () => onSignal("SIGINT"));
353
+ process.on("SIGTERM", () => onSignal("SIGTERM"));
354
+ }
@@ -0,0 +1,99 @@
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
+ // /internal/apply 准入限流(同端口公网可达,验签在读体之后——读体与 HMAC
19
+ // 计算须有廉价放大防线;与 share-room-limit 同风格的最小结构面):
20
+ //
21
+ // - 全局并发读体上限:同时在读/处理中的 /internal/apply 请求达上限即 503
22
+ // (web 转发端对非 2xx 重试至 TTL 后降级直写,语义兼容);正常业务流量
23
+ // (web 门卫逐写转发)远低于上限,纯内存 DoS 面封顶。
24
+ // - per-IP 验签失败滑动窗:验签失败的请求(伪造/探测)按来源 IP 计数,
25
+ // 窗口内超限即 429——合法 web 的密钥配置错误属部署故障,不应靠重试打穿。
26
+ //
27
+ // 单实例边界:计数存进程内存,多实例不共享(阈值 = 配置值 × 实例数),
28
+ // 与 index.ts / rate-limit.ts 的单实例边界声明一致。
29
+
30
+ /** 全局同时在读体/处理中的 /internal/apply 请求上限 */
31
+ export const INTERNAL_APPLY_MAX_IN_FLIGHT = 16;
32
+
33
+ /** per-IP 验签失败计数窗口内上限 */
34
+ export const INTERNAL_APPLY_FAIL_LIMIT_PER_WINDOW = 30;
35
+
36
+ /** per-IP 验签失败滑动窗宽(毫秒) */
37
+ export const INTERNAL_APPLY_FAIL_WINDOW_MS = 60_000;
38
+
39
+ export interface ApplyAdmission {
40
+ /** 进入读体/处理段;false = 全局并发已满(调用方回 503) */
41
+ begin(): boolean;
42
+ /** 结束一次 begin=true 的占用(幂等防错配) */
43
+ end(): void;
44
+ /** 当前在途占用数 */
45
+ inFlight(): number;
46
+ /** 记一次验签失败(按来源 IP;窗口随调用惰性滚动) */
47
+ noteVerifyFailure(ip: string): void;
48
+ /** 该 IP 当前窗口是否已超失败上限(true = 拒绝,调用方回 429) */
49
+ isVerifyBlocked(ip: string): boolean;
50
+ }
51
+
52
+ /** 工厂(测试隔离:每实例独立计数;生产 attachInternalApplyChannel 持有一份) */
53
+ export function createApplyAdmission(
54
+ options: {
55
+ maxInFlight?: number;
56
+ failLimitPerWindow?: number;
57
+ failWindowMs?: number;
58
+ } = {},
59
+ ): ApplyAdmission {
60
+ const maxInFlight = options.maxInFlight ?? INTERNAL_APPLY_MAX_IN_FLIGHT;
61
+ const failLimit = options.failLimitPerWindow ?? INTERNAL_APPLY_FAIL_LIMIT_PER_WINDOW;
62
+ const windowMs = options.failWindowMs ?? INTERNAL_APPLY_FAIL_WINDOW_MS;
63
+
64
+ let current = 0;
65
+ /** ip → 窗口起点与失败计数(惰性滚动:命中检查/计数时过期即重置) */
66
+ const failures = new Map<string, { windowStart: number; count: number }>();
67
+
68
+ return {
69
+ begin() {
70
+ if (current >= maxInFlight) return false;
71
+ current += 1;
72
+ return true;
73
+ },
74
+ end() {
75
+ if (current > 0) current -= 1;
76
+ },
77
+ inFlight() {
78
+ return current;
79
+ },
80
+ noteVerifyFailure(ip) {
81
+ const now = Date.now();
82
+ const entry = failures.get(ip);
83
+ if (!entry || now - entry.windowStart >= windowMs) {
84
+ failures.set(ip, { windowStart: now, count: 1 });
85
+ return;
86
+ }
87
+ entry.count += 1;
88
+ },
89
+ isVerifyBlocked(ip) {
90
+ const entry = failures.get(ip);
91
+ if (!entry) return false;
92
+ if (Date.now() - entry.windowStart >= windowMs) {
93
+ failures.delete(ip);
94
+ return false;
95
+ }
96
+ return entry.count >= failLimit;
97
+ },
98
+ };
99
+ }