@alexsun-top/opencode-chat-room 0.8.1 → 0.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +18 -62
- package/README.zh-CN.md +25 -69
- package/dist/cli.js +1008 -274
- package/package.json +10 -7
- package/packages/chat-room-channeld/README.md +42 -15
- package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
- package/packages/chat-room-channeld/src/adapter.ts +150 -7
- package/packages/chat-room-channeld/src/cli.ts +72 -5
- package/packages/chat-room-channeld/src/host.ts +41 -11
- package/packages/chat-room-channeld/src/inbound.ts +13 -4
- package/packages/chat-room-channeld/src/pg/database.ts +187 -0
- package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
- package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
- package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
- package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
- package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
- package/packages/chat-room-channeld/src/protocol.ts +53 -1
- package/packages/chat-room-channeld/src/rules.ts +7 -2
- package/packages/chat-room-channeld/src/state.ts +73 -97
- package/packages/chat-room-channeld/src/stats.ts +140 -109
- package/plugin.ts +1 -1
- package/server/assets/base.css +11 -3
- package/server/assets/chat/admin-badge.js +32 -30
- package/server/assets/chat/admin.js +198 -163
- package/server/assets/chat/announcements.js +295 -210
- package/server/assets/chat/attachment-store.js +106 -75
- package/server/assets/chat/attachments.js +686 -441
- package/server/assets/chat/chat-background.js +206 -0
- package/server/assets/chat/clipboard.js +44 -25
- package/server/assets/chat/confirm-dialog.js +36 -34
- package/server/assets/chat/copy-action.js +40 -40
- package/server/assets/chat/create-room-dialog.js +50 -48
- package/server/assets/chat/diagram-viewer.js +293 -228
- package/server/assets/chat/doc-preview.js +510 -388
- package/server/assets/chat/editor.js +423 -335
- package/server/assets/chat/events.js +637 -502
- package/server/assets/chat/files.js +476 -426
- package/server/assets/chat/history-loader.js +79 -73
- package/server/assets/chat/icons.js +9 -11
- package/server/assets/chat/image-zoom.js +239 -169
- package/server/assets/chat/index.js +6 -5
- package/server/assets/chat/install-prompt.js +86 -66
- package/server/assets/chat/integration-account-schema.js +101 -0
- package/server/assets/chat/integration-editor.js +162 -153
- package/server/assets/chat/integration-values.js +109 -100
- package/server/assets/chat/integrations.js +696 -479
- package/server/assets/chat/join-requests.js +408 -358
- package/server/assets/chat/locales/de.js +193 -194
- package/server/assets/chat/locales/es.js +193 -194
- package/server/assets/chat/locales/fr.js +193 -194
- package/server/assets/chat/locales/index.js +1 -2
- package/server/assets/chat/locales/it.js +193 -194
- package/server/assets/chat/locales/ja.js +193 -193
- package/server/assets/chat/locales/ko.js +193 -193
- package/server/assets/chat/markdown-footnotes.js +134 -102
- package/server/assets/chat/markdown.js +553 -386
- package/server/assets/chat/members.js +236 -197
- package/server/assets/chat/mentions.js +157 -133
- package/server/assets/chat/message-cache.js +40 -33
- package/server/assets/chat/message-polling.js +280 -227
- package/server/assets/chat/message-window.js +74 -55
- package/server/assets/chat/messages.js +552 -479
- package/server/assets/chat/office-preview.js +46 -45
- package/server/assets/chat/palette.js +450 -412
- package/server/assets/chat/panels.js +94 -58
- package/server/assets/chat/pwa.js +144 -73
- package/server/assets/chat/questions.js +372 -302
- package/server/assets/chat/recall.js +320 -273
- package/server/assets/chat/receipts.js +149 -122
- package/server/assets/chat/reminders.js +331 -216
- package/server/assets/chat/replies.js +165 -136
- package/server/assets/chat/resource-format.js +59 -62
- package/server/assets/chat/room-list.js +58 -55
- package/server/assets/chat/room-watcher.js +72 -50
- package/server/assets/chat/rooms.js +623 -505
- package/server/assets/chat/search.js +136 -114
- package/server/assets/chat/settings.js +229 -140
- package/server/assets/chat/shiki.js +61 -62
- package/server/assets/chat/shortcuts.js +212 -190
- package/server/assets/chat/side-pane.js +166 -131
- package/server/assets/chat/state.js +851 -707
- package/server/assets/chat/system-events.js +55 -27
- package/server/assets/chat/system-messages.js +59 -49
- package/server/assets/chat/task-form.js +178 -182
- package/server/assets/chat/task-row.js +158 -155
- package/server/assets/chat/tasks.js +653 -593
- package/server/assets/chat/viewport.js +32 -29
- package/server/assets/chat/window-controls.js +37 -0
- package/server/assets/code-highlight.css +22 -6
- package/server/assets/conversation.css +65 -16
- package/server/assets/doc-preview.css +6 -1
- package/server/assets/files.css +3 -0
- package/server/assets/monaco/integration-rules.css +1 -1
- package/server/assets/monaco/integration-rules.js +841 -533
- package/server/assets/responsive.css +32 -2
- package/server/assets/settings.css +117 -13
- package/server/assets/window-controls.css +36 -0
- package/server/channel-attachments.ts +133 -0
- package/server/channel-integration.ts +79 -26
- package/server/channels.ts +15 -5
- package/server/chat-server.ts +9 -1
- package/server/chat.html +73 -38
- package/server/manifest.webmanifest +1 -0
- package/server/routes/pages.ts +7 -5
- package/server/sw.js +346 -267
- package/src/center/center-client.ts +1 -1
- package/src/state/pg-database.ts +5 -5
- package/src/state/pg-migrate.ts +7 -7
- package/src/state/pg-worker.mjs +2 -17
- package/src/state/sqlite-database.ts +14 -5
- package/src/state/sqlite-rooms.ts +130 -23
- package/src/state/sqlite-state-store.ts +6 -5
- package/src/state/sqlite.ts +3 -3
- package/src/web/integration-rules-editor.ts +141 -5
- package/src/web/integration-rules.ts +6 -2
- package/src/web/integration-schema.ts +7 -6
- package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
- package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
- package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
- package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
- package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
- package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
- package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
- package/server/assets/chat/forward.js +0 -69
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { DatabaseSync, type StatementSync } from "node:sqlite";
|
|
2
|
+
|
|
3
|
+
// The subset of bun:sqlite that this codebase uses, backed by node:sqlite so the
|
|
4
|
+
// same synchronous driver runs on Node, Bun and Deno.
|
|
5
|
+
export type SQLQueryBindings = null | number | bigint | string | boolean | Uint8Array | undefined;
|
|
6
|
+
export type RunResult = { changes: number; lastInsertRowid: number };
|
|
7
|
+
type RawBindings = Array<null | number | bigint | string | Uint8Array>;
|
|
8
|
+
|
|
9
|
+
// bun:sqlite binds booleans as 1/0 and undefined as NULL; node:sqlite rejects both.
|
|
10
|
+
function bindings(params: SQLQueryBindings[]): RawBindings {
|
|
11
|
+
let values: SQLQueryBindings[] | undefined;
|
|
12
|
+
for (let index = 0; index < params.length; index++) {
|
|
13
|
+
const value = params[index];
|
|
14
|
+
if (value === undefined || typeof value === "boolean") {
|
|
15
|
+
values ??= params.slice();
|
|
16
|
+
values[index] = value === undefined ? null : value ? 1 : 0;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return (values ?? params) as RawBindings;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class Statement {
|
|
23
|
+
readonly #statement: StatementSync;
|
|
24
|
+
constructor(statement: StatementSync) { this.#statement = statement; }
|
|
25
|
+
all(...params: SQLQueryBindings[]): unknown[] {
|
|
26
|
+
return this.#statement.all(...bindings(params));
|
|
27
|
+
}
|
|
28
|
+
// bun:sqlite returns null for a missing row, node:sqlite returns undefined.
|
|
29
|
+
get(...params: SQLQueryBindings[]): unknown {
|
|
30
|
+
return this.#statement.get(...bindings(params)) ?? null;
|
|
31
|
+
}
|
|
32
|
+
run(...params: SQLQueryBindings[]): RunResult {
|
|
33
|
+
const result = this.#statement.run(...bindings(params));
|
|
34
|
+
return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type Transaction<T> = (() => T) & { deferred(): T; immediate(): T };
|
|
39
|
+
|
|
40
|
+
export type QueryStatement = {
|
|
41
|
+
all(...params: SQLQueryBindings[]): unknown[];
|
|
42
|
+
get(...params: SQLQueryBindings[]): unknown;
|
|
43
|
+
run(...params: SQLQueryBindings[]): RunResult;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// The synchronous surface used by the state layer. Implemented by the
|
|
47
|
+
// node:sqlite adapter and by PgDatabase's worker-thread bridge.
|
|
48
|
+
export interface StateDatabase {
|
|
49
|
+
query(sql: string): QueryStatement;
|
|
50
|
+
prepare(sql: string): QueryStatement;
|
|
51
|
+
exec(sql: string): void;
|
|
52
|
+
transaction<T>(fn: () => T): Transaction<T>;
|
|
53
|
+
close(): void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class Database implements StateDatabase {
|
|
57
|
+
readonly #db: DatabaseSync;
|
|
58
|
+
#savepoints = 0;
|
|
59
|
+
|
|
60
|
+
// node:sqlite always creates a missing file, matching the default Bun options.
|
|
61
|
+
constructor(file: string, options: { readOnly?: boolean } = {}) {
|
|
62
|
+
this.#db = options.readOnly ? new DatabaseSync(file, { readOnly: true }) : new DatabaseSync(file);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
query(sql: string): Statement { return new Statement(this.#db.prepare(sql)); }
|
|
66
|
+
prepare(sql: string): Statement { return this.query(sql); }
|
|
67
|
+
exec(sql: string): void { this.#db.exec(sql); }
|
|
68
|
+
|
|
69
|
+
transaction<T>(fn: () => T): Transaction<T> {
|
|
70
|
+
const run = (begin: string) => this.#run(begin, fn);
|
|
71
|
+
return Object.assign(() => run("BEGIN"), { deferred: () => run("BEGIN"), immediate: () => run("BEGIN IMMEDIATE") });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
close(): void { this.#db.close(); }
|
|
75
|
+
|
|
76
|
+
#run<T>(begin: string, fn: () => T): T {
|
|
77
|
+
// Nested calls become savepoints, like bun:sqlite transactions.
|
|
78
|
+
const nested = this.#db.isTransaction;
|
|
79
|
+
const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
|
|
80
|
+
this.#db.exec(nested ? `SAVEPOINT ${savepoint}` : begin);
|
|
81
|
+
try {
|
|
82
|
+
const result = fn();
|
|
83
|
+
this.#db.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
|
|
84
|
+
return result;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
try { this.#db.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK"); } catch { /* keep the original error */ }
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function isBusyError(error: unknown): boolean {
|
|
93
|
+
const err = error as { code?: string; errcode?: number; message?: string } | null;
|
|
94
|
+
if (!err) return false;
|
|
95
|
+
// PostgreSQL serialization failure, deadlock, and advisory-lock timeout. The
|
|
96
|
+
// existing immediate() retry loop treats these like SQLITE_BUSY/SQLITE_LOCKED.
|
|
97
|
+
if (err.code === "40001" || err.code === "40P01" || err.code === "55P03") return true;
|
|
98
|
+
if (typeof err.errcode === "number" && ((err.errcode & 0xff) === 5 || (err.errcode & 0xff) === 6)) return true;
|
|
99
|
+
return /SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || /database (?:is|table is) locked/i.test(err.message ?? "");
|
|
100
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { parentPort } from "node:worker_threads";
|
|
2
|
+
import pg from "pg";
|
|
3
|
+
import { hasSql, translate } from "./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
|
+
let client;
|
|
14
|
+
let port;
|
|
15
|
+
let readyFlag;
|
|
16
|
+
let statementTimeout = 4_500;
|
|
17
|
+
let connected = false;
|
|
18
|
+
let draining = false;
|
|
19
|
+
let closing = false;
|
|
20
|
+
const queue = [];
|
|
21
|
+
|
|
22
|
+
// SQLite returns all integers as JS numbers; int8 is a string in node-postgres
|
|
23
|
+
// by default and COUNT(*) / BIGINT columns must stay numbers.
|
|
24
|
+
pg.types.setTypeParser(20, (value) => Number(value));
|
|
25
|
+
pg.types.setTypeParser(1700, (value) => Number(value));
|
|
26
|
+
|
|
27
|
+
function normalize(params) {
|
|
28
|
+
return params.map((value) =>
|
|
29
|
+
value === undefined ? null : typeof value === "boolean" ? (value ? 1 : 0) : value);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function serialize(error) {
|
|
33
|
+
return {
|
|
34
|
+
name: error?.name,
|
|
35
|
+
message: error?.message ?? String(error),
|
|
36
|
+
code: error?.code,
|
|
37
|
+
detail: error?.detail,
|
|
38
|
+
hint: error?.hint,
|
|
39
|
+
severity: error?.severity,
|
|
40
|
+
position: error?.position,
|
|
41
|
+
constraint: error?.constraint,
|
|
42
|
+
table: error?.table,
|
|
43
|
+
column: error?.column,
|
|
44
|
+
dataType: error?.dataType,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function signalReady() {
|
|
49
|
+
Atomics.store(readyFlag, 0, 1);
|
|
50
|
+
Atomics.notify(readyFlag, 0);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function reply(request, payload) {
|
|
54
|
+
port.postMessage({ id: request.id, ...payload });
|
|
55
|
+
const flag = new Int32Array(request.signal);
|
|
56
|
+
Atomics.store(flag, 0, 1);
|
|
57
|
+
Atomics.notify(flag, 0);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function handle(request) {
|
|
61
|
+
try {
|
|
62
|
+
const text = translate(request.sql);
|
|
63
|
+
if (!hasSql(text)) return reply(request, { ok: true, rows: [], row: null, changes: 0 });
|
|
64
|
+
const params = normalize(request.params ?? []);
|
|
65
|
+
// exec without params uses the simple-query protocol so multi-statement
|
|
66
|
+
// schema scripts (and BEGIN/COMMIT) run in one round trip.
|
|
67
|
+
const result = request.mode === "exec" && params.length === 0
|
|
68
|
+
? await client.query(text)
|
|
69
|
+
: await client.query({ text, values: params });
|
|
70
|
+
if (request.mode === "get") return reply(request, { ok: true, row: result.rows?.[0] ?? null });
|
|
71
|
+
if (request.mode === "all") return reply(request, { ok: true, rows: result.rows ?? [] });
|
|
72
|
+
const last = Array.isArray(result) ? result[result.length - 1] : result;
|
|
73
|
+
// Identity columns are never read through Database.run in the state layer;
|
|
74
|
+
// keep the API shape without pretending to know an insert id.
|
|
75
|
+
return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return reply(request, { ok: false, error: serialize(error) });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function drain() {
|
|
82
|
+
draining = true;
|
|
83
|
+
while (queue.length && !closing) await handle(queue.shift());
|
|
84
|
+
draining = false;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function shutdown(signal) {
|
|
88
|
+
closing = true;
|
|
89
|
+
try { await client.end(); } catch { /* connection already gone */ }
|
|
90
|
+
try { port.close(); } catch { /* already closed */ }
|
|
91
|
+
if (signal) {
|
|
92
|
+
const flag = new Int32Array(signal);
|
|
93
|
+
Atomics.store(flag, 0, 1);
|
|
94
|
+
Atomics.notify(flag, 0);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function handlePortMessage(message) {
|
|
99
|
+
if (message?.type === "close") {
|
|
100
|
+
void shutdown(message.signal);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
queue.push(message);
|
|
104
|
+
if (connected && !draining) void drain();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function startup(connectionString, ready, timeout) {
|
|
108
|
+
readyFlag = new Int32Array(ready);
|
|
109
|
+
statementTimeout = timeout;
|
|
110
|
+
try {
|
|
111
|
+
client = new pg.Client({
|
|
112
|
+
connectionString,
|
|
113
|
+
application_name: "chat-room-channeld",
|
|
114
|
+
statement_timeout: statementTimeout,
|
|
115
|
+
});
|
|
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
|
+
}
|
|
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
|
+
});
|
|
@@ -13,6 +13,58 @@ export type MessageRef = {
|
|
|
13
13
|
|
|
14
14
|
export type ActorKey = { platform: string; identityNamespace: string; nativeUserId: string };
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* One attachment carried by an event. Outbound chatroom forwards name a
|
|
18
|
+
* `resourceId` the host resolves at send time; inbound adapter events supply a
|
|
19
|
+
* local `path` the host imports into the room.
|
|
20
|
+
*/
|
|
21
|
+
export type AttachmentRef = {
|
|
22
|
+
kind: "image" | "file";
|
|
23
|
+
name: string;
|
|
24
|
+
mimeType?: string;
|
|
25
|
+
size?: number;
|
|
26
|
+
resourceId?: string;
|
|
27
|
+
roomId?: string;
|
|
28
|
+
path?: string;
|
|
29
|
+
sourceId?: string;
|
|
30
|
+
error?: string;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type AttachmentCapabilities = {
|
|
34
|
+
kinds: Array<"image" | "file">;
|
|
35
|
+
imageMaxBytes?: number;
|
|
36
|
+
fileMaxBytes?: number;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* One account setting declared by an adapter. `key` is the env variable the
|
|
41
|
+
* adapter process reads; the UI renders the field and stores its value there.
|
|
42
|
+
*/
|
|
43
|
+
export type AccountField = {
|
|
44
|
+
key: string;
|
|
45
|
+
label?: string;
|
|
46
|
+
type?: "string" | "secret" | "boolean" | "number" | "select";
|
|
47
|
+
required?: boolean;
|
|
48
|
+
default?: string;
|
|
49
|
+
description?: string;
|
|
50
|
+
options?: Array<{ value: string; label?: string }>;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export type AccountCapabilities = {
|
|
54
|
+
/** Primary form fields, in display order. */
|
|
55
|
+
schema?: AccountField[];
|
|
56
|
+
/** Advanced env declarations; keys not covered here stay free-form. */
|
|
57
|
+
env?: AccountField[];
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** Adapter-declared platform facts the generic host must not hardcode. */
|
|
61
|
+
export type AdapterCapabilities = {
|
|
62
|
+
displayName?: string;
|
|
63
|
+
attachments?: AttachmentCapabilities;
|
|
64
|
+
account?: AccountCapabilities;
|
|
65
|
+
send?: { idempotency?: string };
|
|
66
|
+
};
|
|
67
|
+
|
|
16
68
|
export interface IngestEvent {
|
|
17
69
|
schemaVersion: number;
|
|
18
70
|
eventId: string;
|
|
@@ -25,7 +77,7 @@ export interface IngestEvent {
|
|
|
25
77
|
parent?: MessageRef;
|
|
26
78
|
occurredAt?: string;
|
|
27
79
|
receivedAt: string;
|
|
28
|
-
content?: { text?: string; attachmentRefs?: string[] };
|
|
80
|
+
content?: { text?: string; attachmentRefs?: string[]; attachments?: AttachmentRef[] };
|
|
29
81
|
selectedMessage?: MessageRef;
|
|
30
82
|
requestedTarget?: Endpoint;
|
|
31
83
|
cause?: { rootEventId: string; visitedEndpoints: Endpoint[]; hopCount: number };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ConfigError, type ChannelConfig, type RuleConfig, type RuleTarget } from "./config.ts";
|
|
2
|
-
import type { Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
|
|
2
|
+
import type { AttachmentRef, Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
|
|
3
3
|
|
|
4
4
|
const QUOTE_PREVIEW_LIMIT = 280;
|
|
5
5
|
export const UNSUPPORTED_NOTICE = "attachment/format unsupported";
|
|
@@ -10,6 +10,7 @@ export type DeliveryPayload = {
|
|
|
10
10
|
text: string;
|
|
11
11
|
degraded?: "empty" | "unthreaded";
|
|
12
12
|
parent?: MessageRef;
|
|
13
|
+
attachments?: AttachmentRef[];
|
|
13
14
|
};
|
|
14
15
|
|
|
15
16
|
export type PayloadPlan = { payload: DeliveryPayload } | { dropped: string };
|
|
@@ -107,13 +108,17 @@ export function planPayload(rule: RuleConfig, event: IngestEvent, target: Endpoi
|
|
|
107
108
|
});
|
|
108
109
|
|
|
109
110
|
let payload: DeliveryPayload;
|
|
110
|
-
if (rendered.degraded === "empty") {
|
|
111
|
+
if (rendered.degraded === "empty" && !event.content?.attachments?.length) {
|
|
111
112
|
if (rule.onUnsupported === "drop") return { dropped: "rendered text is empty" };
|
|
112
113
|
payload = { text: UNSUPPORTED_NOTICE, degraded: "empty" };
|
|
113
114
|
} else {
|
|
114
115
|
payload = { text: rendered.text };
|
|
115
116
|
}
|
|
116
117
|
|
|
118
|
+
// Attachments are opaque to rule rendering: the host resolves chatroom
|
|
119
|
+
// resource ids to local files right before the adapter sends.
|
|
120
|
+
if (event.content?.attachments?.length) payload.attachments = event.content.attachments;
|
|
121
|
+
|
|
117
122
|
if (event.parent) {
|
|
118
123
|
if (sameEndpoint(event.parent.endpoint, target)) {
|
|
119
124
|
payload.parent = event.parent;
|
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { DatabaseSync } from "node:sqlite";
|
|
3
2
|
import type { RuleConfig, RuleTarget } from "./config.ts";
|
|
3
|
+
import { PgDatabase } from "./pg/database.ts";
|
|
4
|
+
import { initializeChannelSchema } from "./pg/schema.ts";
|
|
5
|
+
import { Database, type StateDatabase } from "./pg/sqlite.ts";
|
|
4
6
|
import type { IngestEvent } from "./protocol.ts";
|
|
5
7
|
import { buildPublishedResult, PUBLISHED_RESULT_PREFIX, type PublishedResultEvent } from "./published.ts";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
+
import { accountKey } from "./stats.ts";
|
|
9
|
+
|
|
10
|
+
export {
|
|
11
|
+
readChannelStats,
|
|
12
|
+
readChannelStatsFromPostgres,
|
|
13
|
+
type ChannelAccountStats,
|
|
14
|
+
type ChannelStats,
|
|
15
|
+
} from "./stats.ts";
|
|
8
16
|
export type { PublishedResultEvent } from "./published.ts";
|
|
9
17
|
|
|
10
18
|
export const DELIVERY_STATES = [
|
|
@@ -106,7 +114,7 @@ export interface ChannelState {
|
|
|
106
114
|
pauseAccountDeliveries(accountKey: string, reason: string): number;
|
|
107
115
|
abandonUnconfiguredDeliveries(configuredAccountKeys: string[]): DeliveryRow[];
|
|
108
116
|
resumePausedDeliveries(): number;
|
|
109
|
-
recoverInFlightDeliveries(): number;
|
|
117
|
+
recoverInFlightDeliveries(idempotentAccountKeys: string[]): number;
|
|
110
118
|
recordReceipt(input: ReceiptInput): string;
|
|
111
119
|
recordPublishedResult(delivery: DeliveryRow, receipt?: ReceiptRow): void;
|
|
112
120
|
getPublishedResult(deliveryId: string): PublishedResultEvent | undefined;
|
|
@@ -124,62 +132,13 @@ export interface ChannelState {
|
|
|
124
132
|
|
|
125
133
|
type RawRow = Record<string, unknown>;
|
|
126
134
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
);
|
|
135
|
-
CREATE TABLE IF NOT EXISTS channel_deliveries (
|
|
136
|
-
delivery_id TEXT PRIMARY KEY,
|
|
137
|
-
event_id TEXT NOT NULL,
|
|
138
|
-
rule_id TEXT NOT NULL,
|
|
139
|
-
rule_version INTEGER NOT NULL,
|
|
140
|
-
target TEXT NOT NULL,
|
|
141
|
-
idempotency_key TEXT NOT NULL UNIQUE,
|
|
142
|
-
payload TEXT NOT NULL,
|
|
143
|
-
state TEXT NOT NULL,
|
|
144
|
-
attempt_count INTEGER NOT NULL DEFAULT 0,
|
|
145
|
-
next_attempt_at INTEGER,
|
|
146
|
-
last_error TEXT,
|
|
147
|
-
provider_message TEXT,
|
|
148
|
-
created_at INTEGER NOT NULL,
|
|
149
|
-
updated_at INTEGER NOT NULL
|
|
150
|
-
);
|
|
151
|
-
CREATE TABLE IF NOT EXISTS channel_receipts (
|
|
152
|
-
receipt_id TEXT PRIMARY KEY,
|
|
153
|
-
delivery_id TEXT NOT NULL,
|
|
154
|
-
attempt_id TEXT NOT NULL,
|
|
155
|
-
state TEXT NOT NULL,
|
|
156
|
-
provider_message TEXT,
|
|
157
|
-
detail TEXT,
|
|
158
|
-
observed_at INTEGER NOT NULL
|
|
159
|
-
);
|
|
160
|
-
CREATE TABLE IF NOT EXISTS channel_echoes (
|
|
161
|
-
endpoint TEXT NOT NULL,
|
|
162
|
-
native_message_id TEXT NOT NULL,
|
|
163
|
-
logical_message_id TEXT NOT NULL,
|
|
164
|
-
delivery_id TEXT,
|
|
165
|
-
PRIMARY KEY (endpoint, native_message_id)
|
|
166
|
-
);
|
|
167
|
-
`;
|
|
168
|
-
|
|
169
|
-
function transaction<T>(db: DatabaseSync, fn: () => T): T {
|
|
170
|
-
db.exec("BEGIN IMMEDIATE");
|
|
171
|
-
try {
|
|
172
|
-
const value = fn();
|
|
173
|
-
db.exec("COMMIT");
|
|
174
|
-
return value;
|
|
175
|
-
} catch (error) {
|
|
176
|
-
try {
|
|
177
|
-
db.exec("ROLLBACK");
|
|
178
|
-
} catch {
|
|
179
|
-
// Keep the original failure.
|
|
180
|
-
}
|
|
181
|
-
throw error;
|
|
182
|
-
}
|
|
135
|
+
function transaction<T>(db: StateDatabase, fn: () => T): T {
|
|
136
|
+
return db.transaction(fn).immediate();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Escape LIKE wildcards so an account key matches as a literal prefix.
|
|
140
|
+
function likePrefix(value: string): string {
|
|
141
|
+
return `${value.replace(/[\\%_]/g, (ch) => `\\${ch}`)}%`;
|
|
183
142
|
}
|
|
184
143
|
|
|
185
144
|
function toDelivery(row: RawRow): DeliveryRow {
|
|
@@ -214,8 +173,13 @@ function toReceipt(row: RawRow): ReceiptRow {
|
|
|
214
173
|
}
|
|
215
174
|
|
|
216
175
|
export function openState(path: string): ChannelState {
|
|
217
|
-
const
|
|
218
|
-
|
|
176
|
+
const url = process.env.CHAT_ROOM_DATABASE_URL?.trim();
|
|
177
|
+
return createChannelState(url ? new PgDatabase(url) : new Database(path));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Build a state store over an already-opened backend (used by Postgres tests). */
|
|
181
|
+
export function createChannelState(db: StateDatabase): ChannelState {
|
|
182
|
+
initializeChannelSchema(db, { backfillEchoOrder: db instanceof Database });
|
|
219
183
|
let closed = false;
|
|
220
184
|
|
|
221
185
|
function getDelivery(deliveryId: string): DeliveryRow | undefined {
|
|
@@ -286,12 +250,12 @@ export function openState(path: string): ChannelState {
|
|
|
286
250
|
const prefix = `${accountKey.replace(/\/+$/, "")}/`;
|
|
287
251
|
const row = db.prepare(
|
|
288
252
|
`SELECT * FROM channel_deliveries
|
|
289
|
-
WHERE
|
|
253
|
+
WHERE target LIKE ? ESCAPE '\\'
|
|
290
254
|
AND state IN ('pending', 'retryable', 'rate_limited')
|
|
291
255
|
AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
|
|
292
256
|
ORDER BY created_at ASC, delivery_id ASC
|
|
293
257
|
LIMIT 1`,
|
|
294
|
-
).get(prefix,
|
|
258
|
+
).get(likePrefix(prefix), now) as RawRow | undefined;
|
|
295
259
|
return row ? toDelivery(row) : undefined;
|
|
296
260
|
},
|
|
297
261
|
|
|
@@ -320,6 +284,7 @@ export function openState(path: string): ChannelState {
|
|
|
320
284
|
|
|
321
285
|
recordSent(input) {
|
|
322
286
|
const receiptId = `rcp-${randomUUID()}`;
|
|
287
|
+
const observedAt = input.observedAt ?? Date.now();
|
|
323
288
|
transaction(db, () => {
|
|
324
289
|
db.prepare(
|
|
325
290
|
`INSERT INTO channel_receipts
|
|
@@ -331,18 +296,19 @@ export function openState(path: string): ChannelState {
|
|
|
331
296
|
input.attemptId,
|
|
332
297
|
input.providerMessage,
|
|
333
298
|
input.detail ?? null,
|
|
334
|
-
|
|
299
|
+
observedAt,
|
|
335
300
|
);
|
|
336
301
|
if (input.echo) {
|
|
337
302
|
db.prepare(
|
|
338
303
|
`INSERT OR IGNORE INTO channel_echoes
|
|
339
|
-
(endpoint, native_message_id, logical_message_id, delivery_id)
|
|
340
|
-
VALUES (?, ?, ?, ?)`,
|
|
304
|
+
(endpoint, native_message_id, logical_message_id, delivery_id, created_at)
|
|
305
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
341
306
|
).run(
|
|
342
307
|
input.echo.endpoint,
|
|
343
308
|
input.echo.nativeMessageId,
|
|
344
309
|
input.echo.logicalMessageId,
|
|
345
310
|
input.deliveryId,
|
|
311
|
+
observedAt,
|
|
346
312
|
);
|
|
347
313
|
}
|
|
348
314
|
});
|
|
@@ -354,36 +320,34 @@ export function openState(path: string): ChannelState {
|
|
|
354
320
|
const result = db.prepare(
|
|
355
321
|
`UPDATE channel_deliveries
|
|
356
322
|
SET state = 'paused', next_attempt_at = NULL, last_error = ?, updated_at = ?
|
|
357
|
-
WHERE
|
|
323
|
+
WHERE target LIKE ? ESCAPE '\\'
|
|
358
324
|
AND state IN ('pending', 'retryable', 'rate_limited')`,
|
|
359
|
-
).run(reason, Date.now(), prefix
|
|
325
|
+
).run(reason, Date.now(), likePrefix(prefix));
|
|
360
326
|
return Number(result.changes);
|
|
361
327
|
},
|
|
362
328
|
|
|
363
329
|
abandonUnconfiguredDeliveries(configuredAccountKeys) {
|
|
364
|
-
const configured =
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
ELSE target END`;
|
|
369
|
-
const filter = configured.length > 0
|
|
370
|
-
? `AND (${accountKeySql}) NOT IN (${configured.map(() => "?").join(", ")})`
|
|
371
|
-
: "";
|
|
372
|
-
const rows = db.prepare(
|
|
330
|
+
const configured = new Set(configuredAccountKeys);
|
|
331
|
+
// Account keys are the first two target segments; filter in JS so the
|
|
332
|
+
// same SQL runs on SQLite and PostgreSQL.
|
|
333
|
+
const rows = (db.prepare(
|
|
373
334
|
`SELECT * FROM channel_deliveries
|
|
374
335
|
WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
|
|
375
|
-
${filter}
|
|
376
336
|
ORDER BY created_at ASC, delivery_id ASC`,
|
|
377
|
-
).all(
|
|
337
|
+
).all() as RawRow[]).filter((row) => !configured.has(accountKey(String(row.target))));
|
|
378
338
|
if (rows.length === 0) return [];
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
${filter}`,
|
|
385
|
-
).run("account is not configured; add it back to retry", Date.now(), ...configured)
|
|
339
|
+
const update = db.prepare(
|
|
340
|
+
`UPDATE channel_deliveries
|
|
341
|
+
SET state = 'unknown', next_attempt_at = NULL, last_error = ?, updated_at = ?
|
|
342
|
+
WHERE delivery_id = ?
|
|
343
|
+
AND state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')`,
|
|
386
344
|
);
|
|
345
|
+
transaction(db, () => {
|
|
346
|
+
const now = Date.now();
|
|
347
|
+
for (const row of rows) {
|
|
348
|
+
update.run("account is not configured; add it back to retry", now, String(row.delivery_id));
|
|
349
|
+
}
|
|
350
|
+
});
|
|
387
351
|
return rows.map((row) => ({ ...toDelivery(row), state: "unknown" as const }));
|
|
388
352
|
},
|
|
389
353
|
|
|
@@ -396,14 +360,26 @@ export function openState(path: string): ChannelState {
|
|
|
396
360
|
return Number(result.changes);
|
|
397
361
|
},
|
|
398
362
|
|
|
399
|
-
recoverInFlightDeliveries() {
|
|
400
|
-
const
|
|
363
|
+
recoverInFlightDeliveries(idempotentAccountKeys: string[]): number {
|
|
364
|
+
const idempotent = new Set(idempotentAccountKeys);
|
|
365
|
+
const rows = db.prepare(
|
|
366
|
+
"SELECT delivery_id, target FROM channel_deliveries WHERE state = 'in_flight'",
|
|
367
|
+
).all() as RawRow[];
|
|
368
|
+
if (!rows.length) return 0;
|
|
369
|
+
const now = Date.now();
|
|
370
|
+
const update = db.prepare(
|
|
401
371
|
`UPDATE channel_deliveries
|
|
402
|
-
SET state =
|
|
372
|
+
SET state = ?, next_attempt_at = NULL,
|
|
403
373
|
last_error = 'recovered stale in_flight after restart', updated_at = ?
|
|
404
|
-
WHERE state = 'in_flight'`,
|
|
405
|
-
)
|
|
406
|
-
|
|
374
|
+
WHERE delivery_id = ? AND state = 'in_flight'`,
|
|
375
|
+
);
|
|
376
|
+
transaction(db, () => {
|
|
377
|
+
for (const row of rows) {
|
|
378
|
+
const state = idempotent.has(accountKey(String(row.target))) ? "pending" : "unknown";
|
|
379
|
+
update.run(state, now, String(row.delivery_id));
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
return rows.length;
|
|
407
383
|
},
|
|
408
384
|
|
|
409
385
|
recordReceipt(input) {
|
|
@@ -443,9 +419,9 @@ export function openState(path: string): ChannelState {
|
|
|
443
419
|
recordEcho(endpoint, nativeMessageId, logicalMessageId, deliveryId) {
|
|
444
420
|
db.prepare(
|
|
445
421
|
`INSERT OR IGNORE INTO channel_echoes
|
|
446
|
-
(endpoint, native_message_id, logical_message_id, delivery_id)
|
|
447
|
-
VALUES (?, ?, ?, ?)`,
|
|
448
|
-
).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null);
|
|
422
|
+
(endpoint, native_message_id, logical_message_id, delivery_id, created_at)
|
|
423
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
424
|
+
).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null, Date.now());
|
|
449
425
|
},
|
|
450
426
|
|
|
451
427
|
findEcho(endpoint, nativeMessageId) {
|
|
@@ -459,7 +435,7 @@ export function openState(path: string): ChannelState {
|
|
|
459
435
|
const row = db.prepare(
|
|
460
436
|
`SELECT native_message_id FROM channel_echoes
|
|
461
437
|
WHERE endpoint = ? AND logical_message_id = ? AND delivery_id IS NOT NULL
|
|
462
|
-
ORDER BY
|
|
438
|
+
ORDER BY created_at DESC LIMIT 1`,
|
|
463
439
|
).get(endpoint, logicalMessageId) as RawRow | undefined;
|
|
464
440
|
return row ? String(row.native_message_id) : undefined;
|
|
465
441
|
},
|