mirror of
https://github.com/sinanyuntu/trade-message-center.git
synced 2026-09-17 13:22:11 +08:00
35 KiB
35 KiB
服务端基础设施契约
1. Scope / Trigger
- Trigger:服务端首次引入 Fastify 启动、WebSocket 传输和 PostgreSQL ORM。
- Scope:
apps/server/src/的配置、应用组合、健康路由、WebSocket 生命周期和数据库连接。 - Excluded:OneTalk 业务字段规则和 repository 细节由数据库规范与
src/onetalk/领域模块定义;发送队列仍不在本服务基础设施内。协议帧与可替换授权端口由共享 contract 包定义,数据库迁移由数据库规范单独定义。Mind 生产认证通过两个 HTTP 接口接入,具体目标契约见 Mind HTTP 授权。
2. Signatures
loadConfig(environment: Record<string, string | undefined>): ServerConfig
createDatabase(databaseUrl: string): { db: Database; close(): Promise<void> }
createApp(config: ServerConfig, dependencies?: AppDependencies): FastifyInstance
createServerRuntime(config: ServerConfig, dependencies?: ServerRuntimeDependencies): ServerRuntime
startServer(): Promise<void>
3. Contracts
- Required environment keys:
HOST,PORT,DATABASE_URL。 - Optional
NODE_ENVis normalized at the configuration boundary; only exact trimmeddevelopmentenables the development-only loopback Mind HTTP configuration, while missing/unknown values remain fail-closed。 GET /healthreturns{ "status": "ok" }。- WebSocket routes are
GET /ws/pluginandGET /ws/mind; each route binds its connection type before upgrade and checks its exact Origin allowlist.GET /wsis reject-only compatibility behavior (426 onetalk_protocol_upgrade_required) and has no legacy handler, outbox or dispatch path. Malformed or unsupported protocol frames close with code1003, and connection/handler errors close with1011。 createAppnever callslisten。entry.ts是唯一进程入口,它调用runtime.ts的双 listener lifecycle;runtime.ts只绑定 publicHOST:PORT与 internal0.0.0.0:7777,并在任一 bind 失败时关闭两者。业务/HTTP 模块不得直接监听端口。- Database resources are closed through the app
onClosehook; URL and credentials never enter responses or logs。 createAppcomposes one injected/defaultOneTalkService,OneTalkProfileServiceandOneTalkReadServiceover the samedatabase.db;AppDependenciesmay inject these domain ports, the connection registry and publisher failure sink for tests or deployment adapters。- WebSocket business frames cross through the service boundary; successful observation order is database commit → plugin
message.ack→ authorized Mindmessage.created。message.created与 HTTP history 都必须从同一 normalized JSONB fact 投影 sharedOneTalkCenterMessage,不得暴露顶层text/contentType或 raw payload。 contact.profile.observedis a Bright persistence path: canonical binding/read/sync authorization → profile service → guarded Bright transaction → post-write fence →contact.profile.ack; it never calls Mind profile HTTP or the message service.AppDependencies.profileServiceis the test/deployment seam.
4. Validation & Error Matrix
| Condition | Result |
|---|---|
Missing/blank HOST |
throw Missing HOST |
Missing/blank PORT |
throw Missing PORT |
PORT outside 1..65535 or non-integer |
throw Invalid PORT: expected integer 1-65535 |
Missing/blank DATABASE_URL |
throw Missing DATABASE_URL |
| Malformed or unsupported WebSocket frame received | send the stable protocol error, then close current socket with 1003 |
| WebSocket error received | close current socket with 1011 |
| Profile future-skew or guarded persistence rejected | stable profile_observed_at_future/database failure; no profile ACK |
| Profile transaction succeeds but authorization/connection/policy fence is stale | no late ACK; plugin pending remains |
5. Good / Base / Bad Cases
- Good: tests inject
{ db, close }, callapp.ready(), verify/health, then observe one close call。 - Base: production startup creates a Drizzle client from
DATABASE_URLand listens on configured host/port。 - Bad: route handler reads
process.env, creates a second postgres client, or returns the connection URL in an error。
6. Tests Required
- Configuration test asserts missing URL and invalid port errors contain field/error class but not secret values。
- Health test asserts HTTP
200and exact{ status: "ok" }response。 - Lifecycle test asserts injected database
closeruns once onapp.close()。 - WebSocket registration test asserts
websocketServerexists,GET /ws/plugin/GET /ws/mindare registered, andGET /wsis reject-only; OneTalk protocol tests assert mock-authorized handshake, heartbeat, version rejection, and authorization failures。 - OneTalk business tests assert raw observation validation, conversation discovery, sync completion, anchor snapshot, plugin-only writes and publish-after-commit behavior。
7. Wrong vs Correct
Wrong
app.get("/health", async () => ({ databaseUrl: process.env.DATABASE_URL }));
Correct
app.get("/health", async () => ({ status: "ok" }));
The health boundary is stable and secret-free; database probing belongs in a later operational contract。
Scenario: Bright v3 authorization and commit fences
1. Scope / Trigger
- Trigger:Mind 授权、Bright WebSocket 生命周期和 OneTalk 事实写入共享多个异步边界,需要避免 pause、连接替换或迟到回报穿透副作用。
- Scope:
cutover-policy.ts、websocket/registry.ts、websocket/handler.ts、onetalk/service.ts和 guarded repository ports。 - Excluded:Mind 的远端 revocation push/lease、真实 Mind 页面、浏览器/TLS、跨仓库 legacy 删除和 PostgreSQL 环境验收。
2. Signatures
createOneTalkCutoverPolicy(initial?: { enabled: boolean; paused: boolean }): OneTalkCutoverPolicy
registry.requestSend({ mindSocket, frame }): Promise<OneTalkSendResultFrame["payload"]>
registry.createCommitGuard(connection, policyEpoch): OneTalkCommitGuard
repository.guardedInsertMessage(context, source, message, guard): Promise<InsertResult>
repository.guardedUpdateSyncState(context, update, conversationId, guard): Promise<Conversation | null>
3. Contracts
- Bright v3 policy 只通过
enabled/paused/epoch控制 admission;pause/resume 可以恢复 Bright v3,不依赖或保存firstBrightFactWritten/markBrightFactWritten。 OneTalkConnectionRegistry是 handler-facing façade;其内部connection-store是 canonical connection、generation 和 plugin presence 的唯一 owner,mind-publisher只做 Mind 二次授权/帧发送/失败上报,pending-send-coordinator是 in-flightsendRequestIdreserve、phase、terminal transition、timeout、disconnect、pause 和 late confirmation 的唯一 owner。它只保存进行中的 attempt;settle必须清除pendingSends与pendingConversationSends,不得持有终态 payload、终态 ID 去重历史或重放缓存。三个协作者必须注入同一 store,不能在 handler 或其它模块复制 socket/generation/pending map;所有 wire send 后结果不可自动重试。- HTTP 读取只依赖
OneTalkPluginPresenceReader.isPluginOnline(scope),不得为读取路径注入或依赖完整 registry 的发送、连接管理或发布能力。 - 远程 observation/discovery/sync/confirmation 的 database side effect 必须带同一 canonical connection/generation/policy guard。guard 失效必须使事务回滚,不返回伪造的 accepted/duplicate。
4. Validation & Error Matrix
| 条件 | 结果 |
|---|---|
| 相同 ID 的并发 send 在 attempt 仍进行中 | 一个 attempt,另一个 rejected_before_send/duplicate_request;终态后复用 ID 不属于 coordinator 协议契约 |
| wire send 前断线、替换或 pause | rejected_before_send/waiting_for_page |
| wire send 后断线、替换或 pause | delivery_unknown/send_connection_lost |
| confirmation timeout/non-success/duplicate/late | 唯一 terminal;清 timer 与全部 pending 索引;终态后的 confirmation no-op |
| pause 期间的既有 WS | close 1013/authorization_unavailable,不先发 ws.error |
| guarded transaction 在任一异步边界失效 | rollback;不 ACK、publish 或返回 confirmed result |
5. Good / Base / Bad Cases
- Good:最后一次授权返回后只做同步 canonical/generation/epoch/open 检查,再调用
socket.send。 - Base:本地 fake repository 和 fake Mind fetch 证明调用顺序与 fail-closed 逻辑;真实 PostgreSQL/Mind/浏览器仍需独立环境验收。
- Bad:把 pending 记录放在 authorization await 之后、在 confirmation 中重新授权原 Mind Session、或为 guarded write fallback 到普通 insert。
6. Tests Required
- 使用可控 Promise latch 覆盖 authorization、service、transaction、publish 各 await 点的 pause/disconnect/replacement;关键竞态连续 100 次运行。
- 断言
message.created只在 DB commit 后 publish,terminal/guard 失败不写库、不 ACK、不 publish;独立 PostgreSQL 测试配置TEST_DATABASE_URL后再验证真实 rollback/commit 线性化。 - registry 重构测试必须锁定 façade 的 canonical cleanup/plugin replacement、精确 scope 发布与二次授权、presence 通知、pending-send timeout/connection-loss 映射和 confirmation 单次 claim;拆分后 connection/generation 与 pending/terminal 状态各自只能有一个 owner。
7. Wrong vs Correct
Wrong
const pending = new Map<string, PendingSend>();
const connections = new Map<WebSocket, Connection>();
// handler 或 publisher 再维护自己的 connection/generation/pending 真相。
Correct
const store = createOneTalkConnectionStore({ cutoverPolicy });
const publisher = createOneTalkMindPublisher({ authorization, store, onPublishFailure });
const pendingSends = createOneTalkPendingSendCoordinator({ authorization, store });
const registry = { ...store, ...publisher, ...pendingSends };
协作者共享同一 canonical store,façade 维持调用方兼容;不会因拆文件而改变 guard、publish 或 send 的既有时序。
Scenario: 环境驱动的 Mind HTTP 授权
1. Scope / Trigger
- Trigger:服务端需要通过独立的本地 Mind 授权模拟运行 OneTalk HTTP/WS 联调,同时保留非开发环境的安全默认。
- Scope:
apps/server/src/config.ts、apps/server/src/mind-authorization.ts、apps/server/src/app.ts、serverdevscript 和apps/mind-test-harness/。 - Excluded:真实 Mind Session/Cookie 认证、业务授权后台、数据库权限和请求级认证逻辑不由本地模拟代替。
2. Signatures
loadConfig(environment: Record<string, string | undefined>): ServerConfig
// ServerConfig.environment: "development" | "non_development"
createApp(config: ServerConfig, dependencies?: AppDependencies): FastifyInstance
3. Contracts
loadConfigtrimNODE_ENV;只有值严格为development时返回environment: "development",空值、缺失、大小写变体和其它值返回non_development。loadConfig在NODE_ENV=development时读取MIND_AUTH_BASE_URL、MIND_PAGE_ORIGIN、ONETALK_PLUGIN_ORIGINS和可选MIND_AUTH_TIMEOUT_MS;其中 HTTP 只允许 loopback Origin,供mind-test-harness的 Mind 授权模拟使用。createApp在未显式提供dependencies.authorization时使用配置的createMindAuthorizationReader;显式 reader 在所有环境优先。development 不再从ONETALK_DEV_*构造进程内授权 fixture。- Mind 授权模拟只拥有独立的本地固定 fixture,Bright 仍通过两个 HTTP endpoint 验证 binding/Cookie/status/body;模拟不读取 Mind DB、不推断请求主体,也不改变生产授权边界。
apps/server/package.json的devscript 明确设置NODE_ENV=development;其它启动路径不设置 bypass。installWebsocket未传 authorization 时仍使用 fail-closed reader,不能因 server dev 默认而改变独立安装语义。
4. Validation & Error Matrix
| Condition | Result |
|---|---|
NODE_ENV=development 且 Mind 授权模拟配置完整 |
createApp 通过 Mind HTTP adapter 授权;模拟返回允许时匹配 scope 的 HTTP/WS 请求可进入已有业务边界 |
NODE_ENV=development 且 MIND_AUTH_* 配置缺失/非法 |
启动失败,不创建任意 scope 的默认授权 |
NODE_ENV=development 但 Mind 授权模拟不可用 |
授权返回 authorization_unavailable,不绕过网络边界 |
| 缺失、空值、未知值或非精确 development | createApp 默认 authorization_unavailable,fail-closed |
| development 下显式注入拒绝 reader | 按注入 reader 拒绝,不被 bypass 覆盖 |
| development 下显式注入允许 reader | 按注入 reader 返回其 binding/version/permissions |
独立 installWebsocket 未注入 reader |
仍返回 authorization_unavailable |
5. Good / Base / Bad Cases
- Good:需要时显式运行
pnpm dev:harness启动本地 Mind 授权模拟,createApp通过固定 HTTP adapter 授权;pnpm dev与 server/extension 主流程不依赖该低优先级工具,测试/生产仍按各自 URL/HTTPS 规则运行。 - Base:真实 Mind HTTP auth 通过同一个
createMindAuthorizationReader或AppDependencies.authorization接入,环境选择不改变业务授权调用。 - Bad:在
createApp中无条件 allow、把NODE_ENV缺失当作 development,或在 HTTP header/host 上推断开发模式。
6. Tests Required
- 配置测试覆盖 development(含首尾空格)、loopback HTTP、缺失、空值、test/staging/production、大小写变体和拼写错误。
- App/adapter 测试覆盖默认 development HTTP/WS 授权、Mind 授权模拟不可用、non-development/unknown 默认拒绝,以及显式允许/拒绝 reader 优先级。
- WebSocket 安装测试覆盖独立
installWebsocket的默认 fail-closed;断言 bypass 标识和凭证不出现在可见响应。 - 根级 typecheck、build、test、format check 和 server
db:check必须保持通过。
7. Wrong vs Correct
Wrong
const authorization = dependencies.authorization ?? createUnavailableAuthorizationReader();
Correct
const authorization =
dependencies.authorization ??
(config.mindAuthorization
? createMindAuthorizationReader(config.mindAuthorization)
: createUnavailableAuthorizationReader());
授权默认值必须来自固定的 Mind HTTP 配置或显式注入,不能在应用组合层无条件 allow。
Scenario: Bright 历史读取与 Mind 联调页
1. Scope / Trigger
- Trigger:Bright 事实消息已经由 OneTalk repository 持久化,需要供 Mind 页面读取历史,并通过同一服务接收授权后的实时状态/消息事件。
- Scope:
apps/server/src/http/onetalk/、apps/server/src/onetalk/read-cursor.ts和apps/server/src/websocket/registry.ts的跨层契约;Mind 联调页本身归apps/mind-test-harness/,server 不注册/harness页面路由。 - Excluded:Mind legacy 消息源、插件同步代理、发送 outbox 和未确认发送事实不属于此读取边界。
2. Signatures
GET /api/bright/onetalk/accounts/:channelAccountId/conversations
GET /api/bright/onetalk/accounts/:channelAccountId/conversations/:conversationId
GET /api/bright/onetalk/accounts/:channelAccountId/conversations/:conversationId/messages?fromSentAtMs=<inclusive>&toSentAtMs=<exclusive>&limit=1..100&cursor=<opaque>
OneTalkReadService.listConversations({ scope, query?, cursor?, limit? }) -> result
OneTalkReadService.readConversation({ scope, conversationId }) -> result
OneTalkReadService.readHistory({ scope, conversationId, fromSentAtMs?, toSentAtMs?, cursor?, limit?, purpose? }) -> result
encodeOneTalkListCursor(cursor) -> string
decodeOneTalkListCursor(value) -> cursor | null
encodeOneTalkHistoryReadCursor(cursor) -> string
decodeOneTalkHistoryReadCursor(value) -> cursor | null
3. Contracts
- HTTP scope 只取路径
channelAccountId加 Mind Session 授权返回的完整mindScope;不接受客户端 user/workspace/device header 作为主体。每个请求都使用OneTalkAuthorizationReader.authorize({ connectionType: "mind_page", operation: "read", scope: { channelAccountId }, cookie? })。 - 会话只读取
conversation_kind = "direct"的显式 direct fact。列表/详情返回共享CenterConversation:name/avatarUrl为当前 profile row 的实时值,participantIds固定为空数组,unreadCount固定为 0;latestMessageId来自已确认业务锚点,latestMessageAtMs来自 OneTalk 会话列表活动时间,两者允许独立为空。 - 列表 query 先 trim,按名称或 conversationId 做 Unicode-insensitive substring;列表直接读取
onetalk_conversation.last_message_at_ms,排序与 cursor 都使用绑定账号、query、asOf、(latestMessageAtMs, conversationId)的同一 keyset。实时消息只单调推进会话时间;活跃会话在跨页期间前移时由列表刷新重新出现。profile 必须以同一账号与页面会话复合键另行受限读取,再在内存组合;不得把实时资料当作 SQL JOIN 例外。 - 历史 cursor 不透明且独立绑定账号、会话、from/to 半开窗口、asOf 和
(sentAtMs, messageId)keyset;时间窗为from <= sentAtMs < to。内部7777summary listener 必须同时提供两端时间。 - HTTP history 与
message.created都只返回 sharedOneTalkCenterMessage:语义readStatus加同一content.version=1的text | image | file | business_card | inquiry | orderunion。business_card在消息事实中严格是{ version: 1, kind: "business_card" }marker;read projection 先按同一channelAccountId + conversationId受限读取当前 profile,再以内存方式扩展为contactName、companyName、countryCode、avatarUrl四项 view 字段。没有 profile 时返回 marker,profile 部分缺失时对应字段为null,且 view 不得写回 message/profile。read projection 不得解 Base64、custom.data、contentType、卡片原始正文/params、文件名或 URL fallback;它只复制 shared contract 已批准的字段。 - Mind 联调页由
apps/mind-test-harness/提供,只通过同源 Bright HTTP/WS 访问数据;页面侧的运行时形状校验、文本转义、图片/文件展示和去重边界见 mind-test-harness 规范,不属于 server 路由契约。 - 插件
plugin.status、sync.status和message.created只发送给当前仍通过二次 read 授权的精确 Mind scope;消息必须遵循数据库提交 → plugin ACK → Mind publish。public HTTP CORS 只允许精确 Origin 和Content-Type;internal summary listener 不注册 CORS。
4. Validation & Error Matrix
| Condition | Result |
|---|---|
| Cookie/Session 授权上下文缺失或无效 | HTTP 401 auth_required 或授权适配器稳定拒绝 |
| 路径账号与授权返回 scope 不一致,或请求带未允许身份 header | HTTP 403 scope_mismatch |
| 授权拒绝/撤销/版本变化 | HTTP 403 与对应稳定授权错误码 |
| 授权依赖不可用 | HTTP 503,authorization_unavailable |
limit 非整数或不在 1..100 |
HTTP 400,invalid_limit |
| cursor 无法解码或跨账号/会话使用 | HTTP 400,invalid_cursor |
| internal summary 缺少 from/to,或 from >= to | HTTP 400,invalid_time_range |
| 会话不存在 | HTTP 404,conversation_not_found |
| history 尚未完整且请求 internal summary | HTTP 503 history_incomplete,Retry-After: 30 |
| 数据库读取失败 | HTTP 503,database_unavailable;不返回内部异常 |
| 插件无在线连接 | 仍可读历史;响应/事件状态为 offline,实时发送能力保持禁用 |
消息 kind 为 business_card 且存储 content 含客户资料字段 |
数据库 CHECK/应用 exact-shape 拒绝;迁移先归一化为 marker |
| 名片读取时同账号同会话没有 profile | 返回 marker,不回退到登录人或 item.contact |
| 名片 profile 仅有部分批准字段 | 返回 view,其余批准字段为 null |
| profile 属于其他账号或会话 | 不参与组合;按无 profile 处理 |
5. Good / Base / Bad Cases
- Good:页面先读取 Bright direct list/detail/history,保存并回传 opaque cursor,再连接 WS;断线刷新依靠历史恢复,收到重复
message.created不重复渲染。 - Base:插件状态来自当前进程 registry;页面/接口显示
offline不代表历史不可读,当前 profile 变化可以实时反映到列表名称和头像;名片没有 profile 时仍能稳定返回 marker。 - Bad:HTTP 路由访问 Mind legacy 表或代理插件接口,使用 anchor/latestMessageId 作为 cursor,放宽 direct filter,在消息观察时使用登录人的
item.contact,把读取 view 写回 message,或把未提交消息先推给页面。
6. Tests Required
- HTTP:public 列表、详情、历史首/后续页、internal summary gate、direct filter、profile 实时内存组合、query、独立 cursor/asOf、半开窗口、scope/CORS 校验、授权失败、未知会话、offline 状态、非法 limit/cursor/time range、数据库失败和无秘密响应;六类 content 都必须只含 shared normalized 字段,业务卡必须验证 marker→同账号同会话 profile view、无 profile marker、部分 profile
null,且不能恢复 Base64 或 raw SDK 字段。 - WebSocket:Mind hello/accepted、plugin online/offline、sync status、精确 scope、二次授权、提交后 ACK/publish 顺序、history/live 对同一事实的公开投影等价,以及断线后的连接清理。
- Mind 联调页行为(offline send gate、list/history query paging、异步代际 fence、active-scope guard、runtime shape validation、文本转义、image load error、conditional file links 和去重关键字段)按 mind-test-harness 规范手工验证;server 自动化测试只覆盖 Bright public HTTP/WS 路径与稳定错误。
- PostgreSQL:复合索引上的 direct-only keyset 分页跨页不丢不重,cursor 与 anchor 独立,profile 两次受限读取与内存组合、asOf 和真实 migration 后读取仍按账号/会话隔离;历史业务卡仅能存 marker,旧行清理后数据库 CHECK 拒绝附带资料字段。
7. Wrong vs Correct
Wrong
const cursor = conversation.latestMessageId;
return mindLegacyMessages(conversationId, cursor);
Correct
const cursor = decodeOneTalkHistoryReadCursor(request.query.cursor);
const page = await readService.readHistory({ scope, conversationId, cursor, limit });
return reply.send(page);
读取边界只消费 Bright 事实表和独立 keyset cursor;同步 anchor 仍只表达插件同步状态。
// Wrong: 把消息观察时拿到的登录人/发送者 contact 当成会话客户。
const content = normalizeBusinessCard(item, item.contact);
await messageRepository.insertMessage(context, source, { ...message, content });
// Correct: message 事实只存 marker;读取时按受限会话 profile 组合 view。
const stored = { version: 1, kind: "business_card" } as const;
const conversation = await conversationRepository.read(scope, conversationId);
const profile = await contactProfileRepository.read(scope.channelAccountId, conversation.id);
return projectCenterMessage({ ...message, content: stored }, profile ?? undefined);
Scenario: OneTalk WS 固定协议内核与静态已认证路由
1. Scope / Trigger
- Trigger:新增、删除或重组 OneTalk server 的 inbound WebSocket frame,或调整 Plugin 与 Mind endpoint 的职责边界。
- Scope:
websocket/protocol-kernel.ts、websocket/handler.ts、websocket/endpoint-routes.ts、websocket/plugin/index.ts、websocket/plugin/flows/{sync-flows,profile-flow,observation-batcher,send-confirmation-flow}.ts、websocket/mind/{index,send-request-flow,session-authorization,publisher}.ts与websocket/authenticated-router.ts;不改变 shared contract、registry/store、pending-send 或领域事实的状态所有权。 - Excluded:wire version/error-code 变更、动态模块注册、extension frame routing、send/profile/buyer-fact 的业务顺序调整。唯一既定的 output 收紧是 confirmed
send.result.message投影为既有OneTalkCenterMessage,不允许以修改 shared decoder 接受 raw message 字段代替。
2. Signatures
createOneTalkProtocolKernel<TAuthenticatedFrame extends OneTalkFrame>({
session,
canAdmit,
expectedConnectionType,
isAuthenticatedClientFrame,
onHello,
onAuthenticatedFrame,
// exact error/close/diagnostic callbacks
}): OneTalkProtocolKernel;
createOneTalkAuthenticatedRouter(routes): OneTalkAuthenticatedRouter<TContext>;
// routes: type + connectionType + authorization + operation + handler
createOneTalkWebSocketHandler(
{ expectedConnectionType, authorization, registry, ...sharedPorts },
{ create: endpointCallbacks },
): (socket: WebSocket) => void;
createOneTalkPluginWebSocketHandler(pluginOptions): (socket: WebSocket) => void;
createOneTalkMindWebSocketHandler(mindOptions): (socket: WebSocket) => void;
createOneTalkEndpointAuthenticatedRouter(endpoint, { plugin, mind_page }): OneTalkAuthenticatedRouter<T>;
assertOneTalkEndpointFrameSets({ plugin, mind_page }): void;
createOneTalkSendRequestFlow({ registry, sendFrame, ...narrowPorts }): OneTalkSendRequestFlow;
createOneTalkSendConfirmationFlow({ registry, service, ...narrowPorts }): OneTalkSendConfirmationFlow;
createOneTalkProfileFlow({ profileService, registry, reauthorize, ...narrowPorts }): OneTalkProfileFlow;
TAuthenticatedFrame 必须由 type predicate 从完整 decoded OneTalkFrame 收窄;handler 不得在 callback 边界用类型断言伪造已认证 client frame。
3. Contracts
handler.ts是每 socket 唯一的共享 transport runtime:FIFO、字节限制、JSON parse、strict decode、cutover admission、固定 endpoint connection type、inbound/outbound diagnostics、socket close/unregister 与共享 session reauthorization primitive。它注入 endpoint callback,不能再按connectionType选择 Plugin/Mind hello 或业务 Flow,也不能建立 shadow authentication/session state。plugin/index.ts只拥有 Plugin hello/binding authorization、heartbeat、discovery/sync/observation/profile/buyer facts 与send.confirmation;mind/index.ts只拥有 Mind Cookie/session hello、heartbeat、send.request和 Mind subscriber lifecycle。index.ts仍是唯一 Fastify WebSocket 安装点,只按 URL 组合这两个 fixed handler。- 未认证连接只允许
ws.hello;hello 后再次收到ws.hello是unknown_request。ws.hello永远不进入 authenticated router,endpoint bootstrap 保留accepted -> register -> anchor snapshot顺序。 - 已认证 frame 先检查 session connection type 与 scope,再分类是否为 client route。因此 decoder 接受但不是 client frame 的错 scope 输入必须是
scope_mismatch并关闭1008;同 scope 输入才是unknown_request,且不关闭连接。 - authenticated route set 从
ONETALK_CLIENT_FRAME_TYPES排除ws.hello推导。assertOneTalkEndpointFrameSets要求 Plugin/Mind 两端都恰有一个heartbeat,其余 frame 必须恰有一个 endpoint owner;它在 Fastify route 注册前拒绝缺失、重复、未知和 hello route。endpoint router 在调用 collaborator 前同时校验 frame 的 connection type 和该 endpoint 的 ownership;禁止模块副作用、运行时自动发现、fallback route 或直接 dispatch 绕过 endpoint view。 - 每个 route metadata 显式声明
connectionType、authorization: "session" | "pending_send"和 operation。普通 session route 仍经过现有 binding/scope/version/permission/cutover guard;send.request/send.confirmation的pending_send策略只委托既有 registry coordinator,不能复制或绕过其授权窗口、pending/terminal state。 - endpoint reauthorization 共用同一 binding/scope/version/canonical permission primitive,但 endpoint 自己选择 operation。授权 reader 明确返回
allowed: false时,Plugin/Mind 都必须先发送稳定ws.error,再以1008关闭;reader 已允许、但现有连接或返回 permission 缺失时,仍只发送authorization_rejected,保持原有 error-only 行为。Cookie 只在 Mind endpoint 的单次 session authorization 内存中转发,不能进入 wire 或 diagnostics。 - kernel/router/handler 只做固定 guard、选择和委托。connection/generation、pending-send、commit guard 与 checkpoint 保持原有唯一 owner;每条 plugin connection 的 sync Flow 独占 discovery fragment timer/Set 和 ObservationBatcher。Mind request Flow 只编排
send.request -> registry.requestSend -> send.result;Plugin confirmation Flow 才拥有 confirmation observation/publish。profile Flow 只编排 guarded ingestion、post-write fences、conversation update 与 ACK;这些 Flow 都不能建立第二份连接、pending、timer 或 durable state。 - send Flow 在 request 前后保留 policy fence;confirmation 只能使用 coordinator 已同步 claim 的 pending snapshot 与 guard。accepted 的顺序固定为 durable observation ->
message.created-> conversation update -> terminalsend.result,matching duplicate 不重发message.created。唯一 server output seam 必须用toOneTalkCenterMessage把 accepted 与 duplicate 的send.result.message投影为 strict center fields。 - profile Flow 只接收 typed
contact.profile.observed、canonical source context、store-created guard 与 handler 注入的 reauthorization/close/writer ports。future-skew 必须在 second authorization 前以profile_observed_at_future结束;guarded write 成功后仍须依次确认 policy、guard、canonical connection、reauthorization,再对writtenConversationIds发布 update,最后用 decoded input 的原始 profile count ACK。 - observation Flow 保持 database commit -> plugin ACK -> Mind publish;仅
live + accepted发布message.created和conversation.updated,duplicate/anomaly/rejected/history/incremental 不发布。completion 必须先等待同一 Flow 的 observation flush,再调用completeSync、发布sync.status与 completionconversation.updated。
4. Validation & Error Matrix
| Condition | Result |
|---|---|
| payload 超限、非 text 或 strict decode 失败 | 既有稳定 error 后关闭 1003;不执行 admission 或业务 handler |
| cutover 不准入 | 关闭 1013/authorization_unavailable;不发业务 frame |
| endpoint connection type 不匹配 | scope_mismatch 后关闭 1008 |
| 未认证的非 hello frame | auth_required 后关闭 1008 |
| 已认证后再次 hello | unknown_request;保持既有连接行为 |
| 已认证且 scope/connection type 不匹配(包括 non-client frame) | scope_mismatch 后关闭 1008,优先于 client classification |
| 已认证、scope 匹配但 frame 非 client | unknown_request;不调用 route handler |
| route 表缺失/重复/未知/hello entry | factory 构造失败;服务不能以不完整 registry 启动 |
| route metadata connection type 不匹配 | authorization_rejected;不调用业务 collaborator |
| endpoint router 收到非本端 frame 或其 route 无本端 ownership | 拒绝且不调用 route collaborator |
| endpoint route set 遗漏任一端 heartbeat、业务 frame 双归属或无归属 | Fastify route 注册失败 |
reauthorization reader 返回 allowed: false |
稳定 ws.error 后关闭当前 socket 1008 |
| reader 已允许但连接/decision 缺必要 permission | authorization_rejected,保持既有 error-only 行为 |
confirmed send.result 含完整 OneTalkMessage 的 raw-only 字段 |
shared decoder 拒绝;Flow 必须投影为 OneTalkCenterMessage,不得放宽 contract |
| profile write 后 policy/guard/canonical/reauthorization 任一失效 | 不 publish 新 update,且无 late contact.profile.ack |
5. Good / Base / Bad Cases
- Good:shared handler 只组合 transport callback 与窄错误 callback;Plugin/Mind endpoint 分别拥有 hello 和业务 dispatch,kernel 拥有固定分派顺序,静态 endpoint 表完整列出当前 authenticated v5 frame,send/profile Flow 只接收已收窄 frame 与窄端口。
- Base:新增 client frame 时,contract list 变化使 typed route table 与 runtime validation 都要求在同一改动中添加 metadata/handler/test;这不是协议兼容层。
- Bad:在 shared handler 中以
connectionType分派业务 Flow、在 Flow handler 中 parse raw WebSocket data、先判 unknown 再判 session scope、把 hello 注册为普通 route、让 endpoint router dispatch 绕过 ownership、为 send 再实现 authorization/pending map,或将完整OneTalkMessage直接写入send.result。
6. Tests Required
- router unit test 从 contract list 推导所有非 hello client type;覆盖完整 endpoint 表、两端 heartbeat、missing、duplicate、unknown、hello、单 owner 与 metadata/endpoint connection mismatch,且 mismatch 不调用 collaborator。
- WebSocket regression 必须验证 FIFO/strict decode、unauthenticated gate、hello/repeated-hello、endpoint/cutover,以及同 scope non-client 为
unknown_request、错 scope non-client 为scope_mismatch + 1008的优先级。 - WebSocket regression 必须分别覆盖 Plugin/Mind 的 operation authorization denial(
ws.error后1008close)及 allowed-but-missing-read(error-only、不关闭);Mind Cookie 只作为 authorization adapter 输入,不能出现在 diagnostics 或 wire。 - 保留真实 wire matrix 与 sync/observation/send/profile/buyer focused tests,验证所有 client frame 的可见输出、commit -> ACK -> publish、pending-send terminal 和 post-write fence;accepted 与 matching-duplicate
send.result都必须可被decodeOneTalkFrameround-trip 接受,并断言 duplicate 不发布;sync completion 用 deferred observation latch 验证 flush 未完成前不得调用completeSync。 - 运行 server typecheck/build、focused source 与 compiled tests、Oxfmt 和
git diff --check;若遗留 generated test 无法导入未导出的旧 contract symbol,单独记录为非本路由 diff 的基础设施问题,不修改生成产物掩盖它。
7. Wrong vs Correct
// Wrong: non-client classification can hide a cross-session frame from the scope guard.
if (!isAuthenticatedClientFrame(frame)) return sendUnknown(frame);
if (!isSameOneTalkScope(session.scope, frame.scope)) return closeScopeMismatch(frame);
// Correct: a decoder-valid frame must belong to the current session before route classification.
if (!isSameOneTalkScope(session.scope, frame.scope)) return closeScopeMismatch(frame);
if (!isAuthenticatedClientFrame(frame)) return sendUnknown(frame);
return router.dispatch(context, frame);
// Wrong: the shared transport chooses endpoint business behavior.
if (state.connectionType === "plugin") return pluginSyncFlow.handle(frame);
return mindSendFlow.handle(frame);
// Correct: each fixed endpoint injects only its own hello and authenticated callbacks.
return createOneTalkWebSocketHandler(
{ ...sharedOptions, expectedConnectionType: "plugin" },
{ create: createPluginEndpointCallbacks },
);