@alexsun-top/opencode-chat-room 0.8.4 → 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 +17 -3
- package/README.md +5 -5
- package/README.zh-CN.md +5 -5
- package/cli.ts +20 -1
- package/dist/cli.js +3785 -1462
- package/package.json +19 -11
- package/packages/chat-room-channeld/README.md +16 -10
- 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/inbound.ts +3 -6
- package/packages/chat-room-channeld/src/pg/database.ts +141 -49
- package/packages/chat-room-channeld/src/pg/sql.mjs +157 -142
- package/packages/chat-room-channeld/src/pg/sql.mts +175 -0
- package/packages/chat-room-channeld/src/pg/worker.mjs +148 -99
- package/packages/chat-room-channeld/src/pg/worker.mts +201 -0
- package/packages/chat-room-channeld/src/state-rows.ts +132 -0
- package/packages/chat-room-channeld/src/state.ts +129 -157
- package/plugin.ts +21 -5
- package/server/app.ts +9 -0
- package/server/assets/base.css +22 -2
- package/server/assets/chat/admin.js +17 -1
- package/server/assets/chat/announcements.js +79 -34
- package/server/assets/chat/attachments.js +3 -3
- package/server/assets/chat/clipboard.js +1 -1
- package/server/assets/chat/confirm-dialog.js +3 -0
- package/server/assets/chat/copy-action.js +1 -1
- 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 +71 -31
- package/server/assets/chat/editor.js +49 -10
- package/server/assets/chat/events.js +13 -6
- package/server/assets/chat/files.js +33 -27
- package/server/assets/chat/history-loader.js +31 -15
- package/server/assets/chat/integration-editor.js +27 -1
- package/server/assets/chat/integrations.js +108 -16
- package/server/assets/chat/join-requests.js +40 -2
- 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 +27 -15
- package/server/assets/chat/markdown.js +6 -12
- package/server/assets/chat/members.js +34 -22
- package/server/assets/chat/mentions.js +8 -5
- package/server/assets/chat/message-cache.js +9 -3
- package/server/assets/chat/message-polling.js +10 -4
- package/server/assets/chat/message-window.js +58 -1
- package/server/assets/chat/messages.js +90 -37
- package/server/assets/chat/office-preview.js +3 -3
- package/server/assets/chat/operator.js +624 -0
- package/server/assets/chat/palette.js +7 -10
- package/server/assets/chat/panels.js +42 -0
- package/server/assets/chat/questions.js +75 -58
- 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 +47 -13
- package/server/assets/chat/replies.js +39 -25
- package/server/assets/chat/resource-format.js +6 -3
- package/server/assets/chat/room-list.js +202 -3
- package/server/assets/chat/room-watcher.js +3 -1
- package/server/assets/chat/rooms.js +29 -7
- package/server/assets/chat/settings.js +37 -6
- package/server/assets/chat/shortcuts.js +3 -1
- package/server/assets/chat/side-pane.js +1 -1
- package/server/assets/chat/state.js +51 -18
- package/server/assets/chat/system-events.js +3 -2
- package/server/assets/chat/system-messages.js +15 -15
- package/server/assets/chat/tasks.js +37 -14
- package/server/assets/chat/window-controls.js +25 -15
- package/server/assets/code-highlight.css +0 -13
- package/server/assets/conversation.css +45 -5
- package/server/assets/doc-preview.css +9 -0
- package/server/assets/files.css +4 -0
- package/server/assets/monaco/integration-rules.js +1 -1
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +23 -1
- package/server/assets/office/licenses/docx-preview-HEADER.txt +6 -0
- package/server/assets/office/licenses/echarts-LICENSE-d3.txt +27 -0
- package/server/assets/office/licenses/echarts-NOTICE.txt +5 -0
- package/server/assets/office/licenses/immediate-LICENSE.txt +20 -0
- package/server/assets/office/licenses/lie-LICENSE.txt +7 -0
- package/server/assets/office/licenses/pako-LICENSE.txt +21 -0
- package/server/assets/office/licenses/pako-ZLIB.txt +18 -0
- package/server/assets/office/licenses/setimmediate-LICENSE.txt +20 -0
- 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/sw.js +3 -1
- package/server/system.html +109 -0
- package/server/wake.ts +1 -1
- package/skills/chatroom/SKILL.md +9 -0
- package/src/README.md +1 -1
- 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 +98 -8
- package/src/center/center-client.ts +6 -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 +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-sql.mjs +157 -142
- package/src/state/pg-sql.mts +175 -0
- package/src/state/pg-worker.mjs +148 -99
- package/src/state/pg-worker.mts +201 -0
- 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 +31 -11
- package/src/tui/app-types.mjs +1 -0
- package/src/tui/app-types.mts +175 -0
- package/src/tui/app.mjs +473 -423
- package/src/tui/app.mts +543 -0
- package/src/tui/config.mjs +166 -158
- package/src/tui/config.mts +247 -0
- package/src/tui/http.mjs +239 -206
- package/src/tui/http.mts +412 -0
- package/src/tui/i18n.mjs +17 -20
- package/src/tui/i18n.mts +42 -0
- package/src/tui/info-app.mjs +431 -427
- package/src/tui/info-app.mts +500 -0
- package/src/tui/info-content.mjs +205 -199
- package/src/tui/info-content.mts +341 -0
- package/src/tui/join-app.mjs +75 -64
- package/src/tui/join-app.mts +99 -0
- package/src/tui/locales/en.mjs +302 -320
- package/src/tui/locales/en.mts +349 -0
- package/src/tui/locales/zh-CN.mjs +302 -320
- package/src/tui/locales/zh-CN.mts +349 -0
- package/src/tui/main.mjs +219 -213
- package/src/tui/main.mts +255 -0
- package/src/tui/markdown.mjs +128 -272
- package/src/tui/markdown.mts +152 -0
- package/src/tui/mentions.mjs +181 -184
- package/src/tui/mentions.mts +251 -0
- package/src/tui/message-app.mjs +181 -173
- package/src/tui/message-app.mts +213 -0
- package/src/tui/message-view.mjs +90 -111
- package/src/tui/message-view.mts +151 -0
- package/src/tui/messages.mjs +55 -49
- package/src/tui/messages.mts +106 -0
- package/src/tui/palette-app.mjs +364 -344
- package/src/tui/palette-app.mts +388 -0
- package/src/tui/palette.mjs +100 -98
- package/src/tui/palette.mts +176 -0
- package/src/tui/prefs.mjs +56 -63
- package/src/tui/prefs.mts +126 -0
- package/src/tui/reminder-app.mjs +191 -181
- package/src/tui/reminder-app.mts +228 -0
- package/src/tui/room-settings-app.mjs +275 -242
- package/src/tui/room-settings-app.mts +318 -0
- package/src/tui/session.mjs +30 -29
- package/src/tui/session.mts +51 -0
- package/src/tui/settings-app.mjs +151 -138
- package/src/tui/settings-app.mts +179 -0
- package/src/tui/ui-content.mjs +426 -421
- package/src/tui/ui-content.mts +499 -0
- package/src/tui/ui-help.mjs +58 -67
- package/src/tui/ui-help.mts +87 -0
- package/src/tui/ui-mentions.mjs +34 -36
- package/src/tui/ui-mentions.mts +60 -0
- package/src/tui/ui-overlay-view.mjs +259 -267
- package/src/tui/ui-overlay-view.mts +322 -0
- package/src/tui/ui-suggest-view.mjs +54 -57
- package/src/tui/ui-suggest-view.mts +78 -0
- package/src/tui/ui-suggest.mjs +164 -167
- package/src/tui/ui-suggest.mts +248 -0
- package/src/tui/ui-theme.mjs +52 -57
- package/src/tui/ui-theme.mts +98 -0
- package/src/tui/ui-view.mjs +267 -275
- package/src/tui/ui-view.mts +308 -0
- package/src/tui/ui.mjs +372 -359
- package/src/tui/ui.mts +440 -0
- package/src/tui/wire.mjs +215 -0
- package/src/tui/wire.mts +383 -0
- package/src/web/integration-rules-editor.ts +25 -2
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// SQLite -> PostgreSQL translation for the chat-room state SQL. The app's SQL
|
|
2
|
+
// uses ? placeholders, SQLite DDL, a few pragmas and a handful of scalar
|
|
3
|
+
// functions; everything else is deliberately passed through unchanged.
|
|
4
|
+
//
|
|
5
|
+
// This is intentionally not a general SQLite translator. Keep the dialect
|
|
6
|
+
// narrow and add a test when the state layer starts using a new construct.
|
|
7
|
+
|
|
8
|
+
const PRAGMA_TABLE_INFO = /PRAGMA\s+table_info\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)/gi;
|
|
9
|
+
|
|
10
|
+
function pragmaTableInfo(table: string): string {
|
|
11
|
+
const tableName = table.replace(/'/g, "''");
|
|
12
|
+
return `SELECT c.column_name AS name,c.data_type AS type,` +
|
|
13
|
+
`CASE WHEN c.is_nullable='NO' THEN 1 ELSE 0 END AS "notnull",` +
|
|
14
|
+
`c.column_default AS dflt_value,` +
|
|
15
|
+
`CASE WHEN EXISTS (SELECT 1 FROM pg_index i JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=ANY(i.indkey) ` +
|
|
16
|
+
`WHERE i.indrelid=(quote_ident(c.table_schema)||'.'||quote_ident(c.table_name))::regclass AND i.indisprimary AND a.attname=c.column_name) ` +
|
|
17
|
+
`THEN 1 ELSE 0 END AS pk ` +
|
|
18
|
+
`FROM information_schema.columns c WHERE c.table_schema=current_schema() AND c.table_name='${tableName}' ORDER BY c.ordinal_position`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const isIdentStart = (ch: string | undefined): boolean => !!ch && /[A-Za-z_]/.test(ch);
|
|
22
|
+
const isIdentChar = (ch: string | undefined): boolean => !!ch && /[A-Za-z0-9_$]/.test(ch);
|
|
23
|
+
|
|
24
|
+
function skipQuoted(sql: string, index: number): number {
|
|
25
|
+
const quote = sql[index];
|
|
26
|
+
let i = index + 1;
|
|
27
|
+
while (i < sql.length) {
|
|
28
|
+
if (sql[i] === quote) {
|
|
29
|
+
if (sql[i + 1] === quote) { i += 2; continue; }
|
|
30
|
+
return i + 1;
|
|
31
|
+
}
|
|
32
|
+
i++;
|
|
33
|
+
}
|
|
34
|
+
return i;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function skipComment(sql: string, index: number): number {
|
|
38
|
+
if (sql[index + 1] === "-") {
|
|
39
|
+
const end = sql.indexOf("\n", index + 2);
|
|
40
|
+
return end < 0 ? sql.length : end;
|
|
41
|
+
}
|
|
42
|
+
const end = sql.indexOf("*/", index + 2);
|
|
43
|
+
return end < 0 ? sql.length : end + 2;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function hasTopLevelComma(sql: string, openIndex: number): boolean {
|
|
47
|
+
let depth = 0;
|
|
48
|
+
for (let i = openIndex; i < sql.length; i++) {
|
|
49
|
+
const ch = sql[i];
|
|
50
|
+
if (ch === "'" || ch === '"') { i = skipQuoted(sql, i) - 1; continue; }
|
|
51
|
+
if (ch === "-" && sql[i + 1] === "-") { i = skipComment(sql, i) - 1; continue; }
|
|
52
|
+
if (ch === "/" && sql[i + 1] === "*") { i = skipComment(sql, i) - 1; continue; }
|
|
53
|
+
if (ch === "(") depth++;
|
|
54
|
+
else if (ch === ")") { depth--; if (depth === 0) return false; }
|
|
55
|
+
else if (ch === "," && depth === 1) return true;
|
|
56
|
+
}
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function wordBefore(sql: string, index: number): string {
|
|
61
|
+
let i = index - 1;
|
|
62
|
+
while (i >= 0 && /\s/.test(sql.charAt(i))) i--;
|
|
63
|
+
const end = i + 1;
|
|
64
|
+
while (i >= 0 && isIdentChar(sql[i])) i--;
|
|
65
|
+
return sql.slice(i + 1, end).toLowerCase();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function wordAfter(sql: string, index: number): string {
|
|
69
|
+
let i = index + 1;
|
|
70
|
+
while (i < sql.length && /\s/.test(sql.charAt(i))) i++;
|
|
71
|
+
const start = i;
|
|
72
|
+
while (i < sql.length && isIdentChar(sql[i])) i++;
|
|
73
|
+
return sql.slice(start, i).toLowerCase();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function scan(sql: string): string {
|
|
77
|
+
let out = "";
|
|
78
|
+
let index = 0;
|
|
79
|
+
let parameter = 0;
|
|
80
|
+
while (index < sql.length) {
|
|
81
|
+
const ch = sql.charAt(index);
|
|
82
|
+
if (ch === "'" || ch === '"') {
|
|
83
|
+
const end = skipQuoted(sql, index);
|
|
84
|
+
out += sql.slice(index, end);
|
|
85
|
+
index = end;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (ch === "-" && sql[index + 1] === "-") {
|
|
89
|
+
const end = skipComment(sql, index);
|
|
90
|
+
out += sql.slice(index, end);
|
|
91
|
+
index = end;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (ch === "/" && sql[index + 1] === "*") {
|
|
95
|
+
const end = skipComment(sql, index);
|
|
96
|
+
out += sql.slice(index, end);
|
|
97
|
+
index = end;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (ch === "?") {
|
|
101
|
+
// CASE WHEN ? needs a boolean; a bare `? IS NULL` has no type to infer.
|
|
102
|
+
const nextWord = wordAfter(sql, index);
|
|
103
|
+
const cast = (wordBefore(sql, index) === "when" && nextWord === "then") || nextWord === "is";
|
|
104
|
+
out += `$${++parameter}${cast ? (nextWord === "is" ? "::text" : "::boolean") : ""}`;
|
|
105
|
+
index++;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (isIdentStart(ch)) {
|
|
109
|
+
let end = index + 1;
|
|
110
|
+
while (isIdentChar(sql[end])) end++;
|
|
111
|
+
const word = sql.slice(index, end);
|
|
112
|
+
const lower = word.toLowerCase();
|
|
113
|
+
// SQLite's scalar max(a,b)/min(a,b); the one-argument aggregate forms stay.
|
|
114
|
+
if (lower === "max" || lower === "min") {
|
|
115
|
+
let next = end;
|
|
116
|
+
while (next < sql.length && /\s/.test(sql.charAt(next))) next++;
|
|
117
|
+
if (sql[next] === "(" && hasTopLevelComma(sql, next)) {
|
|
118
|
+
out += lower === "max" ? "GREATEST" : "LEAST";
|
|
119
|
+
index = end;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// Preserve camelCase result aliases: PostgreSQL folds unquoted identifiers.
|
|
124
|
+
if (lower === "as") {
|
|
125
|
+
const previous = wordBefore(sql, index);
|
|
126
|
+
let next = end;
|
|
127
|
+
while (next < sql.length && /\s/.test(sql.charAt(next))) next++;
|
|
128
|
+
if (isIdentStart(sql[next])) {
|
|
129
|
+
let aliasEnd = next + 1;
|
|
130
|
+
while (isIdentChar(sql[aliasEnd])) aliasEnd++;
|
|
131
|
+
const alias = sql.slice(next, aliasEnd);
|
|
132
|
+
if (/[A-Z]/.test(alias) && previous !== "default" && alias.toLowerCase() !== "identity") {
|
|
133
|
+
out += `AS "${alias}"`;
|
|
134
|
+
index = aliasEnd;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
out += word;
|
|
140
|
+
index = end;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
out += ch;
|
|
144
|
+
index++;
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function appendOnConflictDoNothing(sql: string): string {
|
|
150
|
+
return `${sql.replace(/[\s;]+$/, "")} ON CONFLICT DO NOTHING`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function translate(sql: string): string {
|
|
154
|
+
let text = String(sql);
|
|
155
|
+
// Connection tuning pragmas have no PostgreSQL equivalent; foreign keys are
|
|
156
|
+
// always enforced and concurrency is handled by advisory locks.
|
|
157
|
+
text = text.replace(/PRAGMA\s+(?:busy_timeout|journal_mode|foreign_keys)\s*(?:=\s*[^;]+)?\s*;?/gi, "");
|
|
158
|
+
text = text.replace(PRAGMA_TABLE_INFO, (_, table) => pragmaTableInfo(table));
|
|
159
|
+
// SQLite INTEGER is 64-bit; PostgreSQL INTEGER is 32-bit and epoch
|
|
160
|
+
// milliseconds overflow it.
|
|
161
|
+
text = text.replace(/\bINTEGER\b/gi, "BIGINT");
|
|
162
|
+
text = text.replace(/\bBIGINT\s+PRIMARY\s+KEY\s+AUTOINCREMENT\b/gi, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
|
|
163
|
+
// Manual `BEGIN IMMEDIATE` appears inside receiver-state's schema script.
|
|
164
|
+
text = text.replace(/\bBEGIN\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE)\b/gi, "BEGIN");
|
|
165
|
+
if (/\bINSERT\s+OR\s+IGNORE\b/i.test(text)) {
|
|
166
|
+
text = text.replace(/\bINSERT\s+OR\s+IGNORE\b/gi, "INSERT");
|
|
167
|
+
if (!/\bON\s+CONFLICT\b/i.test(text)) text = appendOnConflictDoNothing(text);
|
|
168
|
+
}
|
|
169
|
+
// SQLite treats 1/0 as booleans; PostgreSQL needs an explicit cast.
|
|
170
|
+
return scan(text).trim();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function hasSql(text: string): boolean {
|
|
174
|
+
return text.replace(/[;\s]/g, "").length > 0;
|
|
175
|
+
}
|
package/src/state/pg-worker.mjs
CHANGED
|
@@ -1,133 +1,182 @@
|
|
|
1
1
|
import { parentPort } from "node:worker_threads";
|
|
2
2
|
import pg from "pg";
|
|
3
3
|
import { hasSql, translate } from "./pg-sql.mjs";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
// The worker deliberately starts with no workerData. Some Bun versions fail to
|
|
9
|
-
// load `pg` in a worker that received any workerData at startup. The main
|
|
10
|
-
// thread sends one init message over the default worker channel instead; that
|
|
11
|
-
// message also transfers the request MessagePort and the ready SharedArrayBuffer.
|
|
12
|
-
|
|
4
|
+
const ERROR_FIELDS = [
|
|
5
|
+
"name", "code", "detail", "hint", "severity",
|
|
6
|
+
"position", "constraint", "table", "column", "dataType",
|
|
7
|
+
];
|
|
13
8
|
let client;
|
|
14
9
|
let port;
|
|
15
10
|
let readyFlag;
|
|
16
11
|
let statementTimeout = 4_500;
|
|
17
12
|
let connected = false;
|
|
13
|
+
let lost;
|
|
18
14
|
let draining = false;
|
|
19
15
|
let closing = false;
|
|
20
16
|
const queue = [];
|
|
21
|
-
|
|
22
17
|
// SQLite returns all integers as JS numbers; int8 is a string in node-postgres
|
|
23
18
|
// by default and COUNT(*) / BIGINT columns must stay numbers.
|
|
24
19
|
pg.types.setTypeParser(20, (value) => Number(value));
|
|
25
20
|
pg.types.setTypeParser(1700, (value) => Number(value));
|
|
26
|
-
|
|
27
21
|
function normalize(params) {
|
|
28
|
-
|
|
29
|
-
value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
|
|
22
|
+
return params.map((value) => value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
|
|
30
23
|
}
|
|
31
|
-
|
|
32
24
|
function serialize(error) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
column: error?.column,
|
|
44
|
-
dataType: error?.dataType,
|
|
45
|
-
};
|
|
25
|
+
const source = (typeof error === "object" && error !== null ? error : {});
|
|
26
|
+
const result = {
|
|
27
|
+
message: typeof source.message === "string" ? source.message : String(error),
|
|
28
|
+
};
|
|
29
|
+
for (const key of ERROR_FIELDS) {
|
|
30
|
+
const value = source[key];
|
|
31
|
+
if (typeof value === "string" || typeof value === "number")
|
|
32
|
+
result[key] = value;
|
|
33
|
+
}
|
|
34
|
+
return result;
|
|
46
35
|
}
|
|
47
|
-
|
|
48
36
|
function signalReady() {
|
|
49
|
-
|
|
50
|
-
|
|
37
|
+
if (!readyFlag)
|
|
38
|
+
return;
|
|
39
|
+
Atomics.store(readyFlag, 0, 1);
|
|
40
|
+
Atomics.notify(readyFlag, 0);
|
|
51
41
|
}
|
|
52
|
-
|
|
53
42
|
function reply(request, payload) {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
43
|
+
try {
|
|
44
|
+
port?.postMessage({ id: request.id, ...payload });
|
|
45
|
+
}
|
|
46
|
+
catch { /* port already retired */ }
|
|
47
|
+
const flag = new Int32Array(request.signal);
|
|
48
|
+
Atomics.store(flag, 0, 1);
|
|
49
|
+
Atomics.notify(flag, 0);
|
|
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();
|
|
58
77
|
}
|
|
59
|
-
|
|
60
78
|
async function handle(request) {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
+
const db = client;
|
|
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 });
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const text = translate(request.sql);
|
|
86
|
+
if (!hasSql(text))
|
|
87
|
+
return reply(request, { ok: true, rows: [], row: null, changes: 0 });
|
|
88
|
+
const params = normalize(request.params ?? []);
|
|
89
|
+
// exec without params uses the simple-query protocol so multi-statement
|
|
90
|
+
// schema scripts (and BEGIN/COMMIT) run in one round trip.
|
|
91
|
+
const result = request.mode === "exec" && params.length === 0
|
|
92
|
+
? await db.query(text)
|
|
93
|
+
: await db.query({ text, values: params });
|
|
94
|
+
if (request.mode === "get")
|
|
95
|
+
return reply(request, { ok: true, row: result.rows?.[0] ?? null });
|
|
96
|
+
if (request.mode === "all")
|
|
97
|
+
return reply(request, { ok: true, rows: result.rows ?? [] });
|
|
98
|
+
const last = Array.isArray(result) ? result.at(-1) : result;
|
|
99
|
+
// Identity columns are never read through Database.run in the state layer;
|
|
100
|
+
// keep the API shape without pretending to know an insert id.
|
|
101
|
+
return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
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 });
|
|
108
|
+
}
|
|
79
109
|
}
|
|
80
|
-
|
|
81
110
|
async function drain() {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
111
|
+
draining = true;
|
|
112
|
+
while (queue.length && !closing) {
|
|
113
|
+
const request = queue.shift();
|
|
114
|
+
if (request)
|
|
115
|
+
await handle(request);
|
|
116
|
+
}
|
|
117
|
+
draining = false;
|
|
85
118
|
}
|
|
86
|
-
|
|
87
119
|
async function shutdown(signal) {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
120
|
+
closing = true;
|
|
121
|
+
try {
|
|
122
|
+
await client?.end();
|
|
123
|
+
}
|
|
124
|
+
catch { /* connection already gone */ }
|
|
125
|
+
try {
|
|
126
|
+
port?.close();
|
|
127
|
+
}
|
|
128
|
+
catch { /* already closed */ }
|
|
129
|
+
if (signal) {
|
|
130
|
+
const flag = new Int32Array(signal);
|
|
131
|
+
Atomics.store(flag, 0, 1);
|
|
132
|
+
Atomics.notify(flag, 0);
|
|
133
|
+
}
|
|
96
134
|
}
|
|
97
|
-
|
|
98
135
|
function handlePortMessage(message) {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
136
|
+
if (!("id" in message)) {
|
|
137
|
+
void shutdown(message.signal);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
queue.push(message);
|
|
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))
|
|
144
|
+
void drain();
|
|
105
145
|
}
|
|
106
|
-
|
|
107
146
|
async function startup(connectionString, ready, timeout) {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
147
|
+
readyFlag = new Int32Array(ready);
|
|
148
|
+
statementTimeout = timeout;
|
|
149
|
+
try {
|
|
150
|
+
const db = new pg.Client({
|
|
151
|
+
connectionString,
|
|
152
|
+
application_name: "opencode-chat-room",
|
|
153
|
+
statement_timeout: statementTimeout,
|
|
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")));
|
|
159
|
+
client = db;
|
|
160
|
+
await db.connect();
|
|
161
|
+
connected = true;
|
|
162
|
+
port?.postMessage({ type: "ready" });
|
|
163
|
+
signalReady();
|
|
164
|
+
if (queue.length && !draining)
|
|
165
|
+
void drain();
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
port?.postMessage({ type: "fatal", error: serialize(error) });
|
|
169
|
+
signalReady();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const parent = parentPort;
|
|
173
|
+
if (parent) {
|
|
174
|
+
parent.on("message", (message) => {
|
|
175
|
+
if (message?.type !== "init" || client)
|
|
176
|
+
return;
|
|
177
|
+
port = message.port;
|
|
178
|
+
port.on("message", handlePortMessage);
|
|
179
|
+
parent.close();
|
|
180
|
+
void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
|
|
115
181
|
});
|
|
116
|
-
await client.connect();
|
|
117
|
-
connected = true;
|
|
118
|
-
port.postMessage({ type: "ready" });
|
|
119
|
-
signalReady();
|
|
120
|
-
if (queue.length && !draining) void drain();
|
|
121
|
-
} catch (error) {
|
|
122
|
-
port.postMessage({ type: "fatal", error: serialize(error) });
|
|
123
|
-
signalReady();
|
|
124
|
-
}
|
|
125
182
|
}
|
|
126
|
-
|
|
127
|
-
parentPort.on("message", (message) => {
|
|
128
|
-
if (message?.type !== "init" || client) return;
|
|
129
|
-
port = message.port;
|
|
130
|
-
port.on("message", handlePortMessage);
|
|
131
|
-
parentPort.close();
|
|
132
|
-
void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
|
|
133
|
-
});
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { parentPort, type MessagePort } from "node:worker_threads";
|
|
2
|
+
import pg from "pg";
|
|
3
|
+
import { hasSql, translate } from "./pg-sql.mjs";
|
|
4
|
+
|
|
5
|
+
// One pg.Client per worker: transactions and their advisory locks belong to a
|
|
6
|
+
// single session, so a pool would be incorrect here.
|
|
7
|
+
//
|
|
8
|
+
// The worker deliberately starts with no workerData. Some Bun versions fail to
|
|
9
|
+
// load `pg` in a worker that received any workerData at startup. The main
|
|
10
|
+
// thread sends one init message over the default worker channel instead; that
|
|
11
|
+
// message also transfers the request MessagePort and the ready SharedArrayBuffer.
|
|
12
|
+
|
|
13
|
+
type Request = {
|
|
14
|
+
id: number;
|
|
15
|
+
mode: "all" | "get" | "run" | "exec";
|
|
16
|
+
sql: string;
|
|
17
|
+
params?: unknown[];
|
|
18
|
+
signal: SharedArrayBuffer;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
type PortMessage = Request | { type: "close"; signal?: SharedArrayBuffer };
|
|
22
|
+
|
|
23
|
+
type InitMessage = {
|
|
24
|
+
type: "init";
|
|
25
|
+
connectionString: string;
|
|
26
|
+
ready: SharedArrayBuffer;
|
|
27
|
+
statementTimeout?: number;
|
|
28
|
+
port: MessagePort;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
type SerializedError = { message: string; [field: string]: string | number | undefined };
|
|
32
|
+
|
|
33
|
+
const ERROR_FIELDS = [
|
|
34
|
+
"name", "code", "detail", "hint", "severity",
|
|
35
|
+
"position", "constraint", "table", "column", "dataType",
|
|
36
|
+
] as const;
|
|
37
|
+
|
|
38
|
+
let client: pg.Client | undefined;
|
|
39
|
+
let port: MessagePort | undefined;
|
|
40
|
+
let readyFlag: Int32Array | undefined;
|
|
41
|
+
let statementTimeout = 4_500;
|
|
42
|
+
let connected = false;
|
|
43
|
+
let lost: Error | undefined;
|
|
44
|
+
let draining = false;
|
|
45
|
+
let closing = false;
|
|
46
|
+
const queue: Request[] = [];
|
|
47
|
+
|
|
48
|
+
// SQLite returns all integers as JS numbers; int8 is a string in node-postgres
|
|
49
|
+
// by default and COUNT(*) / BIGINT columns must stay numbers.
|
|
50
|
+
pg.types.setTypeParser(20, (value) => Number(value));
|
|
51
|
+
pg.types.setTypeParser(1700, (value) => Number(value));
|
|
52
|
+
|
|
53
|
+
function normalize(params: unknown[]): unknown[] {
|
|
54
|
+
return params.map((value) =>
|
|
55
|
+
value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function serialize(error: unknown): SerializedError {
|
|
59
|
+
const source = (typeof error === "object" && error !== null ? error : {}) as Record<string, unknown>;
|
|
60
|
+
const result: SerializedError = {
|
|
61
|
+
message: typeof source.message === "string" ? source.message : String(error),
|
|
62
|
+
};
|
|
63
|
+
for (const key of ERROR_FIELDS) {
|
|
64
|
+
const value = source[key];
|
|
65
|
+
if (typeof value === "string" || typeof value === "number") result[key] = value;
|
|
66
|
+
}
|
|
67
|
+
return result;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function signalReady(): void {
|
|
71
|
+
if (!readyFlag) return;
|
|
72
|
+
Atomics.store(readyFlag, 0, 1);
|
|
73
|
+
Atomics.notify(readyFlag, 0);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function reply(request: Request, payload: Record<string, unknown>): void {
|
|
77
|
+
try { port?.postMessage({ id: request.id, ...payload }); } catch { /* port already retired */ }
|
|
78
|
+
const flag = new Int32Array(request.signal);
|
|
79
|
+
Atomics.store(flag, 0, 1);
|
|
80
|
+
Atomics.notify(flag, 0);
|
|
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
|
+
|
|
108
|
+
async function handle(request: Request): Promise<void> {
|
|
109
|
+
const db = client;
|
|
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 });
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
const text = translate(request.sql);
|
|
116
|
+
if (!hasSql(text)) return reply(request, { ok: true, rows: [], row: null, changes: 0 });
|
|
117
|
+
const params = normalize(request.params ?? []);
|
|
118
|
+
// exec without params uses the simple-query protocol so multi-statement
|
|
119
|
+
// schema scripts (and BEGIN/COMMIT) run in one round trip.
|
|
120
|
+
const result = request.mode === "exec" && params.length === 0
|
|
121
|
+
? await db.query(text)
|
|
122
|
+
: await db.query({ text, values: params });
|
|
123
|
+
if (request.mode === "get") return reply(request, { ok: true, row: result.rows?.[0] ?? null });
|
|
124
|
+
if (request.mode === "all") return reply(request, { ok: true, rows: result.rows ?? [] });
|
|
125
|
+
const last = Array.isArray(result) ? result.at(-1) : result;
|
|
126
|
+
// Identity columns are never read through Database.run in the state layer;
|
|
127
|
+
// keep the API shape without pretending to know an insert id.
|
|
128
|
+
return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
|
|
129
|
+
} catch (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 });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function drain(): Promise<void> {
|
|
137
|
+
draining = true;
|
|
138
|
+
while (queue.length && !closing) {
|
|
139
|
+
const request = queue.shift();
|
|
140
|
+
if (request) await handle(request);
|
|
141
|
+
}
|
|
142
|
+
draining = false;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function shutdown(signal?: SharedArrayBuffer): Promise<void> {
|
|
146
|
+
closing = true;
|
|
147
|
+
try { await client?.end(); } catch { /* connection already gone */ }
|
|
148
|
+
try { port?.close(); } catch { /* already closed */ }
|
|
149
|
+
if (signal) {
|
|
150
|
+
const flag = new Int32Array(signal);
|
|
151
|
+
Atomics.store(flag, 0, 1);
|
|
152
|
+
Atomics.notify(flag, 0);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function handlePortMessage(message: PortMessage): void {
|
|
157
|
+
if (!("id" in message)) {
|
|
158
|
+
void shutdown(message.signal);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
queue.push(message);
|
|
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();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function startup(connectionString: string, ready: SharedArrayBuffer, timeout: number): Promise<void> {
|
|
168
|
+
readyFlag = new Int32Array(ready);
|
|
169
|
+
statementTimeout = timeout;
|
|
170
|
+
try {
|
|
171
|
+
const db = new pg.Client({
|
|
172
|
+
connectionString,
|
|
173
|
+
application_name: "opencode-chat-room",
|
|
174
|
+
statement_timeout: statementTimeout,
|
|
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")));
|
|
180
|
+
client = db;
|
|
181
|
+
await db.connect();
|
|
182
|
+
connected = true;
|
|
183
|
+
port?.postMessage({ type: "ready" });
|
|
184
|
+
signalReady();
|
|
185
|
+
if (queue.length && !draining) void drain();
|
|
186
|
+
} catch (error) {
|
|
187
|
+
port?.postMessage({ type: "fatal", error: serialize(error) });
|
|
188
|
+
signalReady();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const parent = parentPort;
|
|
193
|
+
if (parent) {
|
|
194
|
+
parent.on("message", (message: InitMessage) => {
|
|
195
|
+
if (message?.type !== "init" || client) return;
|
|
196
|
+
port = message.port;
|
|
197
|
+
port.on("message", handlePortMessage);
|
|
198
|
+
parent.close();
|
|
199
|
+
void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
|
|
200
|
+
});
|
|
201
|
+
}
|