@alexsun-top/opencode-chat-room 0.8.5 → 0.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -2
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/cli.ts +19 -0
- package/dist/cli.js +3747 -1443
- package/package.json +6 -1
- package/packages/chat-room-channeld/README.md +13 -8
- package/packages/chat-room-channeld/src/delivery.ts +0 -4
- package/packages/chat-room-channeld/src/host.ts +48 -37
- 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/state-rows.ts +132 -0
- package/packages/chat-room-channeld/src/state.ts +129 -157
- package/plugin.ts +20 -4
- package/server/app.ts +9 -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 +6 -1
- 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 +31 -3
- 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 +3 -2
- package/server/chat.html +7 -2
- package/server/inbox.ts +3 -1
- package/server/join-requests.ts +8 -1
- 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 +3 -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 +5 -0
- 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 +389 -0
- package/src/protocol/config.ts +7 -0
- package/src/runtime/plugin-notifications.ts +43 -9
- package/src/runtime/v2-plugin.ts +14 -3
- 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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexsun-top/opencode-chat-room",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.6",
|
|
4
4
|
"description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -52,6 +52,9 @@
|
|
|
52
52
|
"server/message-recall-routes.ts",
|
|
53
53
|
"server/room-payload.ts",
|
|
54
54
|
"server/room-owner.ts",
|
|
55
|
+
"server/operator-auth.ts",
|
|
56
|
+
"server/operator-routes.ts",
|
|
57
|
+
"server/operator-state.ts",
|
|
55
58
|
"server/newrooms.ts",
|
|
56
59
|
"server/join-requests.ts",
|
|
57
60
|
"server/room-join.ts",
|
|
@@ -65,6 +68,8 @@
|
|
|
65
68
|
"server/room-reminders.ts",
|
|
66
69
|
"server/wake.ts",
|
|
67
70
|
"server/chat.html",
|
|
71
|
+
"server/system.html",
|
|
72
|
+
"server/operator.css",
|
|
68
73
|
"server/manifest.webmanifest",
|
|
69
74
|
"server/sw.js",
|
|
70
75
|
"server/assets",
|
|
@@ -224,19 +224,24 @@ The child process reads:
|
|
|
224
224
|
- `FEISHU_HTTP_TIMEOUT_MS` (optional, default `10000`)
|
|
225
225
|
- `FEISHU_CARD_VERSION` (optional, `1.0` default or `2.0`)
|
|
226
226
|
- `FEISHU_INBOUND` (optional, `1` enables the event long connection)
|
|
227
|
-
- `FEISHU_INBOUND_CHATS` (
|
|
228
|
-
|
|
227
|
+
- `FEISHU_INBOUND_CHATS` (comma-separated group `chat_id` allowlist)
|
|
228
|
+
- `FEISHU_INBOUND_DM_CHAT` and `FEISHU_INBOUND_DM_OPEN_ID` (set both with
|
|
229
|
+
`FEISHU_INBOUND=1` to receive only one private chat from one app-scoped user;
|
|
230
|
+
this ignores the group allowlist)
|
|
229
231
|
|
|
230
232
|
Set these in the host environment; the host passes its environment to adapter
|
|
231
233
|
child processes.
|
|
232
234
|
|
|
233
235
|
Inbound requires the app to use long-connection event subscription in the Feishu
|
|
234
|
-
developer console and to subscribe `im.message.receive_v1
|
|
235
|
-
|
|
236
|
+
developer console and to subscribe `im.message.receive_v1`. The bot must be in
|
|
237
|
+
each allowlisted group; private chat requires the app's bot DM read permission
|
|
238
|
+
(`im:message.p2p_msg:readonly` or `im:message.p2p_msg`). Add a server `inbound`
|
|
239
|
+
route for the exact source account and chat to relay it into ChatRoom. The
|
|
240
|
+
adapter obtains the WebSocket URL from
|
|
236
241
|
`POST /callback/ws/endpoint`, pings, reassembles fragmented frames, and
|
|
237
|
-
acknowledges only after the host commits the ingest.
|
|
238
|
-
messages from
|
|
239
|
-
other chats, other event types, other apps, and unsupported message types are
|
|
242
|
+
acknowledges only after the host commits the ingest. Supported `text`, `post`,
|
|
243
|
+
`image`, and `file` messages must come from an allowed human sender and chat.
|
|
244
|
+
Bot/self senders, other chats, other event types, other apps, and unsupported message types are
|
|
240
245
|
acknowledged without ingest. A long-connection start failure logs a warning,
|
|
241
246
|
keeps the account started for outbound sends, and reports a sanitized
|
|
242
247
|
`inbound failed: ...` in the account status; outbound forwarding keeps working.
|
|
@@ -340,4 +345,4 @@ same terminal result event and message.
|
|
|
340
345
|
- no full backpressure (high-water marks, pausing ingress, disk quotas) — only per-account queue/process isolation and `rate_limited` backoff;
|
|
341
346
|
- no attachments, no rule UI, no multi-tenant permission model, no exactly-once
|
|
342
347
|
guarantee (inbound room notifications are idempotent per event and route, but
|
|
343
|
-
a crash between the ACK and Feishu's next retry can still lose an event).
|
|
348
|
+
a crash between the ACK and Feishu's next retry can still lose an event).
|
|
@@ -67,10 +67,6 @@ export function applyReceipt(
|
|
|
67
67
|
|
|
68
68
|
switch (receipt.state) {
|
|
69
69
|
case "sent": {
|
|
70
|
-
state.markDelivery(row.deliveryId, "sent", {
|
|
71
|
-
providerMessage: providerMessage ?? null,
|
|
72
|
-
lastError: null,
|
|
73
|
-
});
|
|
74
70
|
const event = state.getEvent(row.eventId);
|
|
75
71
|
const echo = receipt.providerMessage?.nativeMessageId && receipt.providerMessage.endpoint
|
|
76
72
|
? {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AccountConfig, ChannelConfig
|
|
1
|
+
import type { AccountConfig, ChannelConfig } from "./config.ts";
|
|
2
2
|
import { AdapterProcess, type SendReceipt } from "./adapter.ts";
|
|
3
3
|
import { applyReceipt, notifyDeliveryResult, type DeliveryResultHandler } from "./delivery.ts";
|
|
4
4
|
import { parseTarget, startFailureReason, toEndpoint, validateTargets } from "./host-helpers.ts";
|
|
@@ -8,7 +8,7 @@ import type { AdapterCapabilities, Endpoint, IngestEvent, MessageRef } from "./p
|
|
|
8
8
|
import { matchRules, planPayload, sameEndpoint, targetKey } from "./rules.ts";
|
|
9
9
|
import type { ChannelAccountRuntime } from "./stats.ts";
|
|
10
10
|
import { sanitizeAccountError } from "./stats.ts";
|
|
11
|
-
import { openState, type ChannelState, type DeliveryRow } from "./state.ts";
|
|
11
|
+
import { openState, type ChannelState, type DeliveryRow, type PlannedDelivery } from "./state.ts";
|
|
12
12
|
|
|
13
13
|
export type { IngestResult } from "./ingest-gate.ts";
|
|
14
14
|
|
|
@@ -213,12 +213,9 @@ export class ChannelHost {
|
|
|
213
213
|
.map((account) => `${account.platform}/${account.id}`);
|
|
214
214
|
const recovered = state.recoverInFlightDeliveries(idempotentKeys);
|
|
215
215
|
if (recovered > 0) {
|
|
216
|
+
// Every started account already owns one delivery loop, so recovery only
|
|
217
|
+
// makes rows pending; scheduling again would create a second loop.
|
|
216
218
|
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
219
|
}
|
|
223
220
|
|
|
224
221
|
const usable = started.filter((accountId) => !this.#disabled.has(accountId));
|
|
@@ -264,7 +261,14 @@ export class ChannelHost {
|
|
|
264
261
|
}
|
|
265
262
|
}
|
|
266
263
|
|
|
267
|
-
|
|
264
|
+
// The event and its frozen outbound plan commit together. Classification and
|
|
265
|
+
// planning run only for a new insert, on the stored event with its ingressSeq;
|
|
266
|
+
// the frozen decision also governs whether a consumer error rolls the event back.
|
|
267
|
+
let notificationOnly = false;
|
|
268
|
+
const { result, created } = state.commitIngestWithPlan(event, (storedEvent) => {
|
|
269
|
+
notificationOnly = this.#notificationOnly?.(storedEvent) ?? false;
|
|
270
|
+
return notificationOnly ? [] : this.#planDeliveries(storedEvent);
|
|
271
|
+
});
|
|
268
272
|
if (result.duplicate) {
|
|
269
273
|
log.info("duplicate ingest skipped", { event: result.existingEventId });
|
|
270
274
|
return { duplicate: true, eventId: result.existingEventId };
|
|
@@ -279,7 +283,7 @@ export class ChannelHost {
|
|
|
279
283
|
const message = error instanceof Error ? error.message : String(error);
|
|
280
284
|
// An inbound notification owns the ACK: roll back and fail the ingest so
|
|
281
285
|
// the provider retries. Other consumer failures stay contained as before.
|
|
282
|
-
if (
|
|
286
|
+
if (notificationOnly) {
|
|
283
287
|
state.deleteIngestEvent(stored.eventId);
|
|
284
288
|
log.error(`inbound commit rolled back: ${message}`, { event: stored.eventId });
|
|
285
289
|
throw error;
|
|
@@ -288,58 +292,64 @@ export class ChannelHost {
|
|
|
288
292
|
}
|
|
289
293
|
}
|
|
290
294
|
|
|
291
|
-
if (
|
|
295
|
+
if (notificationOnly) {
|
|
292
296
|
log.info("inbound notification only; outbound rules skipped", { event: stored.eventId });
|
|
293
297
|
return { duplicate: false, eventId: stored.eventId };
|
|
294
298
|
}
|
|
295
299
|
|
|
296
|
-
|
|
297
|
-
const
|
|
300
|
+
for (const delivery of created) {
|
|
301
|
+
const endpoint = parseTarget(delivery.target);
|
|
302
|
+
if (endpoint && this.#disabled.has(endpoint.accountId)) {
|
|
303
|
+
state.markDelivery(delivery.deliveryId, "paused", {
|
|
304
|
+
lastError: "account disabled until restart",
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
log.info(`delivery enqueued rule=${delivery.ruleId}@${delivery.ruleVersion}`, {
|
|
308
|
+
delivery: delivery.deliveryId,
|
|
309
|
+
event: stored.eventId,
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
return { duplicate: false, eventId: stored.eventId };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Freeze matching rules into delivery plans; runs inside the ingest transaction. */
|
|
316
|
+
#planDeliveries(event: IngestEvent): PlannedDelivery[] {
|
|
317
|
+
if (event.kind === "message.forward_requested") {
|
|
318
|
+
const selected = event.selectedMessage;
|
|
298
319
|
const reason = !selected
|
|
299
320
|
? "selectedMessage is required"
|
|
300
|
-
: !sameEndpoint(selected.endpoint,
|
|
321
|
+
: !sameEndpoint(selected.endpoint, event.source)
|
|
301
322
|
? "selectedMessage is outside the source room"
|
|
302
323
|
: undefined;
|
|
303
324
|
if (reason) {
|
|
304
|
-
log.warn(`forward rejected: ${reason}`, { event:
|
|
305
|
-
return
|
|
325
|
+
log.warn(`forward rejected: ${reason}`, { event: event.eventId });
|
|
326
|
+
return [];
|
|
306
327
|
}
|
|
307
328
|
}
|
|
308
329
|
|
|
309
|
-
const requestedTarget =
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
const payloads: string[] = [];
|
|
330
|
+
const requestedTarget = event.kind === "message.forward_requested" ? event.requestedTarget : undefined;
|
|
331
|
+
const planned: PlannedDelivery[] = [];
|
|
332
|
+
for (const rule of matchRules(this.#config, event)) {
|
|
313
333
|
for (const target of rule.to) {
|
|
314
334
|
const endpoint = toEndpoint(this.#config, rule.id, target);
|
|
315
335
|
if (requestedTarget && !sameEndpoint(endpoint, requestedTarget)) continue;
|
|
316
|
-
const plan = planPayload(rule,
|
|
336
|
+
const plan = planPayload(rule, event, endpoint);
|
|
317
337
|
if ("dropped" in plan) {
|
|
318
338
|
log.warn(
|
|
319
339
|
`rule ${rule.id}@${rule.version} dropped delivery to ${targetKey(endpoint)}: ${plan.dropped}`,
|
|
320
|
-
{ event:
|
|
340
|
+
{ event: event.eventId },
|
|
321
341
|
);
|
|
322
342
|
continue;
|
|
323
343
|
}
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
for (const delivery of created) {
|
|
330
|
-
const endpoint = parseTarget(delivery.target);
|
|
331
|
-
if (endpoint && this.#disabled.has(endpoint.accountId)) {
|
|
332
|
-
state.markDelivery(delivery.deliveryId, "paused", {
|
|
333
|
-
lastError: "account disabled until restart",
|
|
334
|
-
});
|
|
335
|
-
}
|
|
336
|
-
log.info(`delivery enqueued rule=${rule.id}@${rule.version}`, {
|
|
337
|
-
delivery: delivery.deliveryId,
|
|
338
|
-
event: stored.eventId,
|
|
344
|
+
planned.push({
|
|
345
|
+
ruleId: rule.id,
|
|
346
|
+
ruleVersion: rule.version,
|
|
347
|
+
target: targetKey(endpoint),
|
|
348
|
+
payload: JSON.stringify(plan.payload),
|
|
339
349
|
});
|
|
340
350
|
}
|
|
341
351
|
}
|
|
342
|
-
return
|
|
352
|
+
return planned;
|
|
343
353
|
}
|
|
344
354
|
|
|
345
355
|
async stop(options: { abortInFlight?: boolean } = {}): Promise<void> {
|
|
@@ -375,6 +385,7 @@ export class ChannelHost {
|
|
|
375
385
|
|
|
376
386
|
#schedule(accountId: string): void {
|
|
377
387
|
if (!this.#running || this.#disabled.has(accountId)) return;
|
|
388
|
+
if (this.#timers.has(accountId)) return;
|
|
378
389
|
const timer = setTimeout(() => {
|
|
379
390
|
this.#timers.delete(accountId);
|
|
380
391
|
if (!this.#running) return;
|
|
@@ -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;
|