@sleep2agi/commhub-server 0.9.0-preview.70 → 0.9.0-preview.71

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/src/db-adapter.ts CHANGED
@@ -2,12 +2,14 @@
2
2
  * Database Adapter — supports SQLite and PostgreSQL
3
3
  *
4
4
  * SQLite adapter: wraps bun:sqlite (sync)
5
- * PostgreSQL adapter: wraps pg Pool (async, bridged to sync interface via blocking)
5
+ * PostgreSQL adapter: one Bun.SQL connection in a worker thread, bridged to the
6
+ * sync interface with Atomics.wait (pg-worker.ts)
6
7
  *
7
8
  * Key design: callers write SQLite-style SQL. PgAdapter auto-translates:
8
9
  * - ?1, ?2 → $1, $2
9
- * - datetime('now') → NOW()
10
- * - datetime('now', '+N seconds') → NOW() + INTERVAL 'N seconds'
10
+ * - datetime('now'[, offset]) → to_char(... AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')
11
+ * (timestamps stay TEXT on both backends, RFC-039 §4.1)
12
+ * - BLOB → BYTEA
11
13
  * - INTEGER PRIMARY KEY AUTOINCREMENT → SERIAL PRIMARY KEY
12
14
  * - ON CONFLICT(col) DO UPDATE SET → ON CONFLICT(col) DO UPDATE SET (same syntax)
13
15
  */
@@ -39,14 +41,32 @@ export interface DbAdapter {
39
41
 
40
42
  /** Dialect identifier */
41
43
  readonly dialect: "sqlite" | "postgres";
44
+
45
+ /** True when transaction() is all-or-nothing on one connection. */
46
+ readonly atomicTransactions: boolean;
47
+
48
+ /**
49
+ * Why features that need atomic transactions (scheduler, runtime evidence,
50
+ * side-thread command outbox) must stay off on this adapter, or null when
51
+ * they may run. Gates refuse on anything but null, so an adapter that does
52
+ * not implement this also refuses.
53
+ */
54
+ readonly transactionalFeaturesRefusal: string | null;
42
55
  }
43
56
 
57
+ /** RFC-039: opt-in for PostgreSQL features whose PG tests do not exist yet (S4). */
58
+ export const PG_EXPERIMENTAL_ENV = "COMMHUB_PG_EXPERIMENTAL";
59
+
44
60
  // ════════════════════════════════════════════
45
61
  // SQLite Adapter (bun:sqlite, sync)
46
62
  // ════════════════════════════════════════════
47
63
 
48
64
  export class SQLiteAdapter implements DbAdapter {
49
65
  readonly dialect = "sqlite" as const;
66
+ readonly atomicTransactions = true;
67
+ get transactionalFeaturesRefusal(): string | null {
68
+ return this.atomicTransactions ? null : "transactions on this adapter are not atomic";
69
+ }
50
70
  constructor(private readonly rawDb: Database) {}
51
71
 
52
72
  run(sql: string, params?: any[]): QueryResult {
@@ -78,6 +98,15 @@ export class SQLiteAdapter implements DbAdapter {
78
98
  // PostgreSQL Adapter (pg Pool, sync bridge)
79
99
  // ════════════════════════════════════════════
80
100
 
101
+ /**
102
+ * PostgreSQL expression for SQLite's `datetime(...)` text: UTC, `YYYY-MM-DD HH:MM:SS`.
103
+ * Timestamps stay TEXT on both backends (RFC-039 §4.1), so a column written by
104
+ * `datetime('now')` compares, sorts and serialises the same way on each.
105
+ */
106
+ function pgUtcText(expr: string): string {
107
+ return `to_char((${expr}) AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`;
108
+ }
109
+
81
110
  /**
82
111
  * Translate SQLite-style SQL to PostgreSQL.
83
112
  * Called on every query — must be fast (simple regex, no parsing).
@@ -85,18 +114,17 @@ export class SQLiteAdapter implements DbAdapter {
85
114
  export function sqliteToPostgres(sql: string): string {
86
115
  let s = sql;
87
116
  // ── datetime translations (before ?N→$N to handle datetime('now', ?N)) ──
88
- // datetime('now', ?N) → NOW() + $N::INTERVAL (param contains "+3600 seconds")
117
+ // datetime('now', ?N) → UTC text of NOW() + $N (param contains "+3600 seconds").
118
+ // The CAST gives PG a type for a parameter it could not otherwise infer.
89
119
  s = s.replace(/datetime\s*\(\s*'now'\s*,\s*\?(\d+)\s*\)/gi, (_, n) => {
90
- return `NOW() + $${n}::INTERVAL`;
120
+ return pgUtcText(`NOW() + CAST($${n} AS TEXT)::INTERVAL`);
91
121
  });
92
- // datetime('now', '+N seconds') → NOW() + INTERVAL 'N seconds'
122
+ // datetime('now', '+N seconds') → UTC text of NOW() + INTERVAL 'N seconds'
93
123
  s = s.replace(/datetime\s*\(\s*'now'\s*,\s*'([^']+)'\s*\)/gi, (_, offset) => {
94
- return `NOW() + INTERVAL '${offset.replace(/^\+/, "")}'`;
124
+ return pgUtcText(`NOW() + INTERVAL '${offset.replace(/^\+/, "")}'`);
95
125
  });
96
- // datetime('now') → NOW()
97
- s = s.replace(/datetime\s*\(\s*'now'\s*\)/gi, "NOW()");
98
- // TEXT NOT NULL DEFAULT (datetime('now')) → TIMESTAMP NOT NULL DEFAULT NOW()
99
- s = s.replace(/TEXT\s+NOT\s+NULL\s+DEFAULT\s+\(NOW\(\)\)/gi, "TIMESTAMP NOT NULL DEFAULT NOW()");
126
+ // datetime('now') → UTC text of NOW()
127
+ s = s.replace(/datetime\s*\(\s*'now'\s*\)/gi, pgUtcText("NOW()"));
100
128
  // ── Parameter placeholders ──
101
129
  // ?1, ?2 → $1, $2 (positional params)
102
130
  s = s.replace(/\?(\d+)/g, (_, n) => `$${n}`);
@@ -106,67 +134,148 @@ export function sqliteToPostgres(sql: string): string {
106
134
  // ── DDL translations ──
107
135
  // INTEGER PRIMARY KEY AUTOINCREMENT → SERIAL PRIMARY KEY
108
136
  s = s.replace(/INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT/gi, "SERIAL PRIMARY KEY");
137
+ // BLOB → BYTEA
138
+ s = s.replace(/\bBLOB\b/gi, "BYTEA");
109
139
  return s;
110
140
  }
111
141
 
112
142
  /**
113
- * PostgreSQL adapter using a synchronous subprocess bridge.
143
+ * Split a multi-statement script on top-level `;`.
114
144
  *
115
- * TODO(P0-4): this is not transaction-safe. querySync currently starts a
116
- * fresh `node -e` process for every statement, so BEGIN/COMMIT/ROLLBACK do
117
- * not share one backend connection. PostgreSQL support is demoted behind
118
- * SQLite for now; before advertising it as production-ready, replace this
119
- * bridge with a long-lived worker or make DbAdapter async and use pg directly.
145
+ * A bare `split(";")` cut through SQL comments (db.ts has `;` inside `--`
146
+ * comments) and through plpgsql `$$ … $$` bodies, so the Hub died on its
147
+ * first schema block on PostgreSQL. This skips `--` and `/* *\/` comments
148
+ * (dropping them) and keeps quoted strings, quoted identifiers and
149
+ * dollar-quoted bodies intact.
150
+ */
151
+ export function splitSqlStatements(sql: string): string[] {
152
+ const out: string[] = [];
153
+ let cur = "";
154
+ let i = 0;
155
+ const n = sql.length;
156
+ while (i < n) {
157
+ const c = sql[i];
158
+ if (c === "-" && sql[i + 1] === "-") {
159
+ while (i < n && sql[i] !== "\n") i++;
160
+ continue;
161
+ }
162
+ if (c === "/" && sql[i + 1] === "*") {
163
+ const close = sql.indexOf("*/", i + 2);
164
+ i = close < 0 ? n : close + 2;
165
+ cur += " ";
166
+ continue;
167
+ }
168
+ if (c === "'" || c === '"') {
169
+ let j = i + 1;
170
+ while (j < n) {
171
+ if (sql[j] === c) {
172
+ if (sql[j + 1] === c) { j += 2; continue; }
173
+ break;
174
+ }
175
+ j++;
176
+ }
177
+ cur += sql.slice(i, j + 1);
178
+ i = j + 1;
179
+ continue;
180
+ }
181
+ if (c === "$") {
182
+ const tag = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
183
+ if (tag) {
184
+ const close = sql.indexOf(tag[0], i + tag[0].length);
185
+ const stop = close < 0 ? n : close + tag[0].length;
186
+ cur += sql.slice(i, stop);
187
+ i = stop;
188
+ continue;
189
+ }
190
+ }
191
+ if (c === ";") {
192
+ if (cur.trim()) out.push(cur.trim());
193
+ cur = "";
194
+ i++;
195
+ continue;
196
+ }
197
+ cur += c;
198
+ i++;
199
+ }
200
+ if (cur.trim()) out.push(cur.trim());
201
+ return out;
202
+ }
203
+
204
+ /**
205
+ * PostgreSQL adapter: synchronous facade over one long-lived worker thread
206
+ * (RFC-039 S2b).
207
+ *
208
+ * The worker (pg-worker.ts) holds a single reserved Bun.SQL connection. Each
209
+ * call posts one request and blocks on Atomics.wait until the worker answers,
210
+ * so the DbAdapter interface stays synchronous — the same contract bun:sqlite
211
+ * gives the rest of the Hub, including "nothing else runs while a transaction
212
+ * is open". Because every statement uses the same backend connection,
213
+ * BEGIN/COMMIT/ROLLBACK are real transactions.
214
+ *
215
+ * SQLite semantics kept on purpose:
216
+ * - a failed statement inside a transaction does not poison the transaction
217
+ * (each statement inside one runs under a savepoint);
218
+ * - nested transaction() calls become savepoints;
219
+ * - booleans bind as 1/0 and undefined as NULL.
120
220
  */
121
221
  export class PgAdapter implements DbAdapter {
122
222
  readonly dialect = "postgres" as const;
123
- private connString: string;
223
+ readonly atomicTransactions = true;
224
+ /** Closed by default on PG even with real transactions: explicit opt-in only. */
225
+ get transactionalFeaturesRefusal(): string | null {
226
+ if (!this.atomicTransactions) return "transactions on this adapter are not atomic";
227
+ if (process.env[PG_EXPERIMENTAL_ENV] === "1") return null;
228
+ return `PostgreSQL support is experimental; set ${PG_EXPERIMENTAL_ENV}=1 to enable this feature on it (RFC-039)`;
229
+ }
230
+ private readonly port: MessagePort;
231
+ private readonly flag: Int32Array;
232
+ private readonly worker: import("node:worker_threads").Worker;
233
+ private readonly waitMs: number;
234
+ private txDepth = 0;
124
235
 
125
236
  constructor(connectionString: string) {
126
- this.connString = connectionString;
127
- // Validate pg is available
128
- try { require("pg"); } catch (e) {
129
- throw new Error(
130
- "PostgreSQL support requires 'pg' package. Install with: bun add pg\n" +
131
- ` Original error: ${(e as Error).message}`
132
- );
133
- }
237
+ const { Worker, MessageChannel } = require("node:worker_threads") as typeof import("node:worker_threads");
238
+ const statementTimeoutMs = Number(process.env.COMMHUB_PG_STATEMENT_TIMEOUT_MS || 30_000);
239
+ // The main thread waits a little longer than PG itself will run a statement.
240
+ this.waitMs = statementTimeoutMs > 0 ? statementTimeoutMs + 5_000 : 300_000;
241
+ const { port1, port2 } = new MessageChannel();
242
+ this.port = port1 as unknown as MessagePort;
243
+ this.flag = new Int32Array(new SharedArrayBuffer(4));
244
+ this.worker = new Worker(new URL("./pg-worker.ts", import.meta.url), {
245
+ workerData: { port: port2, flag: this.flag, url: connectionString, statementTimeoutMs },
246
+ transferList: [port2 as any],
247
+ });
248
+ this.worker.unref();
249
+ (port1 as any).unref?.();
134
250
  // Test connection on startup
135
- const test = this.querySync("SELECT 1 as ok");
251
+ const test = this.request("SELECT 1 as ok");
136
252
  if (!test.rows?.[0]?.ok) throw new Error("PostgreSQL connection test failed");
137
253
  console.log("[commhub] PostgreSQL connection verified");
138
254
  }
139
255
 
140
- private querySync(sql: string, params?: any[]): { rows: any[]; rowCount: number } {
141
- const pgSql = sqliteToPostgres(sql);
142
- // Single-query subprocess with pg Pool (connection string from env)
143
- const script = `
144
- const{Pool}=require('pg');
145
- const p=new Pool({connectionString:${JSON.stringify(this.connString)},max:1});
146
- const q=${JSON.stringify(pgSql)};
147
- const v=${JSON.stringify(params || [])};
148
- p.query(q,v).then(r=>{
149
- process.stdout.write(JSON.stringify({rows:r.rows,rowCount:r.rowCount||0}));
150
- p.end();
151
- }).catch(e=>{
152
- process.stderr.write(e.message);
153
- p.end();
154
- process.exit(1);
155
- });
156
- `;
157
- const proc = Bun.spawnSync(["node", "--no-warnings", "-e", script], {
158
- stdout: "pipe", stderr: "pipe",
159
- });
160
- if (proc.exitCode !== 0) {
161
- throw new Error(`PG: ${proc.stderr.toString().trim() || "query failed"}`);
256
+ /** Send one already-translated statement to the worker and block for the answer. */
257
+ private request(pgSql: string, params?: any[]): { rows: any[]; count: number } {
258
+ const { receiveMessageOnPort } = require("node:worker_threads") as typeof import("node:worker_threads");
259
+ const bound = (params ?? []).map(v => v === undefined ? null : typeof v === "boolean" ? (v ? 1 : 0) : v);
260
+ Atomics.store(this.flag, 0, 0);
261
+ (this.port as any).postMessage({ sql: pgSql, params: bound, guard: this.txDepth > 0 });
262
+ if (Atomics.wait(this.flag, 0, 0, this.waitMs) === "timed-out") {
263
+ throw new Error(`PG: no answer from the database worker within ${this.waitMs}ms`);
162
264
  }
163
- return JSON.parse(proc.stdout.toString().trim());
265
+ const reply = receiveMessageOnPort(this.port as any)?.message as any;
266
+ if (!reply) throw new Error("PG: database worker signalled without a reply");
267
+ if (!reply.ok) throw new Error(`PG: ${reply.error}`);
268
+ return reply;
269
+ }
270
+
271
+ private querySync(sql: string, params?: any[]): { rows: any[]; count: number } {
272
+ return this.request(sqliteToPostgres(sql), params);
164
273
  }
165
274
 
166
275
  run(sql: string, params?: any[]): QueryResult {
167
276
  if (sql.trim().toUpperCase().startsWith("PRAGMA")) return { changes: 0 };
168
277
  const result = this.querySync(sql, params);
169
- return { changes: result.rowCount };
278
+ return { changes: result.count };
170
279
  }
171
280
 
172
281
  get<T = any>(sql: string, ...params: any[]): T | null {
@@ -183,9 +292,9 @@ export class PgAdapter implements DbAdapter {
183
292
  if (sql.trim().toUpperCase().startsWith("PRAGMA")) return;
184
293
  const pgSql = sqliteToPostgres(sql);
185
294
  // Split multi-statement DDL (CREATE TABLE; CREATE INDEX; ...)
186
- const stmts = pgSql.split(";").map(s => s.trim()).filter(s => s.length > 0);
295
+ const stmts = splitSqlStatements(pgSql);
187
296
  for (const stmt of stmts) {
188
- try { this.querySync(stmt); } catch (e: any) {
297
+ try { this.request(stmt); } catch (e: any) {
189
298
  // Ignore "already exists" errors for CREATE TABLE/INDEX IF NOT EXISTS
190
299
  if (!/already exists/.test(e.message)) throw e;
191
300
  }
@@ -193,19 +302,32 @@ export class PgAdapter implements DbAdapter {
193
302
  }
194
303
 
195
304
  transaction<T>(fn: () => T): T {
196
- // Not atomic for PostgreSQL until P0-4 is implemented; see class TODO.
197
- this.querySync("BEGIN");
305
+ const depth = this.txDepth;
306
+ const savepoint = `anet_tx_${depth}`;
307
+ // Control statements run unguarded: they are what the guard is made of.
308
+ this.txDepth = 0;
309
+ try { this.request(depth === 0 ? "BEGIN" : `SAVEPOINT ${savepoint}`); } finally { this.txDepth = depth; }
310
+ this.txDepth = depth + 1;
311
+ let result: T;
198
312
  try {
199
- const result = fn();
200
- this.querySync("COMMIT");
201
- return result;
313
+ result = fn();
202
314
  } catch (e) {
203
- try { this.querySync("ROLLBACK"); } catch {}
315
+ this.txDepth = 0;
316
+ try {
317
+ if (depth === 0) this.request("ROLLBACK");
318
+ else { this.request(`ROLLBACK TO SAVEPOINT ${savepoint}`); this.request(`RELEASE SAVEPOINT ${savepoint}`); }
319
+ } catch {}
320
+ this.txDepth = depth;
204
321
  throw e;
205
322
  }
323
+ this.txDepth = 0;
324
+ try { this.request(depth === 0 ? "COMMIT" : `RELEASE SAVEPOINT ${savepoint}`); } finally { this.txDepth = depth; }
325
+ return result;
206
326
  }
207
327
 
208
- close(): void {}
328
+ close(): void {
329
+ this.worker.terminate();
330
+ }
209
331
  }
210
332
 
211
333
  // ════════════════════════════════════════════
package/src/db.ts CHANGED
@@ -983,7 +983,7 @@ try { db.exec("ALTER TABLE requirements ADD COLUMN client_id TEXT"); } catch {}
983
983
  try { db.exec("ALTER TABLE requirements ADD COLUMN issues_json TEXT"); } catch {}
984
984
  try { db.exec("ALTER TABLE requirements ADD COLUMN tags_json TEXT NOT NULL DEFAULT '[]'"); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
985
985
  db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_requirements_client ON requirements(network_id, client_id) WHERE client_id IS NOT NULL AND client_id != ''");
986
- for (const column of ["owner_json TEXT", "participants_json TEXT NOT NULL DEFAULT '[]'", "agent_owner_json TEXT", "description TEXT", "checklist_json TEXT", "project_id TEXT", "external_ref TEXT", "external_url TEXT", "archived INTEGER NOT NULL DEFAULT 0", "created_by_json TEXT", "updated_by_json TEXT", "parent_id TEXT"]) {
986
+ for (const column of ["owner_json TEXT", "participants_json TEXT NOT NULL DEFAULT '[]'", "agent_owner_json TEXT", "description TEXT", "checklist_json TEXT", "project_id TEXT", "external_ref TEXT", "external_url TEXT", "archived INTEGER NOT NULL DEFAULT 0", "created_by_json TEXT", "updated_by_json TEXT", "parent_id TEXT", "start_on TEXT"]) {
987
987
  try { db.exec(`ALTER TABLE requirements ADD COLUMN ${column}`); } catch (e: any) { if (!/duplicate column|already exists/i.test(e?.message || "")) throw e; }
988
988
  }
989
989
 
@@ -1068,6 +1068,43 @@ db.exec(`
1068
1068
  CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_grants_alias ON network_member_agent_grants(network_id, user_id, alias) WHERE alias IS NOT NULL;
1069
1069
  `);
1070
1070
 
1071
+ // ── Agent 分组(RFC-038 §8):管理员自由定义的组,授权可以给到组,组成员动态生效 ──
1072
+ // 组授权单独一张表(不给 network_member_agent_grants 加列):那张表的 CHECK 改不了,
1073
+ // 而且旧 app 的 PUT 是整体替换 —— 同表的话,旧 app 一保存就把组授权清掉。
1074
+ db.exec(`
1075
+ CREATE TABLE IF NOT EXISTS agent_groups (
1076
+ group_id TEXT PRIMARY KEY,
1077
+ network_id TEXT NOT NULL,
1078
+ name TEXT NOT NULL,
1079
+ description TEXT,
1080
+ created_by TEXT,
1081
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1082
+ updated_at TEXT
1083
+ );
1084
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_groups_name ON agent_groups(network_id, name);
1085
+
1086
+ CREATE TABLE IF NOT EXISTS agent_group_members (
1087
+ group_id TEXT NOT NULL,
1088
+ node_id TEXT NOT NULL,
1089
+ added_by TEXT,
1090
+ added_at TEXT NOT NULL DEFAULT (datetime('now')),
1091
+ PRIMARY KEY (group_id, node_id)
1092
+ );
1093
+
1094
+ CREATE TABLE IF NOT EXISTS network_member_group_grants (
1095
+ network_id TEXT NOT NULL,
1096
+ user_id TEXT NOT NULL,
1097
+ group_id TEXT NOT NULL,
1098
+ can_message INTEGER NOT NULL DEFAULT 1,
1099
+ created_by TEXT,
1100
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1101
+ PRIMARY KEY (network_id, user_id, group_id)
1102
+ );
1103
+ -- 改组成员 / 删组时按组找被授权成员(usersGrantedGroup、granted_user_count):主键以 network_id 开头用不上。
1104
+ -- 展开查询本身走各表主键,见 agent-groups-perf.test.ts 的 EXPLAIN QUERY PLAN。
1105
+ CREATE INDEX IF NOT EXISTS idx_group_grants_group ON network_member_group_grants(group_id);
1106
+ `);
1107
+
1071
1108
  // ── #84: node rename — rename_txn table (RFC-010 §4) ──
1072
1109
  // Single isolated table holding the rename 2PC transaction state. It doubles
1073
1110
  // as the alias_rename_log (RFC §4 risk #5): the audit log of completed renames
@@ -1475,7 +1512,7 @@ if (db.dialect === "sqlite") {
1475
1512
  IF NEW.status IN ('replied', 'failed', 'cancelled', 'expired')
1476
1513
  AND (TG_OP = 'INSERT' OR OLD.status NOT IN ('replied', 'failed', 'cancelled', 'expired')) THEN
1477
1514
  INSERT INTO task_terminal_events (task_id, network_id, from_node_id, completed_at)
1478
- VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, NOW()))
1515
+ VALUES (NEW.task_id, NEW.network_id, NEW.from_node_id, COALESCE(NEW.completed_at, datetime('now')))
1479
1516
  ON CONFLICT (task_id) DO NOTHING;
1480
1517
  END IF;
1481
1518
  RETURN NEW;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * PostgreSQL worker for PgAdapter (RFC-039 S2b).
3
+ *
4
+ * Holds ONE reserved Bun.SQL connection for the life of the Hub, so BEGIN /
5
+ * statements / COMMIT all run on the same backend and transactions are real.
6
+ * The main thread posts one request at a time and blocks on `flag` with
7
+ * Atomics.wait; this worker answers on `port` and then notifies, which keeps
8
+ * DbAdapter synchronous exactly like bun:sqlite.
9
+ *
10
+ * Request: { sql, params?, guard? } guard=true wraps the statement in a
11
+ * savepoint so a failed statement inside a transaction behaves like
12
+ * SQLite (the statement fails, the transaction survives).
13
+ * Response: { ok: true, rows, count } | { ok: false, error, code }
14
+ */
15
+ import { workerData } from "node:worker_threads";
16
+ import { SQL } from "bun";
17
+
18
+ type Request = { sql: string; params?: unknown[]; guard?: boolean };
19
+
20
+ const { port, flag, url, statementTimeoutMs } = workerData as {
21
+ port: MessagePort;
22
+ flag: Int32Array;
23
+ url: string;
24
+ statementTimeoutMs: number;
25
+ };
26
+
27
+ // bigint:true makes int8 arrive as BigInt, so it can be told apart from a
28
+ // TEXT column that happens to hold digits; normalise() turns it into a number.
29
+ // libpq's `connect_timeout` (seconds) in the URL is honoured, default 10 s,
30
+ // so an endpoint that accepts TCP but never speaks PostgreSQL fails the
31
+ // startup check instead of hanging the Hub.
32
+ const connectTimeout = Number(new URL(url).searchParams.get("connect_timeout") || 10);
33
+ const sql = new SQL(url, { max: 1, bigint: true, connectionTimeout: connectTimeout > 0 ? connectTimeout : 10 });
34
+ let conn: any = null;
35
+
36
+ async function connection() {
37
+ if (!conn) {
38
+ conn = await sql.reserve();
39
+ await conn.unsafe("SET TIME ZONE 'UTC'");
40
+ await conn.unsafe(`SET statement_timeout = ${Math.max(0, Math.floor(statementTimeoutMs))}`);
41
+ }
42
+ return conn;
43
+ }
44
+
45
+ function normalise(value: unknown): unknown {
46
+ if (typeof value === "bigint") {
47
+ const n = Number(value);
48
+ return Number.isSafeInteger(n) ? n : value.toString();
49
+ }
50
+ return value;
51
+ }
52
+
53
+ async function handle(req: Request) {
54
+ const c = await connection();
55
+ if (req.guard) await c.unsafe("SAVEPOINT anet_stmt");
56
+ let result: any;
57
+ try {
58
+ result = await c.unsafe(req.sql, req.params ?? []);
59
+ } catch (e) {
60
+ if (req.guard) {
61
+ await c.unsafe("ROLLBACK TO SAVEPOINT anet_stmt");
62
+ await c.unsafe("RELEASE SAVEPOINT anet_stmt");
63
+ }
64
+ throw e;
65
+ }
66
+ if (req.guard) await c.unsafe("RELEASE SAVEPOINT anet_stmt");
67
+ const rows = [...result].map((row: Record<string, unknown>) => {
68
+ for (const k of Object.keys(row)) row[k] = normalise(row[k]);
69
+ return row;
70
+ });
71
+ return { ok: true, rows, count: typeof result.count === "number" ? result.count : rows.length };
72
+ }
73
+
74
+ port.on("message", async (req: Request) => {
75
+ let out: unknown;
76
+ try {
77
+ out = await handle(req);
78
+ } catch (e: any) {
79
+ // A dropped connection is not retried: a retry inside a transaction would
80
+ // replay half of it. Forget it so the next request reconnects.
81
+ if (String(e?.code ?? "").startsWith("ERR_POSTGRES_CONNECTION")) conn = null;
82
+ out = { ok: false, error: String(e?.message ?? e), code: e?.errno ?? e?.code ?? null };
83
+ }
84
+ port.postMessage(out);
85
+ Atomics.store(flag, 0, 1);
86
+ Atomics.notify(flag, 0);
87
+ });
@@ -0,0 +1,91 @@
1
+ // GET /api/requirements conditional requests: ETag on every list response, 304 with an empty body
2
+ // when If-None-Match matches. The app polls the whole list every 15 s (production: 500 rows,
3
+ // 708 KB / 163 KB gzip) and it is unchanged on almost every poll. Old clients never send
4
+ // If-None-Match and keep getting the full 200.
5
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6
+ import { mkdtempSync, rmSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+
10
+ const dir = mkdtempSync(join(tmpdir(), "anet-requirements-etag-"));
11
+ process.env.COMMHUB_DB = join(dir, "hub.db");
12
+
13
+ let server: { port: number; stop?: (force?: boolean) => void };
14
+ let base = "";
15
+ let ownerToken = "", network = "";
16
+
17
+ const list = (token: string, headers: Record<string, string> = {}) =>
18
+ fetch(`${base}/api/requirements?network_id=${network}`, { headers: { Authorization: `Bearer ${token}`, ...headers } });
19
+
20
+ beforeAll(async () => {
21
+ const { register } = await import("./auth.js");
22
+ const owner = register(`etag_owner_${Date.now()}`, "EtagOwnerPassw0rd!", undefined, "seed");
23
+ ownerToken = owner.token!; network = owner.network_id!;
24
+ const mod: any = await import("./server.js");
25
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
26
+ base = `http://127.0.0.1:${server.port}`;
27
+ const created = await fetch(`${base}/api/requirements`, {
28
+ method: "POST",
29
+ headers: { Authorization: `Bearer ${ownerToken}`, "Content-Type": "application/json" },
30
+ body: JSON.stringify({ name: "etag card", network_id: network }),
31
+ });
32
+ expect(created.status).toBe(201);
33
+ }, 30_000);
34
+
35
+ afterAll(() => {
36
+ try { server?.stop?.(true); } catch {}
37
+ try { rmSync(dir, { recursive: true, force: true }); } catch {}
38
+ });
39
+
40
+ describe("GET /api/requirements conditional requests", () => {
41
+ test("a plain GET is the same 200 JSON as before, plus ETag and private/no-cache", async () => {
42
+ const res = await list(ownerToken);
43
+ expect(res.status).toBe(200);
44
+ expect(res.headers.get("content-type")).toBe("application/json;charset=utf-8");
45
+ expect(res.headers.get("etag")).toMatch(/^W\/"[A-Za-z0-9_-]{27}"$/);
46
+ expect(res.headers.get("cache-control")).toBe("private, no-cache");
47
+ const body = await res.json() as any;
48
+ expect(body.ok).toBe(true);
49
+ expect(body.requirements.map((r: any) => r.name)).toEqual(["etag card"]);
50
+ expect(Array.isArray(body.capabilities)).toBe(true);
51
+ });
52
+
53
+ test("If-None-Match with the current ETag → 304, empty body, same ETag", async () => {
54
+ const etag = (await list(ownerToken)).headers.get("etag")!;
55
+ const res = await list(ownerToken, { "If-None-Match": etag });
56
+ expect(res.status).toBe(304);
57
+ expect(res.headers.get("etag")).toBe(etag);
58
+ expect(await res.text()).toBe("");
59
+ // strong/weak spelling and lists are accepted
60
+ expect((await list(ownerToken, { "If-None-Match": etag.replace(/^W\//, "") })).status).toBe(304);
61
+ expect((await list(ownerToken, { "If-None-Match": `W/"stale", ${etag}` })).status).toBe(304);
62
+ });
63
+
64
+ test("304 survives gzip negotiation (not compressed, still empty)", async () => {
65
+ const etag = (await list(ownerToken, { "Accept-Encoding": "gzip" })).headers.get("etag")!;
66
+ const res = await list(ownerToken, { "If-None-Match": etag, "Accept-Encoding": "gzip" });
67
+ expect(res.status).toBe(304);
68
+ expect(res.headers.get("content-encoding")).toBeNull();
69
+ });
70
+
71
+ test("any change to the list changes the ETag → full 200 again", async () => {
72
+ const before = await list(ownerToken);
73
+ const etag = before.headers.get("etag")!;
74
+ const id = ((await before.json()) as any).requirements[0].id;
75
+ const patched = await fetch(`${base}/api/requirements/${id}?network_id=${network}`, {
76
+ method: "PATCH",
77
+ headers: { Authorization: `Bearer ${ownerToken}`, "Content-Type": "application/json" },
78
+ body: JSON.stringify({ name: "etag card renamed" }),
79
+ });
80
+ expect(patched.status).toBe(200);
81
+ const res = await list(ownerToken, { "If-None-Match": etag });
82
+ expect(res.status).toBe(200);
83
+ expect(res.headers.get("etag")).not.toBe(etag);
84
+ expect(((await res.json()) as any).requirements[0].name).toBe("etag card renamed");
85
+ });
86
+
87
+ test("a stale or foreign ETag never yields 304", async () => {
88
+ expect((await list(ownerToken, { "If-None-Match": 'W/"not-the-current-one"' })).status).toBe(200);
89
+ expect((await list(ownerToken, { "If-None-Match": "" })).status).toBe(200);
90
+ });
91
+ });
@@ -372,7 +372,7 @@ describe("requirements stay on the hub", () => {
372
372
  expect((await api(ownerToken, path, { method: "PATCH", body: JSON.stringify({ due: "" }) })).body.requirement.due).toBe("");
373
373
  const listed = await api(ownerToken, "/api/requirements");
374
374
  expect(listed.body.capabilities).toContain("due_datetime");
375
- expect(listed.body.capabilities).toEqual(["agent_owner", "description", "checklist", "projects", "due_datetime", "external_ref", "archived", "agent_api", "sub_requirements", "tags", "priority_lowest"]);
375
+ expect(listed.body.capabilities).toEqual(["agent_owner", "description", "checklist", "projects", "due_datetime", "external_ref", "archived", "agent_api", "sub_requirements", "tags", "priority_lowest", "start_date"]);
376
376
  });
377
377
 
378
378
  test("sub-requirements: parent_id in the same network, no cycles, ≤ 5 levels, child counts, filters, delete detaches children", async () => {