Files
trade-message-center/.trellis/spec/server/backend/service-foundation.md
T

19 KiB
Raw Blame History

服务端基础设施契约

1. Scope / Trigger

  • Trigger:服务端首次引入 Fastify 启动、WebSocket 传输和 PostgreSQL ORM。
  • Scopeapps/server/src/ 的配置、应用组合、健康路由、WebSocket 生命周期和数据库连接。
  • ExcludedOneTalk 业务字段规则和 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
startServer(): Promise<void>

3. Contracts

  • Required environment keys: HOST, PORT, DATABASE_URL
  • Optional NODE_ENV is normalized at the configuration boundary; only exact trimmed development enables the development-only loopback Mind HTTP configuration, while missing/unknown values remain fail-closed。
  • GET /health returns { "status": "ok" }
  • WebSocket routes are GET /ws/plugin and GET /ws/mind; each route binds its connection type before upgrade and checks its exact Origin allowlist. GET /ws is 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 code 1003, and connection/handler errors close with 1011
  • createApp never calls listen; only entry.ts may bind the port。
  • Database resources are closed through the app onClose hook; URL and credentials never enter responses or logs。
  • createApp composes one injected/default OneTalkService, OneTalkProfileService and OneTalkReadService over the same database.db; AppDependencies may 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 Mind message.createdmessage.created 与 HTTP history 都必须从同一 normalized JSONB fact 投影 shared OneTalkCenterMessage,不得暴露顶层 text/contentType 或 raw payload。
  • contact.profile.observed is 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.profileService is 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 }, call app.ready(), verify /health, then observe one close call。
  • Base: production startup creates a Drizzle client from DATABASE_URL and 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 200 and exact { status: "ok" } response。
  • Lifecycle test asserts injected database close runs once on app.close()
  • WebSocket registration test asserts websocketServer exists, GET /ws/plugin/GET /ws/mind are registered, and GET /ws is 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

  • TriggerMind 授权、Bright WebSocket 生命周期和 OneTalk 事实写入共享多个异步边界,需要避免 pause、连接替换或迟到回报穿透副作用。
  • Scopecutover-policy.tswebsocket/registry.tswebsocket/handler.tsonetalk/service.ts 和 guarded repository ports。
  • ExcludedMind 的远端 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 控制 admissionpause/resume 可以恢复 Bright v3,不依赖或保存 firstBrightFactWritten/markBrightFactWritten
  • sendRequestId 的 reserve、phase、terminal transition、timeout、disconnect、pause 和 late confirmation 由 registry 单一 owner 管理;所有 wire send 后结果不可自动重试。
  • 远程 observation/discovery/sync/confirmation 的 database side effect 必须带同一 canonical connection/generation/policy guard。guard 失效必须使事务回滚,不返回伪造的 accepted/duplicate。

4. Validation & Error Matrix

条件 结果
相同 ID 的并发 send 在授权等待期间 一个 attempt,另一个 rejected_before_send/duplicate_request
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;后续输入 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 后 publishterminal/guard 失败不写库、不 ACK、不 publish;独立 PostgreSQL 测试配置 TEST_DATABASE_URL 后再验证真实 rollback/commit 线性化。

7. Wrong vs Correct

Wrong

await authorizeMind();
await repository.insertMessage(context, source, message);

Correct

const epoch = policy.capture();
const guard = registry.createCommitGuard(canonicalConnection, epoch);
await repository.guardedInsertMessage(context, source, message, guard);
guard.assertValid();

Scenario: 环境驱动的 Mind HTTP 授权

1. Scope / Trigger

  • Trigger:服务端需要通过独立的本地 Mind HTTP mock 运行 OneTalk HTTP/WS 联调,同时保留非开发环境的安全默认。
  • Scopeapps/server/src/config.tsapps/server/src/mind-authorization.tsapps/server/src/app.ts、server dev script 和 apps/mind-http-mock/
  • Excluded:真实 Mind Session/Cookie 认证、业务授权后台、数据库权限和请求级认证逻辑不由本地 mock 代替。

2. Signatures

loadConfig(environment: Record<string, string | undefined>): ServerConfig
// ServerConfig.environment: "development" | "non_development"
createApp(config: ServerConfig, dependencies?: AppDependencies): FastifyInstance

3. Contracts

  • loadConfig trim NODE_ENV;只有值严格为 development 时返回 environment: "development",空值、缺失、大小写变体和其它值返回 non_development
  • loadConfigNODE_ENV=development 时读取 MIND_AUTH_BASE_URLMIND_PAGE_ORIGINONETALK_PLUGIN_ORIGINS 和可选 MIND_AUTH_TIMEOUT_MS;其中 HTTP 只允许 loopback Origin,供独立 mind-http-mock 使用。
  • createApp 在未显式提供 dependencies.authorization 时使用配置的 createMindAuthorizationReader;显式 reader 在所有环境优先。development 不再从 ONETALK_DEV_* 构造进程内授权 fixture。
  • Mind mock 只拥有独立的本地固定 fixtureBright 仍通过两个 HTTP endpoint 验证 binding/Cookie/status/bodymock 不读取 Mind DB、不推断请求主体,也不改变生产授权边界。
  • apps/server/package.jsondev script 明确设置 NODE_ENV=development;其它启动路径不设置 bypass。
  • installWebsocket 未传 authorization 时仍使用 fail-closed reader,不能因 server dev 默认而改变独立安装语义。

4. Validation & Error Matrix

Condition Result
NODE_ENV=development 且 Mind HTTP mock 配置完整 createApp 通过 Mind HTTP adapter 授权;mock 返回允许时匹配 scope 的 HTTP/WS 请求可进入已有业务边界
NODE_ENV=developmentMIND_AUTH_* 配置缺失/非法 启动失败,不创建任意 scope 的默认授权
NODE_ENV=development 但 Mind HTTP mock 不可用 授权返回 authorization_unavailable,不绕过网络边界
缺失、空值、未知值或非精确 development createApp 默认 authorization_unavailablefail-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 通过同一个 createMindAuthorizationReaderAppDependencies.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 mock 不可用、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

  • TriggerBright 事实消息已经由 OneTalk repository 持久化,需要供 Mind 页面读取历史,并通过同一服务接收授权后的实时状态/消息事件。
  • Scopeapps/server/src/http/onetalk.tsapps/server/src/http/harness.tsapps/server/src/onetalk/history.tsapps/server/src/websocket/registry.ts 的跨层契约。
  • ExcludedMind 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
GET /harness -> text/html (native browser page)

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。列表/详情返回共享 CenterConversationname/avatarUrl 为当前 profile row 的实时值,participantIds 固定为空数组,unreadCount 固定为 0,latest 字段来自已持久化 message fact。
  • 列表 query 先 trim,按名称或 conversationId 做 Unicode-insensitive substring;列表 cursor 不透明且绑定账号、query、asOf、(latestMessageAtMs, conversationId) keyset。当前 profile left join 是实时资料例外。
  • 历史 cursor 不透明且独立绑定账号、会话、from/to 半开窗口、asOf 和 (sentAtMs, messageId) keyset;时间窗为 from <= sentAtMs < to。summary purpose communication_summary_read 必须同时提供两端时间。
  • HTTP history 与 message.created 都只返回 shared OneTalkCenterMessage:语义 readStatus 加同一 content.version=1text | image | file union。read projection 不得解 Base64、custom.datacontentType、文件名或 URL fallback。
  • /harness 只通过同源 Bright HTTP/WS 访问数据;浏览器对 list/detail/history、scope、page、语义消息和稳定错误做运行时形状校验,展示原始 ID,按 scope/account/conversation/messageId 去重。它按 content.kind 转义渲染文本、以真实 <img> 加载图片预览并显示加载失败、为文件保留元数据且只在 URL 存在时提供带 noopener noreferrer 的用户触发链接;不解 raw 字段、不自动下载、不增加媒体发送。
  • 插件 plugin.statussync.statusmessage.created 只发送给当前仍通过二次 read 授权的精确 Mind scope;消息必须遵循数据库提交 → plugin ACK → Mind publish。HTTP CORS 只允许精确 Origin 和 Content-Type/X-Mind-Purpose

4. Validation & Error Matrix

Condition Result
Cookie/Session 授权上下文缺失或无效 HTTP 401 auth_required 或授权适配器稳定拒绝
路径账号与授权返回 scope 不一致,或请求带未允许身份 header HTTP 403 scope_mismatch
授权拒绝/撤销/版本变化 HTTP 403 与对应稳定授权错误码
授权依赖不可用 HTTP 503authorization_unavailable
limit 非整数或不在 1..100 HTTP 400invalid_limit
cursor 无法解码或跨账号/会话使用 HTTP 400invalid_cursor
summary 缺少 from/to,或 from >= to HTTP 400invalid_time_range
会话不存在 HTTP 404conversation_not_found
history 尚未完整且请求 summary HTTP 503 history_incompleteRetry-After: 30
数据库读取失败 HTTP 503database_unavailable;不返回内部异常
插件无在线连接 仍可读历史;响应/事件状态为 offline,实时发送能力保持禁用

5. Good / Base / Bad Cases

  • Good:页面先读取 Bright direct list/detail/history,保存并回传 opaque cursor,再连接 WS;断线刷新依靠历史恢复,收到重复 message.created 不重复渲染。
  • Base:插件状态来自当前进程 registry;页面/接口显示 offline 不代表历史不可读,当前 profile 变化可以实时反映到列表名称和头像。
  • BadHTTP 路由访问 Mind legacy 表或代理插件接口,使用 anchor/latestMessageId 作为 cursor,放宽 direct filter,或把未提交消息先推给页面。

6. Tests Required

  • HTTP:列表、详情、历史首/后续页、direct filter、profile realtime join、query、独立 cursor/asOf、半开窗口、summary gate、scope/CORS 校验、授权失败、未知会话、offline 状态、非法 limit/cursor/time range、数据库失败和无秘密响应;text/image/file 必须只含 normalized content。
  • WebSocketMind hello/accepted、plugin online/offline、sync status、精确 scope、二次授权、提交后 ACK/publish 顺序、history/live 对同一事实的公开投影等价,以及断线后的连接清理。
  • HarnessGET /harness 的 HTML 标记、Bright HTTP/WS 路径、summary header、offline send gate、list/history query paging、异步代际 fence、active-scope guard、runtime shape validation、文本转义、image load error、conditional file links 和去重关键字段。
  • PostgreSQL:复合索引上的 direct-only keyset 分页跨页不丢不重,cursor 与 anchor 独立,profile left join、asOf 和真实 migration 后读取仍按账号/会话隔离。

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 仍只表达插件同步状态。