@alexsun-top/opencode-chat-room 0.8.5 → 0.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -2
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/cli.ts +19 -0
- package/dist/cli.js +4058 -1531
- package/package.json +7 -1
- package/packages/chat-room-channeld/README.md +13 -8
- package/packages/chat-room-channeld/src/adapter.ts +52 -0
- package/packages/chat-room-channeld/src/config.ts +6 -1
- package/packages/chat-room-channeld/src/delivery.ts +0 -4
- package/packages/chat-room-channeld/src/host.ts +66 -44
- package/packages/chat-room-channeld/src/inbound.ts +14 -1
- package/packages/chat-room-channeld/src/pg/database.ts +141 -49
- package/packages/chat-room-channeld/src/pg/worker.mjs +46 -5
- package/packages/chat-room-channeld/src/pg/worker.mts +41 -6
- package/packages/chat-room-channeld/src/protocol.ts +38 -1
- package/packages/chat-room-channeld/src/state-rows.ts +132 -0
- package/packages/chat-room-channeld/src/state.ts +129 -157
- package/packages/chat-room-channeld/src/stats.ts +4 -0
- package/plugin.ts +26 -5
- package/server/app.ts +15 -0
- package/server/assets/base.css +22 -2
- package/server/assets/chat/admin.js +13 -0
- package/server/assets/chat/announcements.js +76 -34
- package/server/assets/chat/confirm-dialog.js +3 -0
- package/server/assets/chat/create-room-dialog.js +7 -0
- package/server/assets/chat/diagram-viewer.js +4 -8
- package/server/assets/chat/doc-preview.js +70 -30
- package/server/assets/chat/editor.js +38 -3
- package/server/assets/chat/events.js +11 -2
- package/server/assets/chat/files.js +28 -26
- package/server/assets/chat/history-loader.js +31 -15
- package/server/assets/chat/integration-editor.js +25 -1
- package/server/assets/chat/integrations.js +107 -15
- package/server/assets/chat/join-requests.js +39 -1
- package/server/assets/chat/locales/de.js +5 -3
- package/server/assets/chat/locales/es.js +5 -3
- package/server/assets/chat/locales/fr.js +5 -3
- package/server/assets/chat/locales/it.js +5 -3
- package/server/assets/chat/locales/ja.js +5 -3
- package/server/assets/chat/locales/ko.js +5 -3
- package/server/assets/chat/markdown-footnotes.js +19 -8
- package/server/assets/chat/markdown.js +0 -7
- package/server/assets/chat/members.js +31 -19
- package/server/assets/chat/message-cache.js +8 -2
- package/server/assets/chat/message-polling.js +8 -2
- package/server/assets/chat/message-window.js +57 -0
- package/server/assets/chat/messages.js +79 -40
- package/server/assets/chat/operator.js +624 -0
- package/server/assets/chat/palette.js +2 -7
- package/server/assets/chat/panels.js +31 -8
- package/server/assets/chat/questions.js +72 -56
- package/server/assets/chat/recall.js +14 -5
- package/server/assets/chat/receipts.js +63 -7
- package/server/assets/chat/refresh-timing.js +6 -0
- package/server/assets/chat/reminders.js +44 -13
- package/server/assets/chat/replies.js +33 -22
- package/server/assets/chat/resource-format.js +4 -1
- package/server/assets/chat/room-list.js +202 -3
- package/server/assets/chat/room-watcher.js +3 -1
- package/server/assets/chat/rooms.js +22 -3
- package/server/assets/chat/settings.js +33 -3
- package/server/assets/chat/state.js +21 -7
- package/server/assets/chat/tasks.js +33 -11
- package/server/assets/chat/window-controls.js +25 -16
- package/server/assets/code-highlight.css +0 -13
- package/server/assets/conversation.css +30 -2
- package/server/assets/doc-preview.css +3 -0
- package/server/assets/files.css +4 -0
- package/server/assets/monaco/integration-rules.js +1 -1
- package/server/assets/responsive.css +12 -2
- package/server/assets/settings.css +3 -1
- package/server/assets/tasks.css +6 -1
- package/server/assets/window-controls.css +3 -1
- package/server/channels.ts +24 -6
- package/server/chat-server.ts +4 -0
- package/server/chat.html +7 -2
- package/server/inbox.ts +3 -1
- package/server/join-requests.ts +8 -1
- package/server/mcp-http.ts +88 -0
- package/server/member-routes.ts +16 -2
- package/server/newrooms.ts +2 -13
- package/server/operator-auth.ts +21 -0
- package/server/operator-routes.ts +150 -0
- package/server/operator-state.ts +64 -0
- package/server/operator.css +139 -0
- package/server/room-owner.ts +17 -0
- package/server/routes/inbox.ts +15 -5
- package/server/routes/pages.ts +12 -2
- package/server/routes/room-actions.ts +4 -3
- package/server/system.html +109 -0
- package/server/wake.ts +1 -1
- package/skills/chatroom/SKILL.md +19 -3
- package/src/acp/client.ts +254 -0
- package/src/acp/protocol.ts +300 -0
- package/src/acp/watch.ts +498 -0
- package/src/agent/agent-receipts.ts +87 -5
- package/src/center/center-client.ts +18 -1
- package/src/center/center-inbox.ts +54 -7
- package/src/center/center-wake.ts +57 -3
- package/src/center/forward-client.ts +48 -0
- package/src/center/mentions.ts +16 -3
- package/src/center/notification-delay.ts +139 -0
- package/src/center/queue.ts +3 -0
- package/src/config/file-config.ts +25 -0
- package/src/mcp/server.ts +407 -0
- package/src/protocol/config.ts +7 -0
- package/src/runtime/plugin-notifications.ts +43 -9
- package/src/runtime/v2-plugin.ts +20 -4
- package/src/runtime/v2-receiver.ts +10 -2
- package/src/runtime/watch.ts +5 -1
- package/src/state/pg-database.ts +133 -49
- package/src/state/pg-worker.mjs +46 -5
- package/src/state/pg-worker.mts +41 -6
- package/src/state/receiver-state.ts +47 -0
- package/src/state/sqlite-database.ts +6 -2
- package/src/state/sqlite-members.ts +48 -4
- package/src/state/sqlite-messages.ts +25 -12
- package/src/state/sqlite-schema.ts +4 -1
- package/src/state/sqlite-state.ts +1 -1
- package/src/state/store.ts +10 -4
- package/src/tui/app.mjs +57 -10
- package/src/tui/app.mts +54 -11
- package/src/tui/room-settings-app.mjs +27 -9
- package/src/tui/room-settings-app.mts +26 -9
- package/src/web/integration-rules-editor.ts +25 -2
|
@@ -20,6 +20,8 @@ type Reply = {
|
|
|
20
20
|
changes?: number;
|
|
21
21
|
lastInsertRowid?: number;
|
|
22
22
|
error?: Record<string, unknown>;
|
|
23
|
+
// The worker's connection is gone; the next top-level call must reconnect.
|
|
24
|
+
broken?: true;
|
|
23
25
|
};
|
|
24
26
|
|
|
25
27
|
type ReadyMessage = { type: "ready" } | { type: "fatal"; error?: Record<string, unknown> };
|
|
@@ -41,11 +43,22 @@ function databaseError(error: Record<string, unknown> | undefined): Error {
|
|
|
41
43
|
return result;
|
|
42
44
|
}
|
|
43
45
|
|
|
46
|
+
// A lost transport is not a retryable SQL condition: immediate() retries busy
|
|
47
|
+
// errors, and replaying a statement with an unknown outcome is unsafe.
|
|
48
|
+
function lostError(error: unknown): Error {
|
|
49
|
+
const cause = error instanceof Error ? error : new Error(String(error));
|
|
50
|
+
return Object.assign(new Error(`PostgreSQL connection lost: ${cause.message}`, { cause }), {
|
|
51
|
+
code: "PG_BRIDGE_LOST",
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
44
55
|
export class PgDatabase implements StateDatabase {
|
|
45
|
-
readonly #
|
|
46
|
-
readonly #port: MessagePort;
|
|
56
|
+
readonly #connectionString: string;
|
|
47
57
|
readonly #timeout: number;
|
|
48
58
|
readonly #lockTimeout: number;
|
|
59
|
+
#worker: Worker | undefined;
|
|
60
|
+
#port: MessagePort | undefined;
|
|
61
|
+
#generation = 0;
|
|
49
62
|
#nextID = 1;
|
|
50
63
|
#depth = 0;
|
|
51
64
|
#savepoints = 0;
|
|
@@ -54,39 +67,90 @@ export class PgDatabase implements StateDatabase {
|
|
|
54
67
|
|
|
55
68
|
constructor(connectionString: string, options: { timeout?: number } = {}) {
|
|
56
69
|
if (!connectionString) throw new Error("PostgreSQL connection string is empty");
|
|
70
|
+
this.#connectionString = connectionString;
|
|
57
71
|
this.#timeout = options.timeout ?? 5_000;
|
|
58
72
|
this.#lockTimeout = Math.max(1, this.#timeout - 1_000);
|
|
73
|
+
this.#connect();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// A worker owns one pg.Client. After a timeout or a lost connection the old
|
|
77
|
+
// worker is disposed instead of reused; the next independent call builds a
|
|
78
|
+
// fresh generation. Work that was already sent is never replayed.
|
|
79
|
+
#connect(): void {
|
|
80
|
+
// Generations hide events from a worker that was already discarded, so a
|
|
81
|
+
// late error or exit cannot mark the replacement connection dead.
|
|
82
|
+
const generation = ++this.#generation;
|
|
59
83
|
const ready = new SharedArrayBuffer(4);
|
|
60
84
|
const { port1, port2 } = new MessageChannel();
|
|
85
|
+
const worker = new Worker(workerURL());
|
|
86
|
+
worker.unref();
|
|
87
|
+
port1.unref();
|
|
88
|
+
// A dying worker must not surface as an uncaught 'error' event. Break the
|
|
89
|
+
// bridge so the next top-level call reconnects.
|
|
90
|
+
worker.on("error", (error: Error) => this.#lose(generation, error));
|
|
91
|
+
worker.on("exit", (code: number) => this.#lose(generation, new Error(`PostgreSQL worker exited with code ${code}`)));
|
|
92
|
+
this.#worker = worker;
|
|
61
93
|
this.#port = port1;
|
|
62
|
-
this.#worker = new Worker(workerURL());
|
|
63
|
-
this.#worker.unref();
|
|
64
|
-
this.#port.unref();
|
|
65
94
|
try {
|
|
66
95
|
// No workerData: some Bun versions break `pg` when a worker starts with
|
|
67
96
|
// any workerData. The default worker channel carries one init message
|
|
68
97
|
// and transfers the request port.
|
|
69
|
-
|
|
98
|
+
worker.postMessage({
|
|
70
99
|
type: "init",
|
|
71
|
-
connectionString,
|
|
100
|
+
connectionString: this.#connectionString,
|
|
72
101
|
ready,
|
|
73
102
|
statementTimeout: Math.max(1, this.#timeout - 500),
|
|
74
103
|
port: port2,
|
|
75
104
|
}, [port2]);
|
|
76
105
|
} catch (error) {
|
|
77
|
-
|
|
78
|
-
this.#port.close();
|
|
106
|
+
this.#dispose();
|
|
79
107
|
throw error;
|
|
80
108
|
}
|
|
81
109
|
const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
|
|
82
110
|
if (status === "timed-out") {
|
|
83
|
-
|
|
111
|
+
this.#dispose();
|
|
84
112
|
throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
|
|
85
113
|
}
|
|
86
|
-
const message = receiveMessageOnPort(
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
114
|
+
const message = receiveMessageOnPort(port1)?.message as ReadyMessage | undefined;
|
|
115
|
+
// Only an explicit "ready" makes the bridge healthy; a silent exit between
|
|
116
|
+
// signalReady and this read must not be reported as a usable connection.
|
|
117
|
+
if (message?.type !== "ready") {
|
|
118
|
+
this.#dispose();
|
|
119
|
+
throw message?.type === "fatal"
|
|
120
|
+
? databaseError(message.error)
|
|
121
|
+
: new Error("PostgreSQL bridge closed before signaling ready");
|
|
122
|
+
}
|
|
123
|
+
this.#broken = undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
#dispose(): void {
|
|
127
|
+
const port = this.#port;
|
|
128
|
+
const worker = this.#worker;
|
|
129
|
+
this.#port = undefined;
|
|
130
|
+
this.#worker = undefined;
|
|
131
|
+
try { port?.close(); } catch { /* already closed */ }
|
|
132
|
+
void worker?.terminate();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
#lose(generation: number, error: Error): void {
|
|
136
|
+
if (generation !== this.#generation || this.#broken || this.#closed) return;
|
|
137
|
+
this.#broken = lostError(error);
|
|
138
|
+
this.#dispose();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Fails fast inside a transaction: the old transaction is already lost, so
|
|
142
|
+
// reopening here would run its remaining statements outside that transaction.
|
|
143
|
+
// A closed handle never reopens, even when it is also marked lost.
|
|
144
|
+
#ensureOpen(): void {
|
|
145
|
+
if (this.#closed) throw new Error("PostgreSQL database is closed");
|
|
146
|
+
if (!this.#broken) return;
|
|
147
|
+
if (this.#depth > 0) throw this.#broken;
|
|
148
|
+
this.#dispose();
|
|
149
|
+
try {
|
|
150
|
+
this.#connect();
|
|
151
|
+
} catch (error) {
|
|
152
|
+
this.#broken = lostError(error);
|
|
153
|
+
throw this.#broken;
|
|
90
154
|
}
|
|
91
155
|
}
|
|
92
156
|
|
|
@@ -116,37 +180,39 @@ export class PgDatabase implements StateDatabase {
|
|
|
116
180
|
close(): void {
|
|
117
181
|
if (this.#closed) return;
|
|
118
182
|
this.#closed = true;
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
183
|
+
const port = this.#port;
|
|
184
|
+
if (port && !this.#broken) {
|
|
185
|
+
const signal = new SharedArrayBuffer(4);
|
|
186
|
+
try {
|
|
187
|
+
port.postMessage({ type: "close", signal });
|
|
188
|
+
// Give client.end() time to flush before a caller opens the next
|
|
189
|
+
// connection (migration and restart tests rely on it).
|
|
190
|
+
Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
|
|
191
|
+
} catch { /* worker already gone */ }
|
|
192
|
+
}
|
|
193
|
+
this.#dispose();
|
|
128
194
|
}
|
|
129
195
|
|
|
130
196
|
#run<T>(fn: () => T, immediate: boolean): T {
|
|
197
|
+
// A new transaction may reconnect, but once its depth is pinned every
|
|
198
|
+
// BEGIN, lock, COMMIT and ROLLBACK runs against the same connection
|
|
199
|
+
// generation. A lost transaction therefore fails on the old bridge instead
|
|
200
|
+
// of continuing on a fresh one.
|
|
201
|
+
this.#ensureOpen();
|
|
131
202
|
const nested = this.#depth > 0;
|
|
132
203
|
const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
204
|
+
this.#depth++;
|
|
205
|
+
try {
|
|
206
|
+
if (nested) {
|
|
207
|
+
this.exec(`SAVEPOINT ${savepoint}`);
|
|
208
|
+
} else {
|
|
209
|
+
// Deferred reads need one stable snapshot; immediate writers are
|
|
210
|
+
// serialized by the transaction-level advisory lock.
|
|
211
|
+
this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
|
|
212
|
+
if (immediate) {
|
|
141
213
|
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
214
|
}
|
|
146
215
|
}
|
|
147
|
-
}
|
|
148
|
-
this.#depth++;
|
|
149
|
-
try {
|
|
150
216
|
const result = fn();
|
|
151
217
|
this.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
|
|
152
218
|
return result;
|
|
@@ -161,27 +227,53 @@ export class PgDatabase implements StateDatabase {
|
|
|
161
227
|
}
|
|
162
228
|
|
|
163
229
|
#request(mode: "all" | "get" | "run" | "exec", sql: string, params: SQLQueryBindings[]): Reply {
|
|
164
|
-
|
|
165
|
-
|
|
230
|
+
this.#ensureOpen();
|
|
231
|
+
const port = this.#port as MessagePort;
|
|
166
232
|
const id = this.#nextID++;
|
|
167
233
|
const signal = new SharedArrayBuffer(4);
|
|
168
|
-
|
|
234
|
+
try {
|
|
235
|
+
port.postMessage({ id, mode, sql, params, signal });
|
|
236
|
+
} catch (error) {
|
|
237
|
+
const failure = lostError(error);
|
|
238
|
+
this.#fail(failure);
|
|
239
|
+
throw this.#broken ?? failure;
|
|
240
|
+
}
|
|
169
241
|
const status = Atomics.wait(new Int32Array(signal), 0, 0, this.#timeout);
|
|
170
242
|
if (status === "timed-out") {
|
|
171
|
-
// The worker may still be inside the
|
|
172
|
-
//
|
|
173
|
-
|
|
174
|
-
|
|
243
|
+
// The worker may still be inside the statement, so its outcome is unknown.
|
|
244
|
+
// Terminating the worker aborts its transaction; the statement is never
|
|
245
|
+
// replayed and a later independent call reconnects.
|
|
246
|
+
const error = Object.assign(
|
|
247
|
+
new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the connection reopens on the next operation`),
|
|
175
248
|
{ code: "PG_BRIDGE_TIMEOUT" },
|
|
176
249
|
);
|
|
177
|
-
|
|
250
|
+
this.#fail(error);
|
|
251
|
+
throw error;
|
|
178
252
|
}
|
|
179
|
-
const message = receiveMessageOnPort(
|
|
253
|
+
const message = receiveMessageOnPort(port)?.message as Reply | undefined;
|
|
180
254
|
if (!message || message.id !== id) {
|
|
181
|
-
this.#broken
|
|
182
|
-
|
|
255
|
+
const error = this.#broken ??
|
|
256
|
+
Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
|
|
257
|
+
this.#fail(error);
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
if (!message.ok) {
|
|
261
|
+
const error = databaseError(message.error);
|
|
262
|
+
if (message.broken) {
|
|
263
|
+
// A normal SQL error keeps the connection; a lost one cannot be
|
|
264
|
+
// repaired in place, so close it and let the next call reconnect.
|
|
265
|
+
const lost = lostError(error);
|
|
266
|
+
this.#fail(lost);
|
|
267
|
+
throw lost;
|
|
268
|
+
}
|
|
269
|
+
throw error;
|
|
183
270
|
}
|
|
184
|
-
if (!message.ok) throw databaseError(message.error);
|
|
185
271
|
return message;
|
|
186
272
|
}
|
|
273
|
+
|
|
274
|
+
#fail(error: Error): void {
|
|
275
|
+
if (this.#broken) return;
|
|
276
|
+
this.#broken = error;
|
|
277
|
+
this.#dispose();
|
|
278
|
+
}
|
|
187
279
|
}
|
|
@@ -10,6 +10,7 @@ let port;
|
|
|
10
10
|
let readyFlag;
|
|
11
11
|
let statementTimeout = 4_500;
|
|
12
12
|
let connected = false;
|
|
13
|
+
let lost;
|
|
13
14
|
let draining = false;
|
|
14
15
|
let closing = false;
|
|
15
16
|
const queue = [];
|
|
@@ -39,15 +40,46 @@ function signalReady() {
|
|
|
39
40
|
Atomics.notify(readyFlag, 0);
|
|
40
41
|
}
|
|
41
42
|
function reply(request, payload) {
|
|
42
|
-
|
|
43
|
+
try {
|
|
44
|
+
port?.postMessage({ id: request.id, ...payload });
|
|
45
|
+
}
|
|
46
|
+
catch { /* port already retired */ }
|
|
43
47
|
const flag = new Int32Array(request.signal);
|
|
44
48
|
Atomics.store(flag, 0, 1);
|
|
45
49
|
Atomics.notify(flag, 0);
|
|
46
50
|
}
|
|
51
|
+
function markLost(error) {
|
|
52
|
+
if (!lost)
|
|
53
|
+
lost = error instanceof Error ? error : new Error(String(error));
|
|
54
|
+
connected = false;
|
|
55
|
+
return lost;
|
|
56
|
+
}
|
|
57
|
+
// Session-level failures (backend termination, server shutdown, socket error)
|
|
58
|
+
// leave the client unusable. Ordinary statement errors such as 57014 keep it.
|
|
59
|
+
function unusable(error) {
|
|
60
|
+
if (lost)
|
|
61
|
+
return true;
|
|
62
|
+
const source = (error ?? {});
|
|
63
|
+
if (source.severity === "FATAL" || source.severity === "PANIC")
|
|
64
|
+
return true;
|
|
65
|
+
// SQLSTATE class 08 is a connection exception, not a statement failure.
|
|
66
|
+
return typeof source.code === "string" && source.code.startsWith("08");
|
|
67
|
+
}
|
|
68
|
+
// pg emits "error" on the client when the socket dies without an active query
|
|
69
|
+
// (idle connection). Without this listener the event is uncaught and the worker
|
|
70
|
+
// dies, which used to take the whole server process with it.
|
|
71
|
+
function clientLost(error) {
|
|
72
|
+
if (closing)
|
|
73
|
+
return;
|
|
74
|
+
markLost(error);
|
|
75
|
+
if (queue.length && !draining)
|
|
76
|
+
void drain();
|
|
77
|
+
}
|
|
47
78
|
async function handle(request) {
|
|
48
79
|
const db = client;
|
|
49
|
-
if (!db) {
|
|
50
|
-
|
|
80
|
+
if (!db || lost) {
|
|
81
|
+
const error = lost ?? new Error("PostgreSQL worker is not connected");
|
|
82
|
+
return reply(request, { ok: false, error: serialize(error), broken: true });
|
|
51
83
|
}
|
|
52
84
|
try {
|
|
53
85
|
const text = translate(request.sql);
|
|
@@ -69,7 +101,10 @@ async function handle(request) {
|
|
|
69
101
|
return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
|
|
70
102
|
}
|
|
71
103
|
catch (error) {
|
|
72
|
-
|
|
104
|
+
if (!unusable(error))
|
|
105
|
+
return reply(request, { ok: false, error: serialize(error) });
|
|
106
|
+
markLost(error);
|
|
107
|
+
return reply(request, { ok: false, error: serialize(error), broken: true });
|
|
73
108
|
}
|
|
74
109
|
}
|
|
75
110
|
async function drain() {
|
|
@@ -103,7 +138,9 @@ function handlePortMessage(message) {
|
|
|
103
138
|
return;
|
|
104
139
|
}
|
|
105
140
|
queue.push(message);
|
|
106
|
-
|
|
141
|
+
// After a loss the queue is still served, but every reply is marked broken so
|
|
142
|
+
// the main thread reopens immediately instead of waiting for its timeout.
|
|
143
|
+
if (!draining && (connected || lost))
|
|
107
144
|
void drain();
|
|
108
145
|
}
|
|
109
146
|
async function startup(connectionString, ready, timeout) {
|
|
@@ -115,6 +152,10 @@ async function startup(connectionString, ready, timeout) {
|
|
|
115
152
|
application_name: "chat-room-channeld",
|
|
116
153
|
statement_timeout: statementTimeout,
|
|
117
154
|
});
|
|
155
|
+
db.on("error", clientLost);
|
|
156
|
+
// pg normally emits "error" before "end"; "end" alone still means the
|
|
157
|
+
// connection is gone, and the first failure keeps its message.
|
|
158
|
+
db.on("end", () => clientLost(new Error("PostgreSQL connection ended")));
|
|
118
159
|
client = db;
|
|
119
160
|
await db.connect();
|
|
120
161
|
connected = true;
|
|
@@ -40,6 +40,7 @@ let port: MessagePort | undefined;
|
|
|
40
40
|
let readyFlag: Int32Array | undefined;
|
|
41
41
|
let statementTimeout = 4_500;
|
|
42
42
|
let connected = false;
|
|
43
|
+
let lost: Error | undefined;
|
|
43
44
|
let draining = false;
|
|
44
45
|
let closing = false;
|
|
45
46
|
const queue: Request[] = [];
|
|
@@ -73,16 +74,42 @@ function signalReady(): void {
|
|
|
73
74
|
}
|
|
74
75
|
|
|
75
76
|
function reply(request: Request, payload: Record<string, unknown>): void {
|
|
76
|
-
port?.postMessage({ id: request.id, ...payload });
|
|
77
|
+
try { port?.postMessage({ id: request.id, ...payload }); } catch { /* port already retired */ }
|
|
77
78
|
const flag = new Int32Array(request.signal);
|
|
78
79
|
Atomics.store(flag, 0, 1);
|
|
79
80
|
Atomics.notify(flag, 0);
|
|
80
81
|
}
|
|
81
82
|
|
|
83
|
+
function markLost(error: unknown): Error {
|
|
84
|
+
if (!lost) lost = error instanceof Error ? error : new Error(String(error));
|
|
85
|
+
connected = false;
|
|
86
|
+
return lost;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Session-level failures (backend termination, server shutdown, socket error)
|
|
90
|
+
// leave the client unusable. Ordinary statement errors such as 57014 keep it.
|
|
91
|
+
function unusable(error: unknown): boolean {
|
|
92
|
+
if (lost) return true;
|
|
93
|
+
const source = (error ?? {}) as { severity?: unknown; code?: unknown };
|
|
94
|
+
if (source.severity === "FATAL" || source.severity === "PANIC") return true;
|
|
95
|
+
// SQLSTATE class 08 is a connection exception, not a statement failure.
|
|
96
|
+
return typeof source.code === "string" && source.code.startsWith("08");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// pg emits "error" on the client when the socket dies without an active query
|
|
100
|
+
// (idle connection). Without this listener the event is uncaught and the worker
|
|
101
|
+
// dies, which used to take the whole server process with it.
|
|
102
|
+
function clientLost(error: unknown): void {
|
|
103
|
+
if (closing) return;
|
|
104
|
+
markLost(error);
|
|
105
|
+
if (queue.length && !draining) void drain();
|
|
106
|
+
}
|
|
107
|
+
|
|
82
108
|
async function handle(request: Request): Promise<void> {
|
|
83
109
|
const db = client;
|
|
84
|
-
if (!db) {
|
|
85
|
-
|
|
110
|
+
if (!db || lost) {
|
|
111
|
+
const error = lost ?? new Error("PostgreSQL worker is not connected");
|
|
112
|
+
return reply(request, { ok: false, error: serialize(error), broken: true });
|
|
86
113
|
}
|
|
87
114
|
try {
|
|
88
115
|
const text = translate(request.sql);
|
|
@@ -100,7 +127,9 @@ async function handle(request: Request): Promise<void> {
|
|
|
100
127
|
// keep the API shape without pretending to know an insert id.
|
|
101
128
|
return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
|
|
102
129
|
} catch (error) {
|
|
103
|
-
return reply(request, { ok: false, error: serialize(error) });
|
|
130
|
+
if (!unusable(error)) return reply(request, { ok: false, error: serialize(error) });
|
|
131
|
+
markLost(error);
|
|
132
|
+
return reply(request, { ok: false, error: serialize(error), broken: true });
|
|
104
133
|
}
|
|
105
134
|
}
|
|
106
135
|
|
|
@@ -130,7 +159,9 @@ function handlePortMessage(message: PortMessage): void {
|
|
|
130
159
|
return;
|
|
131
160
|
}
|
|
132
161
|
queue.push(message);
|
|
133
|
-
|
|
162
|
+
// After a loss the queue is still served, but every reply is marked broken so
|
|
163
|
+
// the main thread reopens immediately instead of waiting for its timeout.
|
|
164
|
+
if (!draining && (connected || lost)) void drain();
|
|
134
165
|
}
|
|
135
166
|
|
|
136
167
|
async function startup(connectionString: string, ready: SharedArrayBuffer, timeout: number): Promise<void> {
|
|
@@ -142,6 +173,10 @@ async function startup(connectionString: string, ready: SharedArrayBuffer, timeo
|
|
|
142
173
|
application_name: "chat-room-channeld",
|
|
143
174
|
statement_timeout: statementTimeout,
|
|
144
175
|
});
|
|
176
|
+
db.on("error", clientLost);
|
|
177
|
+
// pg normally emits "error" before "end"; "end" alone still means the
|
|
178
|
+
// connection is gone, and the first failure keeps its message.
|
|
179
|
+
db.on("end", () => clientLost(new Error("PostgreSQL connection ended")));
|
|
145
180
|
client = db;
|
|
146
181
|
await db.connect();
|
|
147
182
|
connected = true;
|
|
@@ -163,4 +198,4 @@ if (parent) {
|
|
|
163
198
|
parent.close();
|
|
164
199
|
void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
|
|
165
200
|
});
|
|
166
|
-
}
|
|
201
|
+
}
|
|
@@ -57,14 +57,46 @@ export type AccountCapabilities = {
|
|
|
57
57
|
env?: AccountField[];
|
|
58
58
|
};
|
|
59
59
|
|
|
60
|
+
/** A feature contract version such as `v1`. A `domain/` prefix means a different contract; matching is exact. */
|
|
61
|
+
export const FEATURE_VERSION_PATTERN = /^(?:[A-Za-z0-9][A-Za-z0-9.-]*\/)?v[1-9]\d*$/;
|
|
62
|
+
|
|
63
|
+
export type FeatureDirection = "receive" | "send" | "both";
|
|
64
|
+
|
|
65
|
+
/** One capability, versioned on its own so features can evolve independently. */
|
|
66
|
+
export type FeatureDeclaration = {
|
|
67
|
+
version: string;
|
|
68
|
+
direction?: FeatureDirection;
|
|
69
|
+
limits?: Record<string, string | number | boolean>;
|
|
70
|
+
};
|
|
71
|
+
|
|
60
72
|
/** Adapter-declared platform facts the generic host must not hardcode. */
|
|
61
73
|
export type AdapterCapabilities = {
|
|
62
74
|
displayName?: string;
|
|
63
75
|
attachments?: AttachmentCapabilities;
|
|
64
76
|
account?: AccountCapabilities;
|
|
65
77
|
send?: { idempotency?: string };
|
|
78
|
+
/**
|
|
79
|
+
* Stable feature id to every version the adapter implements. An adapter may
|
|
80
|
+
* declare several versions of one feature; the host picks the highest it supports.
|
|
81
|
+
*/
|
|
82
|
+
features?: Record<string, FeatureDeclaration[]>;
|
|
66
83
|
};
|
|
67
84
|
|
|
85
|
+
/** Return the first host-supported version of a feature, or undefined when none match. */
|
|
86
|
+
export function selectFeature(
|
|
87
|
+
capabilities: AdapterCapabilities | undefined,
|
|
88
|
+
id: string,
|
|
89
|
+
hostVersions: string[],
|
|
90
|
+
): FeatureDeclaration | undefined {
|
|
91
|
+
const declared = capabilities?.features?.[id];
|
|
92
|
+
if (!declared?.length) return undefined;
|
|
93
|
+
for (const version of hostVersions) {
|
|
94
|
+
const match = declared.find((feature) => feature.version === version);
|
|
95
|
+
if (match) return match;
|
|
96
|
+
}
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
68
100
|
export interface IngestEvent {
|
|
69
101
|
schemaVersion: number;
|
|
70
102
|
eventId: string;
|
|
@@ -77,7 +109,12 @@ export interface IngestEvent {
|
|
|
77
109
|
parent?: MessageRef;
|
|
78
110
|
occurredAt?: string;
|
|
79
111
|
receivedAt: string;
|
|
80
|
-
content?: {
|
|
112
|
+
content?: {
|
|
113
|
+
text?: string;
|
|
114
|
+
attachmentRefs?: string[];
|
|
115
|
+
attachments?: AttachmentRef[];
|
|
116
|
+
mentions?: Array<{ id: string; name: string }>;
|
|
117
|
+
};
|
|
81
118
|
selectedMessage?: MessageRef;
|
|
82
119
|
requestedTarget?: Endpoint;
|
|
83
120
|
cause?: { rootEventId: string; visitedEndpoints: Endpoint[]; hopCount: number };
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// Row shapes and mappers shared by the Channel D state store.
|
|
2
|
+
|
|
3
|
+
export const DELIVERY_STATES = [
|
|
4
|
+
"pending",
|
|
5
|
+
"in_flight",
|
|
6
|
+
"sent",
|
|
7
|
+
"retryable",
|
|
8
|
+
"rate_limited",
|
|
9
|
+
"permanent",
|
|
10
|
+
"unsupported",
|
|
11
|
+
"unknown",
|
|
12
|
+
"exhausted",
|
|
13
|
+
"paused",
|
|
14
|
+
] as const;
|
|
15
|
+
|
|
16
|
+
export type DeliveryState = (typeof DELIVERY_STATES)[number];
|
|
17
|
+
|
|
18
|
+
export const TERMINAL_DELIVERY_STATES: readonly DeliveryState[] = [
|
|
19
|
+
"sent",
|
|
20
|
+
"permanent",
|
|
21
|
+
"unsupported",
|
|
22
|
+
"exhausted",
|
|
23
|
+
"unknown",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
export function isTerminalDeliveryState(state: DeliveryState): boolean {
|
|
27
|
+
return TERMINAL_DELIVERY_STATES.includes(state);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface DeliveryPatch {
|
|
31
|
+
attemptCount?: number;
|
|
32
|
+
nextAttemptAt?: number | null;
|
|
33
|
+
lastError?: string | null;
|
|
34
|
+
providerMessage?: string | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface DeliveryRow {
|
|
38
|
+
deliveryId: string;
|
|
39
|
+
eventId: string;
|
|
40
|
+
ruleId: string;
|
|
41
|
+
ruleVersion: number;
|
|
42
|
+
target: string;
|
|
43
|
+
idempotencyKey: string;
|
|
44
|
+
payload: string;
|
|
45
|
+
state: DeliveryState;
|
|
46
|
+
attemptCount: number;
|
|
47
|
+
nextAttemptAt: number | null;
|
|
48
|
+
lastError: string | null;
|
|
49
|
+
providerMessage: string | null;
|
|
50
|
+
createdAt: number;
|
|
51
|
+
updatedAt: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ReceiptRow {
|
|
55
|
+
receiptId: string;
|
|
56
|
+
deliveryId: string;
|
|
57
|
+
attemptId: string;
|
|
58
|
+
state: string;
|
|
59
|
+
providerMessage: string | null;
|
|
60
|
+
detail: string | null;
|
|
61
|
+
observedAt: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface SentRecordInput {
|
|
65
|
+
deliveryId: string;
|
|
66
|
+
attemptId: string;
|
|
67
|
+
providerMessage: string | null;
|
|
68
|
+
detail?: string | null;
|
|
69
|
+
observedAt?: number;
|
|
70
|
+
echo?: { endpoint: string; nativeMessageId: string; logicalMessageId: string };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface ReceiptInput {
|
|
74
|
+
deliveryId: string;
|
|
75
|
+
attemptId: string;
|
|
76
|
+
state: string;
|
|
77
|
+
providerMessage?: string | null;
|
|
78
|
+
detail?: string | null;
|
|
79
|
+
observedAt?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type CommitResult =
|
|
83
|
+
| { duplicate: true; existingEventId: string }
|
|
84
|
+
| { duplicate: false; eventId: string; ingressSeq: number };
|
|
85
|
+
|
|
86
|
+
/** One authorized outbound delivery, frozen before the ingest transaction. */
|
|
87
|
+
export interface PlannedDelivery {
|
|
88
|
+
ruleId: string;
|
|
89
|
+
ruleVersion: number;
|
|
90
|
+
target: string;
|
|
91
|
+
payload: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface CreatedDelivery {
|
|
95
|
+
deliveryId: string;
|
|
96
|
+
target: string;
|
|
97
|
+
ruleId: string;
|
|
98
|
+
ruleVersion: number;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type RawRow = Record<string, unknown>;
|
|
102
|
+
|
|
103
|
+
export function toDelivery(row: RawRow): DeliveryRow {
|
|
104
|
+
return {
|
|
105
|
+
deliveryId: String(row.delivery_id),
|
|
106
|
+
eventId: String(row.event_id),
|
|
107
|
+
ruleId: String(row.rule_id),
|
|
108
|
+
ruleVersion: Number(row.rule_version),
|
|
109
|
+
target: String(row.target),
|
|
110
|
+
idempotencyKey: String(row.idempotency_key),
|
|
111
|
+
payload: String(row.payload),
|
|
112
|
+
state: String(row.state) as DeliveryState,
|
|
113
|
+
attemptCount: Number(row.attempt_count),
|
|
114
|
+
nextAttemptAt: row.next_attempt_at === null ? null : Number(row.next_attempt_at),
|
|
115
|
+
lastError: row.last_error === null ? null : String(row.last_error),
|
|
116
|
+
providerMessage: row.provider_message === null ? null : String(row.provider_message),
|
|
117
|
+
createdAt: Number(row.created_at),
|
|
118
|
+
updatedAt: Number(row.updated_at),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function toReceipt(row: RawRow): ReceiptRow {
|
|
123
|
+
return {
|
|
124
|
+
receiptId: String(row.receipt_id),
|
|
125
|
+
deliveryId: String(row.delivery_id),
|
|
126
|
+
attemptId: String(row.attempt_id),
|
|
127
|
+
state: String(row.state),
|
|
128
|
+
providerMessage: row.provider_message === null ? null : String(row.provider_message),
|
|
129
|
+
detail: row.detail === null ? null : String(row.detail),
|
|
130
|
+
observedAt: Number(row.observed_at),
|
|
131
|
+
};
|
|
132
|
+
}
|