@alexsun-top/opencode-chat-room 0.8.2 → 0.8.3

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 (92) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +466 -188
  5. package/package.json +8 -5
  6. package/packages/chat-room-channeld/README.md +25 -3
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +5 -0
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +17 -2
  11. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  12. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  13. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  14. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  15. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  16. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  17. package/packages/chat-room-channeld/src/protocol.ts +1 -0
  18. package/packages/chat-room-channeld/src/state.ts +73 -97
  19. package/packages/chat-room-channeld/src/stats.ts +140 -109
  20. package/server/assets/base.css +3 -1
  21. package/server/assets/chat/admin-badge.js +32 -30
  22. package/server/assets/chat/admin.js +198 -161
  23. package/server/assets/chat/announcements.js +295 -208
  24. package/server/assets/chat/attachment-store.js +106 -75
  25. package/server/assets/chat/attachments.js +686 -441
  26. package/server/assets/chat/chat-background.js +185 -156
  27. package/server/assets/chat/clipboard.js +44 -25
  28. package/server/assets/chat/confirm-dialog.js +36 -33
  29. package/server/assets/chat/copy-action.js +40 -40
  30. package/server/assets/chat/create-room-dialog.js +50 -47
  31. package/server/assets/chat/diagram-viewer.js +293 -234
  32. package/server/assets/chat/doc-preview.js +507 -441
  33. package/server/assets/chat/editor.js +423 -335
  34. package/server/assets/chat/events.js +637 -510
  35. package/server/assets/chat/files.js +476 -430
  36. package/server/assets/chat/history-loader.js +79 -73
  37. package/server/assets/chat/icons.js +9 -11
  38. package/server/assets/chat/image-zoom.js +239 -176
  39. package/server/assets/chat/index.js +2 -3
  40. package/server/assets/chat/install-prompt.js +86 -66
  41. package/server/assets/chat/integration-account-schema.js +88 -86
  42. package/server/assets/chat/integration-editor.js +162 -153
  43. package/server/assets/chat/integration-values.js +109 -100
  44. package/server/assets/chat/integrations.js +689 -622
  45. package/server/assets/chat/join-requests.js +408 -358
  46. package/server/assets/chat/locales/de.js +193 -194
  47. package/server/assets/chat/locales/es.js +193 -194
  48. package/server/assets/chat/locales/fr.js +193 -194
  49. package/server/assets/chat/locales/index.js +1 -2
  50. package/server/assets/chat/locales/it.js +193 -194
  51. package/server/assets/chat/locales/ja.js +193 -193
  52. package/server/assets/chat/locales/ko.js +193 -193
  53. package/server/assets/chat/markdown-footnotes.js +134 -102
  54. package/server/assets/chat/markdown.js +547 -403
  55. package/server/assets/chat/members.js +236 -197
  56. package/server/assets/chat/mentions.js +157 -133
  57. package/server/assets/chat/message-cache.js +40 -33
  58. package/server/assets/chat/message-polling.js +280 -227
  59. package/server/assets/chat/message-window.js +74 -55
  60. package/server/assets/chat/messages.js +552 -480
  61. package/server/assets/chat/office-preview.js +46 -45
  62. package/server/assets/chat/palette.js +450 -417
  63. package/server/assets/chat/panels.js +94 -78
  64. package/server/assets/chat/pwa.js +144 -73
  65. package/server/assets/chat/questions.js +372 -302
  66. package/server/assets/chat/recall.js +320 -273
  67. package/server/assets/chat/receipts.js +149 -121
  68. package/server/assets/chat/reminders.js +331 -214
  69. package/server/assets/chat/replies.js +165 -130
  70. package/server/assets/chat/resource-format.js +59 -62
  71. package/server/assets/chat/room-list.js +58 -55
  72. package/server/assets/chat/room-watcher.js +72 -50
  73. package/server/assets/chat/rooms.js +623 -500
  74. package/server/assets/chat/search.js +136 -114
  75. package/server/assets/chat/settings.js +223 -200
  76. package/server/assets/chat/shiki.js +61 -62
  77. package/server/assets/chat/shortcuts.js +212 -187
  78. package/server/assets/chat/side-pane.js +160 -150
  79. package/server/assets/chat/state.js +849 -735
  80. package/server/assets/chat/system-events.js +45 -43
  81. package/server/assets/chat/system-messages.js +57 -56
  82. package/server/assets/chat/task-form.js +178 -182
  83. package/server/assets/chat/task-row.js +158 -155
  84. package/server/assets/chat/tasks.js +653 -587
  85. package/server/assets/chat/viewport.js +32 -29
  86. package/server/assets/chat/window-controls.js +32 -32
  87. package/server/assets/conversation.css +10 -4
  88. package/server/chat-server.ts +9 -1
  89. package/server/chat.html +2 -1
  90. package/server/routes/pages.ts +7 -5
  91. package/server/sw.js +346 -268
  92. package/src/web/integration-rules-editor.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -64,6 +64,8 @@
64
64
  "server/manifest.webmanifest",
65
65
  "server/sw.js",
66
66
  "server/assets",
67
+ "!server/assets/chat/**/*.ts",
68
+ "!server/chat-src",
67
69
  "CHANGELOG.md",
68
70
  "docs/administrator-rooms.md",
69
71
  "README.md",
@@ -74,17 +76,18 @@
74
76
  "registry": "https://registry.npmjs.org/"
75
77
  },
76
78
  "scripts": {
79
+ "build:web": "tsc -p tsconfig.web.json && tsc -p tsconfig.sw.json",
77
80
  "build:cli": "bun build cli.ts --target=node --packages external --outfile dist/cli.js >&2",
78
- "build:channeld-mock": "bun build packages/chat-room-channeld/src/mock-adapter.ts --target=node --packages external --outfile packages/chat-room-channeld/dist/mock-adapter.js >&2",
81
+ "build:channeld-mock": "bun run --cwd packages/chat-room-channeld build:mock",
79
82
  "build:adapter-feishu": "bun scripts/build-feishu-adapter.ts",
80
83
  "build:monaco": "bun scripts/build-monaco.ts",
81
84
  "build:office": "bun scripts/build-office.ts",
82
- "prepack": "bun run build:cli && bun run build:channeld-mock && bun scripts/build-monaco.ts --quiet && bun scripts/build-office.ts --quiet",
85
+ "prepack": "bun run build:web && bun run build:cli && bun run build:channeld-mock && bun scripts/build-monaco.ts --quiet && bun scripts/build-office.ts --quiet",
83
86
  "server": "node cli.ts",
84
87
  "server:bun": "bun cli.ts",
85
88
  "server:deno": "deno run --allow-env --allow-read --allow-write --allow-net cli.ts",
86
- "test": "for file in src/tests/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done && bun test src/tui/test --isolate",
87
- "typecheck": "tsc --noEmit"
89
+ "test": "bun run build:web && bun scripts/check-web-build.ts && bun scripts/check-web-types.ts && for file in src/tests/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done && bun test src/tui/test --isolate",
90
+ "typecheck": "bun run build:web && tsc --noEmit && bun scripts/check-web-types.ts"
88
91
  },
89
92
  "engines": {
90
93
  "node": ">=24.2.0"
@@ -46,6 +46,26 @@ Run the mock adapter on stdio (the host normally spawns it):
46
46
  bun src/cli.ts mock
47
47
  ```
48
48
 
49
+ ## PostgreSQL state
50
+
51
+ Set `CHAT_ROOM_DATABASE_URL` on the host process to use PostgreSQL instead of
52
+ the SQLite `stateFile`. One host process owns the database; the bridge
53
+ serializes writers with an advisory lock but multi-instance Channel D is not
54
+ supported. Unset the variable to roll back to SQLite.
55
+
56
+ Copy an existing SQLite store into an empty PostgreSQL database (stop the host
57
+ first; the SQLite file is never modified):
58
+
59
+ ```sh
60
+ bun src/cli.ts migrate --state ./channeld.sqlite --to-postgres postgresql://...
61
+ ```
62
+
63
+ Migration preserves event and delivery ids, `ingress_seq`, receipts, and echo
64
+ timestamps; legacy echoes that predate `created_at` are backfilled from SQLite
65
+ rowid order so historical echo selection stays stable. It refuses a target that
66
+ already has rows and verifies per-table row counts, maxima, and `ingress_seq`. Rollback is unsetting `CHAT_ROOM_DATABASE_URL`; rows written while
67
+ PostgreSQL was active are not copied back.
68
+
49
69
  Requires Node.js 22.13 or newer (the state store uses `node:sqlite`).
50
70
 
51
71
  Run the suite from a checkout:
@@ -64,7 +84,7 @@ npm run build
64
84
  bun test tests/*.test.ts
65
85
  ```
66
86
 
67
- Bun is still required for tests.
87
+ Bun is still required for the build script and tests.
68
88
 
69
89
  ## Config
70
90
 
@@ -284,7 +304,9 @@ flattened to one line, and redacts credential-shaped `token=…`/`secret=…`
284
304
  fragments. On disable or crash, in-flight deliveries move to `unknown`
285
305
  with the reason; a deliberate host stop also settles remaining in-flight rows as
286
306
  `unknown`, so a centered reload cannot auto-resend them. A host start resets
287
- stale `in_flight` rows from a previous crash to `pending`. If every account becomes disabled at runtime, the host logs
307
+ stale `in_flight` rows from a previous crash to `pending` for adapters that
308
+ declare `send.idempotency = "persistent_delivery_key"`, and to `unknown` for
309
+ every other adapter. If every account becomes disabled at runtime, the host logs
288
310
  `all accounts disabled; host idle until restart` and stays alive; only a startup
289
311
  with zero usable adapters fails. `onUnsupported: drop` skips empty renders; otherwise the
290
312
  payload carries an `attachment/format unsupported` notice. Replies without a
@@ -313,7 +335,7 @@ same terminal result event and message.
313
335
  ## Non-goals (0.1 MVP)
314
336
 
315
337
  - no config hot reload — rule changes require a restart (each delivery still freezes ruleId + ruleVersion + rendered payload);
316
- - no one-click manual resend command — `unknown` deliveries only guarantee no duplicate delivery row if resent (unique idempotency key); they are never auto-resent;
338
+ - no automatic resend of `unknown` deliveries; `channeld retry --config <path> --delivery <id> --force` moves one `unknown` delivery back to `pending` and rejects every other state. It does not start the host. `--force` acknowledges that an adapter without durable idempotency resends from the first message part, so a duplicate is possible;
317
339
  - no full backpressure (high-water marks, pausing ingress, disk quotas) — only per-account queue/process isolation and `rate_limited` backoff;
318
340
  - no attachments, no rule UI, no multi-tenant permission model, no exactly-once
319
341
  guarantee (inbound room notifications are idempotent per event and route, but
@@ -1,11 +1,11 @@
1
- // packages/chat-room-channeld/src/mock-adapter.ts
1
+ // src/mock-adapter.ts
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
 
5
- // packages/chat-room-channeld/src/framing.ts
5
+ // src/framing.ts
6
6
  import { StringDecoder } from "node:string_decoder";
7
7
 
8
- // packages/chat-room-channeld/src/protocol.ts
8
+ // src/protocol.ts
9
9
  var PROTOCOL_VERSION = 1;
10
10
  var EVENT_SCHEMA_VERSION = 1;
11
11
  var MAX_FRAME_BYTES = 1048576;
@@ -25,7 +25,7 @@ function rpcError(id, code, message, data) {
25
25
  return { jsonrpc: "2.0", id, error };
26
26
  }
27
27
 
28
- // packages/chat-room-channeld/src/framing.ts
28
+ // src/framing.ts
29
29
  function parseFrame(line) {
30
30
  const text = line.trim();
31
31
  if (!text)
@@ -130,7 +130,7 @@ function writeFrame(stream, value) {
130
130
  });
131
131
  }
132
132
 
133
- // packages/chat-room-channeld/src/mock-adapter.ts
133
+ // src/mock-adapter.ts
134
134
  async function handleRequest(message, options, state) {
135
135
  const rawId = message.id;
136
136
  if (rawId === undefined) {
@@ -152,6 +152,11 @@ function readCapabilities(result: unknown, accountId: string): AdapterCapabiliti
152
152
  const env = readAccountFields(value.env);
153
153
  if (schema || env) capabilities.account = { ...(schema ? { schema } : {}), ...(env ? { env } : {}) };
154
154
  }
155
+ const send = entry.send;
156
+ if (send && typeof send === "object") {
157
+ const value = (send as Record<string, unknown>).idempotency;
158
+ if (typeof value === "string" && value.trim()) capabilities.send = { idempotency: value.trim() };
159
+ }
155
160
  return Object.keys(capabilities).length ? capabilities : undefined;
156
161
  }
157
162
 
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { loadConfig } from "./config.ts";
6
+ import { accountKey } from "./stats.ts";
6
7
  import { log } from "./log.ts";
7
8
 
8
9
  function readVersion(): string {
@@ -31,6 +32,10 @@ Usage:
31
32
  chat-room-channeld run --config <path> Same as the default command
32
33
  chat-room-channeld check --config <path> Validate a config file only
33
34
  chat-room-channeld status --config <path> Print queue and integrity counts
35
+ chat-room-channeld retry --config <path> --delivery <id> --force
36
+ Retry one unknown delivery; --force may duplicate
37
+ chat-room-channeld migrate --state <sqlite> --to-postgres <url>
38
+ Copy an existing SQLite store into PostgreSQL
34
39
  chat-room-channeld mock Run the mock adapter on stdio
35
40
  chat-room-channeld --version, -v Print the version
36
41
  chat-room-channeld --help, -h Print this help
@@ -38,7 +43,7 @@ Usage:
38
43
 
39
44
  class UsageError extends Error {}
40
45
 
41
- type Command = "run" | "check" | "status" | "mock";
46
+ type Command = "run" | "check" | "status" | "migrate" | "mock" | "retry";
42
47
 
43
48
  async function main(): Promise<void> {
44
49
  const argv = process.argv.slice(2);
@@ -54,11 +59,15 @@ async function main(): Promise<void> {
54
59
  const rest = [...argv];
55
60
  let command: Command = "run";
56
61
  const first = rest[0];
57
- if (first === "run" || first === "check" || first === "status" || first === "mock") {
62
+ if (first === "run" || first === "check" || first === "status" || first === "migrate" || first === "mock" || first === "retry") {
58
63
  command = rest.shift() as Command;
59
64
  }
60
65
 
61
66
  let configPath: string | undefined;
67
+ let statePath: string | undefined;
68
+ let toPostgres: string | undefined;
69
+ let deliveryId: string | undefined;
70
+ let forceRetry = false;
62
71
  while (rest.length > 0) {
63
72
  const arg = rest.shift() as string;
64
73
  if (arg === "--config") {
@@ -68,6 +77,29 @@ async function main(): Promise<void> {
68
77
  } else if (arg.startsWith("--config=")) {
69
78
  configPath = arg.slice("--config=".length);
70
79
  if (!configPath) throw new UsageError("--config requires a path");
80
+ } else if (arg === "--state") {
81
+ const value = rest.shift();
82
+ if (!value) throw new UsageError("--state requires a path");
83
+ statePath = value;
84
+ } else if (arg.startsWith("--state=")) {
85
+ statePath = arg.slice("--state=".length);
86
+ if (!statePath) throw new UsageError("--state requires a path");
87
+ } else if (arg === "--to-postgres") {
88
+ const value = rest.shift();
89
+ if (!value) throw new UsageError("--to-postgres requires a URL");
90
+ toPostgres = value;
91
+ } else if (arg.startsWith("--to-postgres=")) {
92
+ toPostgres = arg.slice("--to-postgres=".length);
93
+ if (!toPostgres) throw new UsageError("--to-postgres requires a URL");
94
+ } else if (arg === "--delivery") {
95
+ const value = rest.shift();
96
+ if (!value) throw new UsageError("--delivery requires an id");
97
+ deliveryId = value;
98
+ } else if (arg.startsWith("--delivery=")) {
99
+ deliveryId = arg.slice("--delivery=".length);
100
+ if (!deliveryId) throw new UsageError("--delivery requires an id");
101
+ } else if (arg === "--force") {
102
+ forceRetry = true;
71
103
  } else {
72
104
  throw new UsageError(`unknown argument: ${arg}`);
73
105
  }
@@ -80,6 +112,15 @@ async function main(): Promise<void> {
80
112
  return;
81
113
  }
82
114
 
115
+ if (command === "migrate") {
116
+ if (!toPostgres) throw new UsageError("migrate requires --to-postgres <url>");
117
+ if (!statePath) throw new UsageError("migrate requires --state <sqlite path>");
118
+ const { migrateToPostgres } = await import("./pg/migrate.ts");
119
+ const report = migrateToPostgres(statePath, toPostgres);
120
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
121
+ return;
122
+ }
123
+
83
124
  if (!configPath) throw new UsageError(`${command} requires --config <path>`);
84
125
  const config = loadConfig(configPath);
85
126
  if (command === "check") {
@@ -87,8 +128,34 @@ async function main(): Promise<void> {
87
128
  return;
88
129
  }
89
130
  if (command === "status") {
90
- const { readChannelStats } = await import("./state.ts");
91
- process.stdout.write(`${JSON.stringify(readChannelStats(config.stateFile), null, 2)}\n`);
131
+ const { readChannelStats, readChannelStatsFromPostgres } = await import("./state.ts");
132
+ const url = process.env.CHAT_ROOM_DATABASE_URL?.trim();
133
+ const stats = url ? readChannelStatsFromPostgres(url) : readChannelStats(config.stateFile);
134
+ process.stdout.write(`${JSON.stringify(stats, null, 2)}\n`);
135
+ return;
136
+ }
137
+ if (command === "retry") {
138
+ if (!deliveryId) throw new UsageError("retry requires --delivery <id>");
139
+ const { openState } = await import("./state.ts");
140
+ const state = openState(config.stateFile);
141
+ try {
142
+ const delivery = state.getDelivery(deliveryId);
143
+ if (!delivery) throw new UsageError(`delivery not found: ${deliveryId}`);
144
+ if (delivery.state !== "unknown") {
145
+ throw new UsageError(`delivery ${deliveryId} is ${delivery.state}; only unknown can be retried`);
146
+ }
147
+ const key = accountKey(delivery.target);
148
+ if (!config.accounts.some((account) => `${account.platform}/${account.id}` === key)) {
149
+ throw new UsageError(`account ${key} is not configured; add it back before retrying`);
150
+ }
151
+ if (!forceRetry) {
152
+ throw new UsageError("retry may resend from the first part and duplicate; pass --force");
153
+ }
154
+ state.markDelivery(deliveryId, "pending");
155
+ process.stdout.write(`${JSON.stringify({ deliveryId, state: "pending" })}\n`);
156
+ } finally {
157
+ state.close();
158
+ }
92
159
  return;
93
160
  }
94
161
 
@@ -112,7 +179,7 @@ async function main(): Promise<void> {
112
179
  await host.stop();
113
180
  throw error;
114
181
  }
115
- log.info(`relay running; state=${config.stateFile}`);
182
+ log.info(`relay running; state=${process.env.CHAT_ROOM_DATABASE_URL?.trim() ? "postgres" : config.stateFile}`);
116
183
  }
117
184
 
118
185
  main().catch((error: unknown) => {
@@ -145,8 +145,6 @@ export class ChannelHost {
145
145
  }
146
146
  const resumed = state.resumePausedDeliveries();
147
147
  if (resumed > 0) log.info(`resumed ${resumed} paused deliveries`);
148
- const recovered = state.recoverInFlightDeliveries();
149
- if (recovered > 0) log.warn(`recovered ${recovered} stale in-flight deliveries`);
150
148
 
151
149
  this.#running = true;
152
150
  this.#starting = true;
@@ -206,6 +204,23 @@ export class ChannelHost {
206
204
  }
207
205
  }
208
206
 
207
+ // Recovery runs after adapters initialize: an in-flight send whose adapter
208
+ // lacks durable idempotency cannot be replayed safely, so it becomes
209
+ // unknown instead of being retried as pending.
210
+ const idempotentKeys = this.#config.accounts
211
+ .filter((account) => !this.#disabled.has(account.id))
212
+ .filter((account) => this.#adapters.get(account.id)?.capabilities?.send?.idempotency === "persistent_delivery_key")
213
+ .map((account) => `${account.platform}/${account.id}`);
214
+ const recovered = state.recoverInFlightDeliveries(idempotentKeys);
215
+ if (recovered > 0) {
216
+ log.warn(`recovered ${recovered} stale in-flight deliveries`);
217
+ for (const account of this.#config.accounts) {
218
+ if (!this.#disabled.has(account.id) && idempotentKeys.includes(`${account.platform}/${account.id}`)) {
219
+ this.#schedule(account.id);
220
+ }
221
+ }
222
+ }
223
+
209
224
  const usable = started.filter((accountId) => !this.#disabled.has(accountId));
210
225
  if (usable.length === 0) {
211
226
  this.#running = false;
@@ -0,0 +1,187 @@
1
+ import { existsSync } from "node:fs";
2
+ import { MessageChannel, receiveMessageOnPort, Worker, type MessagePort } from "node:worker_threads";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { QueryStatement, SQLQueryBindings, StateDatabase, Transaction } from "./sqlite.ts";
5
+
6
+ // Synchronous facade over a PostgreSQL connection. Every call blocks the
7
+ // calling thread on a SharedArrayBuffer while a worker thread performs the
8
+ // network I/O. The state layer is synchronous by design, so this preserves its
9
+ // transaction boundaries without turning 100+ call sites into async code.
10
+ //
11
+ // Channel D uses PostgreSQL as a single-instance durable backend selected by
12
+ // CHAT_ROOM_DATABASE_URL. Writers serialize per transaction with an advisory
13
+ // xact lock so a stray second process cannot interleave writes.
14
+
15
+ type Reply = {
16
+ id: number;
17
+ ok: boolean;
18
+ rows?: unknown[];
19
+ row?: unknown;
20
+ changes?: number;
21
+ lastInsertRowid?: number;
22
+ error?: Record<string, unknown>;
23
+ };
24
+
25
+ type ReadyMessage = { type: "ready" } | { type: "fatal"; error?: Record<string, unknown> };
26
+
27
+ function workerURL(): URL {
28
+ const candidates = [
29
+ new URL("./worker.mjs", import.meta.url), // dist/pg/database.js
30
+ new URL("../packages/chat-room-channeld/src/pg/worker.mjs", import.meta.url), // bundled dist/cli.js + npm package
31
+ new URL("../packages/chat-room-channeld/dist/pg/worker.mjs", import.meta.url), // container with built dist
32
+ new URL("../../src/pg/worker.mjs", import.meta.url), // package src layout
33
+ ];
34
+ for (const candidate of candidates) if (existsSync(fileURLToPath(candidate))) return candidate;
35
+ return candidates[0]!;
36
+ }
37
+
38
+ function databaseError(error: Record<string, unknown> | undefined): Error {
39
+ const result = new Error(String(error?.message ?? "PostgreSQL query failed"));
40
+ Object.assign(result, error);
41
+ return result;
42
+ }
43
+
44
+ export class PgDatabase implements StateDatabase {
45
+ readonly #worker: Worker;
46
+ readonly #port: MessagePort;
47
+ readonly #timeout: number;
48
+ readonly #lockTimeout: number;
49
+ #nextID = 1;
50
+ #depth = 0;
51
+ #savepoints = 0;
52
+ #broken: Error | undefined;
53
+ #closed = false;
54
+
55
+ constructor(connectionString: string, options: { timeout?: number } = {}) {
56
+ if (!connectionString) throw new Error("PostgreSQL connection string is empty");
57
+ this.#timeout = options.timeout ?? 5_000;
58
+ this.#lockTimeout = Math.max(1, this.#timeout - 1_000);
59
+ const ready = new SharedArrayBuffer(4);
60
+ const { port1, port2 } = new MessageChannel();
61
+ this.#port = port1;
62
+ this.#worker = new Worker(workerURL());
63
+ this.#worker.unref();
64
+ this.#port.unref();
65
+ try {
66
+ // No workerData: some Bun versions break `pg` when a worker starts with
67
+ // any workerData. The default worker channel carries one init message
68
+ // and transfers the request port.
69
+ this.#worker.postMessage({
70
+ type: "init",
71
+ connectionString,
72
+ ready,
73
+ statementTimeout: Math.max(1, this.#timeout - 500),
74
+ port: port2,
75
+ }, [port2]);
76
+ } catch (error) {
77
+ void this.#worker.terminate();
78
+ this.#port.close();
79
+ throw error;
80
+ }
81
+ const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
82
+ if (status === "timed-out") {
83
+ void this.#worker.terminate();
84
+ throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
85
+ }
86
+ const message = receiveMessageOnPort(this.#port)?.message as ReadyMessage | undefined;
87
+ if (message?.type === "fatal") {
88
+ void this.#worker.terminate();
89
+ throw databaseError(message.error);
90
+ }
91
+ }
92
+
93
+ query(sql: string): QueryStatement {
94
+ return {
95
+ all: (...params: SQLQueryBindings[]) => this.#request("all", sql, params).rows as unknown[],
96
+ get: (...params: SQLQueryBindings[]) => this.#request("get", sql, params).row as unknown,
97
+ run: (...params: SQLQueryBindings[]) => {
98
+ const result = this.#request("run", sql, params);
99
+ return { changes: result.changes ?? 0, lastInsertRowid: result.lastInsertRowid ?? 0 };
100
+ },
101
+ };
102
+ }
103
+
104
+ prepare(sql: string): QueryStatement { return this.query(sql); }
105
+
106
+ exec(sql: string): void { this.#request("exec", sql, []); }
107
+
108
+ transaction<T>(fn: () => T): Transaction<T> {
109
+ const run = (immediate: boolean) => this.#run(fn, immediate);
110
+ return Object.assign(() => run(false), {
111
+ deferred: () => run(false),
112
+ immediate: () => run(true),
113
+ });
114
+ }
115
+
116
+ close(): void {
117
+ if (this.#closed) return;
118
+ this.#closed = true;
119
+ const signal = new SharedArrayBuffer(4);
120
+ try {
121
+ this.#port.postMessage({ type: "close", signal });
122
+ // Give client.end() time to flush before a caller opens the next
123
+ // connection (migration and restart tests rely on it).
124
+ Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
125
+ } catch { /* worker already gone */ }
126
+ this.#port.close();
127
+ void this.#worker.terminate();
128
+ }
129
+
130
+ #run<T>(fn: () => T, immediate: boolean): T {
131
+ const nested = this.#depth > 0;
132
+ const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
133
+ if (nested) {
134
+ this.exec(`SAVEPOINT ${savepoint}`);
135
+ } else {
136
+ // Deferred reads need one stable snapshot; immediate writers are
137
+ // serialized by the transaction-level advisory lock.
138
+ this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
139
+ if (immediate) {
140
+ try {
141
+ this.exec(`SET LOCAL lock_timeout = '${this.#lockTimeout}ms'; SELECT pg_advisory_xact_lock(hashtext('channeld-state')); SET LOCAL lock_timeout = 0`);
142
+ } catch (error) {
143
+ try { this.exec("ROLLBACK"); } catch { /* keep the original error */ }
144
+ throw error;
145
+ }
146
+ }
147
+ }
148
+ this.#depth++;
149
+ try {
150
+ const result = fn();
151
+ this.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
152
+ return result;
153
+ } catch (error) {
154
+ try {
155
+ this.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
156
+ } catch { /* keep the original error */ }
157
+ throw error;
158
+ } finally {
159
+ this.#depth--;
160
+ }
161
+ }
162
+
163
+ #request(mode: "all" | "get" | "run" | "exec", sql: string, params: SQLQueryBindings[]): Reply {
164
+ if (this.#broken) throw this.#broken;
165
+ if (this.#closed) throw new Error("PostgreSQL database is closed");
166
+ const id = this.#nextID++;
167
+ const signal = new SharedArrayBuffer(4);
168
+ this.#port.postMessage({ id, mode, sql, params, signal });
169
+ const status = Atomics.wait(new Int32Array(signal), 0, 0, this.#timeout);
170
+ if (status === "timed-out") {
171
+ // The worker may still be inside the query. Its connection and queue are
172
+ // no longer trustworthy, so fail closed rather than desynchronize later calls.
173
+ this.#broken = Object.assign(
174
+ new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the database connection must be reopened`),
175
+ { code: "PG_BRIDGE_TIMEOUT" },
176
+ );
177
+ throw this.#broken;
178
+ }
179
+ const message = receiveMessageOnPort(this.#port)?.message as Reply | undefined;
180
+ if (!message || message.id !== id) {
181
+ this.#broken = Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
182
+ throw this.#broken;
183
+ }
184
+ if (!message.ok) throw databaseError(message.error);
185
+ return message;
186
+ }
187
+ }
@@ -0,0 +1,150 @@
1
+ import { existsSync } from "node:fs";
2
+ import { PgDatabase } from "./database.ts";
3
+ import { initializeChannelSchema } from "./schema.ts";
4
+ import { Database, type SQLQueryBindings, type StateDatabase } from "./sqlite.ts";
5
+
6
+ // One-shot SQLite -> PostgreSQL copy for Channel D. Stop the relay host first:
7
+ // this takes a SQLite write lock, but nothing blocks a running PostgreSQL writer.
8
+ // Rollback is unsetting CHAT_ROOM_DATABASE_URL; the SQLite file is never modified.
9
+
10
+ export type MigrationReport = { tables: Array<{ table: string; rows: number }> };
11
+
12
+ const TABLES = ["channel_events", "channel_deliveries", "channel_receipts", "channel_echoes"] as const;
13
+
14
+ const COLUMNS: Record<(typeof TABLES)[number], string[]> = {
15
+ channel_events: ["event_id", "dedup_key", "payload", "ingress_seq", "committed_at"],
16
+ channel_deliveries: [
17
+ "delivery_id", "event_id", "rule_id", "rule_version", "target", "idempotency_key", "payload",
18
+ "state", "attempt_count", "next_attempt_at", "last_error", "provider_message", "created_at", "updated_at",
19
+ ],
20
+ channel_receipts: [
21
+ "receipt_id", "delivery_id", "attempt_id", "state", "provider_message", "detail", "observed_at",
22
+ ],
23
+ channel_echoes: ["endpoint", "native_message_id", "logical_message_id", "delivery_id", "created_at"],
24
+ };
25
+
26
+ const quote = (name: string) => `"${name.replace(/"/g, '""')}"`;
27
+
28
+ function rowCount(db: StateDatabase, table: string): number {
29
+ const row = db.query(`SELECT COUNT(*) AS count FROM ${quote(table)}`).get() as { count: unknown };
30
+ return Number(row.count);
31
+ }
32
+
33
+ function hasTable(db: StateDatabase, table: string): boolean {
34
+ return (db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all() as Array<{ name: unknown }>)
35
+ .some((row) => String(row.name) === table);
36
+ }
37
+
38
+ function assertEmptyTarget(target: PgDatabase): void {
39
+ const tables = target.query(
40
+ "SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema()",
41
+ ).all() as Array<{ table_name: string }>;
42
+ const nonEmpty: string[] = [];
43
+ for (const { table_name: table } of tables) {
44
+ const count = rowCount(target, table);
45
+ if (count > 0) nonEmpty.push(`${table} (${count})`);
46
+ }
47
+ if (nonEmpty.length > 0) {
48
+ throw new Error(`target database is not empty: ${nonEmpty.join(", ")}; migrate into a fresh database`);
49
+ }
50
+ }
51
+
52
+ function maxValue(db: StateDatabase, table: string, column: string, binary = false): unknown {
53
+ const expression = binary ? `${quote(column)} COLLATE "C"` : quote(column);
54
+ const row = db.query(`SELECT MAX(${expression}) AS value FROM ${quote(table)}`).get() as { value: unknown };
55
+ return row.value ?? null;
56
+ }
57
+
58
+ function assertMaxima(source: StateDatabase, target: StateDatabase): void {
59
+ const maxColumns: Record<(typeof TABLES)[number], string> = {
60
+ channel_events: "event_id",
61
+ channel_deliveries: "delivery_id",
62
+ channel_receipts: "receipt_id",
63
+ channel_echoes: "native_message_id",
64
+ };
65
+ for (const table of TABLES) {
66
+ const column = maxColumns[table];
67
+ const expected = maxValue(source, table, column);
68
+ const actual = maxValue(target, table, column, true);
69
+ if (String(expected) !== String(actual)) {
70
+ throw new Error(`max ${column} mismatch for ${table}: source ${String(expected)}, target ${String(actual)}`);
71
+ }
72
+ }
73
+ const sourceSeq = maxValue(source, "channel_events", "ingress_seq");
74
+ const targetSeq = maxValue(target, "channel_events", "ingress_seq");
75
+ if (String(sourceSeq) !== String(targetSeq)) {
76
+ throw new Error(`max ingress_seq mismatch: source ${String(sourceSeq)}, target ${String(targetSeq)}`);
77
+ }
78
+ }
79
+
80
+ function copyTable(
81
+ source: StateDatabase,
82
+ target: StateDatabase,
83
+ table: string,
84
+ columns: string[],
85
+ select: string,
86
+ ): number {
87
+ const rows = source.query(`SELECT ${select} FROM ${quote(table)}`).all() as Array<Record<string, unknown>>;
88
+ const insert = target.query(
89
+ `INSERT INTO ${quote(table)} (${columns.map(quote).join(",")}) VALUES (${columns.map(() => "?").join(",")})`,
90
+ );
91
+ for (const row of rows) {
92
+ insert.run(...(columns.map((column) => row[column]) as SQLQueryBindings[]));
93
+ }
94
+ return rows.length;
95
+ }
96
+
97
+ /**
98
+ * Copy the four channel tables into an empty PostgreSQL database, preserving
99
+ * ids and ingress_seq. Throws before writing if the target holds any rows.
100
+ */
101
+ export function migrateToPostgres(sqlitePath: string, url: string): MigrationReport {
102
+ if (!url.trim()) throw new Error("PostgreSQL URL is required");
103
+ if (!existsSync(sqlitePath)) throw new Error(`SQLite state database not found: ${sqlitePath}`);
104
+ const source = new Database(sqlitePath);
105
+ let target: PgDatabase | undefined;
106
+ try {
107
+ target = new PgDatabase(url);
108
+ const destination = target;
109
+ for (const table of TABLES) {
110
+ if (!hasTable(source, table)) throw new Error(`SQLite channel state not found: ${sqlitePath}`);
111
+ }
112
+ assertEmptyTarget(destination);
113
+ initializeChannelSchema(destination);
114
+
115
+ const echoHasCreatedAt = (source.query("PRAGMA table_info(channel_echoes)").all() as Array<{ name: unknown }>)
116
+ .some((column) => column.name === "created_at");
117
+ // Legacy rows predate created_at. rowid preserves their insertion order and
118
+ // stays below epoch timestamps written after the upgrade.
119
+ const echoTimestamp = echoHasCreatedAt
120
+ ? "CASE WHEN created_at IS NULL OR created_at = 0 THEN rowid ELSE created_at END"
121
+ : "rowid";
122
+ const echoColumns = COLUMNS.channel_echoes.filter((column) => column !== "created_at");
123
+ const copies: Array<{ table: string; rows: number }> = [];
124
+
125
+ source.transaction(() => {
126
+ destination.transaction(() => {
127
+ for (const table of TABLES) {
128
+ const columns = COLUMNS[table];
129
+ const select = table === "channel_echoes"
130
+ ? `${echoColumns.join(",")}, ${echoTimestamp} AS created_at`
131
+ : columns.join(",");
132
+ const expected = rowCount(source, table);
133
+ const rows = copyTable(source, destination, table, columns, select);
134
+ const actual = rowCount(destination, table);
135
+ if (rows !== expected || actual !== expected) {
136
+ throw new Error(`row count mismatch for ${table}: source ${expected}, copied ${rows}, target ${actual}`);
137
+ }
138
+ copies.push({ table, rows });
139
+ }
140
+ assertMaxima(source, destination);
141
+ return copies;
142
+ }).immediate();
143
+ }).immediate();
144
+
145
+ return { tables: copies };
146
+ } finally {
147
+ source.close();
148
+ target?.close();
149
+ }
150
+ }