@20baht/live 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +142 -2
- package/dist/browser.d.ts +164 -0
- package/dist/browser.js +404 -0
- package/dist/elysia.d.ts +332 -0
- package/dist/elysia.js +131 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/live.d.ts +81 -0
- package/dist/live.js +393 -0
- package/dist/pg.d.ts +81 -0
- package/dist/pg.js +214 -0
- package/dist/protocol.d.ts +112 -0
- package/dist/protocol.js +122 -0
- package/dist/source.d.ts +17 -0
- package/dist/source.js +24 -0
- package/dist/topics.d.ts +10 -0
- package/dist/topics.js +25 -0
- package/package.json +86 -4
package/dist/live.js
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import { diffRows, encodeFrame, MAX_SUBSCRIPTIONS, parseSubscriptions, requestKey, rowsOf, versionOf, } from './protocol.js';
|
|
2
|
+
import { cleanTopics } from './topics.js';
|
|
3
|
+
const encoder = new TextEncoder();
|
|
4
|
+
const SSE_HEADERS = {
|
|
5
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
6
|
+
'cache-control': 'no-cache, no-transform',
|
|
7
|
+
'x-accel-buffering': 'no',
|
|
8
|
+
};
|
|
9
|
+
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
10
|
+
export function createLive(options) {
|
|
11
|
+
const { source } = options;
|
|
12
|
+
const forward = (options.forward ?? ['cookie', 'authorization']).map((name) => name.toLowerCase());
|
|
13
|
+
const settleMs = options.settleMs ?? 100;
|
|
14
|
+
const concurrency = Math.max(1, options.concurrency ?? 8);
|
|
15
|
+
const recheckMs = options.recheckMs ?? 300_000;
|
|
16
|
+
const heartbeatMs = options.heartbeatMs ?? 15_000;
|
|
17
|
+
const maxSubscriptions = options.maxSubscriptions ?? MAX_SUBSCRIPTIONS;
|
|
18
|
+
const streams = new Set();
|
|
19
|
+
const entries = new Map();
|
|
20
|
+
const byTopic = new Map();
|
|
21
|
+
const dirty = new Set();
|
|
22
|
+
const queue = new Set();
|
|
23
|
+
let settle;
|
|
24
|
+
let running = 0;
|
|
25
|
+
const index = (entry, topics) => {
|
|
26
|
+
for (const topic of entry.topics)
|
|
27
|
+
byTopic.get(topic)?.delete(entry);
|
|
28
|
+
entry.topics = topics;
|
|
29
|
+
for (const topic of topics) {
|
|
30
|
+
const set = byTopic.get(topic) ?? new Set();
|
|
31
|
+
set.add(entry);
|
|
32
|
+
byTopic.set(topic, set);
|
|
33
|
+
}
|
|
34
|
+
for (const [topic, set] of byTopic)
|
|
35
|
+
if (set.size === 0)
|
|
36
|
+
byTopic.delete(topic);
|
|
37
|
+
};
|
|
38
|
+
const drop = (entry) => {
|
|
39
|
+
if (entries.get(entry.key) === entry)
|
|
40
|
+
entries.delete(entry.key);
|
|
41
|
+
index(entry, []);
|
|
42
|
+
dirty.delete(entry);
|
|
43
|
+
queue.delete(entry);
|
|
44
|
+
};
|
|
45
|
+
const leave = (sub) => {
|
|
46
|
+
sub.entry.subs.delete(sub);
|
|
47
|
+
sub.stream.subs.delete(sub);
|
|
48
|
+
if (sub.entry.subs.size === 0)
|
|
49
|
+
drop(sub.entry);
|
|
50
|
+
};
|
|
51
|
+
const flush = () => {
|
|
52
|
+
settle = undefined;
|
|
53
|
+
for (const entry of dirty)
|
|
54
|
+
schedule(entry);
|
|
55
|
+
dirty.clear();
|
|
56
|
+
};
|
|
57
|
+
const touched = (entry) => {
|
|
58
|
+
dirty.add(entry);
|
|
59
|
+
settle ??= setTimeout(flush, settleMs);
|
|
60
|
+
};
|
|
61
|
+
const schedule = (entry) => {
|
|
62
|
+
if (entry.running) {
|
|
63
|
+
entry.again = true;
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
queue.add(entry);
|
|
67
|
+
pump();
|
|
68
|
+
};
|
|
69
|
+
const pump = () => {
|
|
70
|
+
for (const entry of queue) {
|
|
71
|
+
if (running >= concurrency)
|
|
72
|
+
return;
|
|
73
|
+
queue.delete(entry);
|
|
74
|
+
void start(entry);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const start = async (entry) => {
|
|
78
|
+
const owner = [...entry.subs][0]?.stream;
|
|
79
|
+
if (owner === undefined)
|
|
80
|
+
return;
|
|
81
|
+
entry.running = true;
|
|
82
|
+
running += 1;
|
|
83
|
+
let result;
|
|
84
|
+
try {
|
|
85
|
+
result = await entry.runner.run(entry.request, owner.headers, owner.caller);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
result = {
|
|
89
|
+
status: 500,
|
|
90
|
+
body: { message: error instanceof Error ? error.message : 'failed' },
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
running -= 1;
|
|
94
|
+
entry.running = false;
|
|
95
|
+
settleRun(entry, owner, result);
|
|
96
|
+
if (entry.again && entry.subs.size > 0) {
|
|
97
|
+
entry.again = false;
|
|
98
|
+
schedule(entry);
|
|
99
|
+
}
|
|
100
|
+
pump();
|
|
101
|
+
};
|
|
102
|
+
const settleRun = (entry, owner, result) => {
|
|
103
|
+
if (entry.subs.size === 0)
|
|
104
|
+
return;
|
|
105
|
+
if (result.status === 401 || result.status === 403)
|
|
106
|
+
refused(entry, owner, result);
|
|
107
|
+
else if (result.status < 200 || result.status >= 300)
|
|
108
|
+
failed(entry, result);
|
|
109
|
+
else {
|
|
110
|
+
const live = result.live ?? { topics: [] };
|
|
111
|
+
index(entry, cleanTopics(live.topics));
|
|
112
|
+
publish(entry, answerOf(result.body, live));
|
|
113
|
+
if (live.share !== undefined)
|
|
114
|
+
reshare(entry, `${requestKey(entry.request)}|s:${live.share}`);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
const refused = (entry, owner, result) => {
|
|
118
|
+
for (const sub of [...entry.subs]) {
|
|
119
|
+
if (sub.stream !== owner)
|
|
120
|
+
continue;
|
|
121
|
+
if (result.status === 401)
|
|
122
|
+
owner.end('unauthorized');
|
|
123
|
+
else {
|
|
124
|
+
owner.write(errorFrame(sub.id, result));
|
|
125
|
+
leave(sub);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (entry.subs.size > 0)
|
|
129
|
+
entry.again = true;
|
|
130
|
+
};
|
|
131
|
+
const failed = (entry, result) => {
|
|
132
|
+
if (result.live !== undefined)
|
|
133
|
+
index(entry, cleanTopics(result.live.topics));
|
|
134
|
+
for (const sub of entry.subs) {
|
|
135
|
+
sub.answered = true;
|
|
136
|
+
sub.stream.write(errorFrame(sub.id, result));
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const answerOf = (body, live) => {
|
|
140
|
+
const version = versionOf(body);
|
|
141
|
+
if (live.key === undefined)
|
|
142
|
+
return { version, body };
|
|
143
|
+
const at = { key: live.key, rows: live.rows };
|
|
144
|
+
const found = rowsOf(body, at);
|
|
145
|
+
return found === null ? { version, body } : { version, body, keyed: { at, rows: found.rows } };
|
|
146
|
+
};
|
|
147
|
+
const publish = (entry, next) => {
|
|
148
|
+
const previous = entry.answer;
|
|
149
|
+
entry.answer = next;
|
|
150
|
+
let patch;
|
|
151
|
+
for (const sub of entry.subs) {
|
|
152
|
+
const held = sub.held;
|
|
153
|
+
sub.held = next.version;
|
|
154
|
+
if (held === next.version) {
|
|
155
|
+
if (!sub.answered)
|
|
156
|
+
sub.stream.write(unchanged(sub.id, next.version));
|
|
157
|
+
}
|
|
158
|
+
else if (sub.answered &&
|
|
159
|
+
previous !== undefined &&
|
|
160
|
+
held === previous.version &&
|
|
161
|
+
patchable(previous, next)) {
|
|
162
|
+
patch ??= patchFrame(previous.keyed.rows, next);
|
|
163
|
+
sub.stream.write({ ...patch, data: { ...patch.data, id: sub.id } });
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
sub.stream.write(snapshot(sub.id, next));
|
|
167
|
+
}
|
|
168
|
+
sub.answered = true;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
const reshare = (entry, key) => {
|
|
172
|
+
if (entry.key === key)
|
|
173
|
+
return;
|
|
174
|
+
const target = entries.get(key);
|
|
175
|
+
if (target === undefined) {
|
|
176
|
+
entries.delete(entry.key);
|
|
177
|
+
entry.key = key;
|
|
178
|
+
entries.set(key, entry);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
for (const sub of entry.subs) {
|
|
182
|
+
sub.entry = target;
|
|
183
|
+
target.subs.add(sub);
|
|
184
|
+
}
|
|
185
|
+
entry.subs.clear();
|
|
186
|
+
drop(entry);
|
|
187
|
+
};
|
|
188
|
+
const join = (stream, sub, held, runner, shareBase) => {
|
|
189
|
+
const request = {
|
|
190
|
+
method: sub.method,
|
|
191
|
+
path: sub.path,
|
|
192
|
+
...(sub.query === undefined ? {} : { query: sub.query }),
|
|
193
|
+
...(sub.body === undefined ? {} : { body: sub.body }),
|
|
194
|
+
};
|
|
195
|
+
if (!runner.isLive(request)) {
|
|
196
|
+
stream.write({
|
|
197
|
+
event: 'error',
|
|
198
|
+
data: {
|
|
199
|
+
id: sub.id,
|
|
200
|
+
status: 404,
|
|
201
|
+
body: { code: 'NOT_LIVE', message: `${sub.method} ${sub.path} is not a live route` },
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const key = `${requestKey(request)}|${shareBase}`;
|
|
207
|
+
let entry = entries.get(key);
|
|
208
|
+
const fresh = entry === undefined;
|
|
209
|
+
entry ??= {
|
|
210
|
+
key,
|
|
211
|
+
request,
|
|
212
|
+
runner,
|
|
213
|
+
subs: new Set(),
|
|
214
|
+
topics: [],
|
|
215
|
+
answer: undefined,
|
|
216
|
+
running: false,
|
|
217
|
+
again: false,
|
|
218
|
+
};
|
|
219
|
+
entries.set(key, entry);
|
|
220
|
+
const member = { id: sub.id, stream, entry, held, answered: false };
|
|
221
|
+
entry.subs.add(member);
|
|
222
|
+
stream.subs.add(member);
|
|
223
|
+
const answer = entry.answer;
|
|
224
|
+
if (fresh)
|
|
225
|
+
schedule(entry);
|
|
226
|
+
else if (answer !== undefined) {
|
|
227
|
+
stream.write(held === answer.version ? unchanged(sub.id, answer.version) : snapshot(sub.id, answer));
|
|
228
|
+
member.held = answer.version;
|
|
229
|
+
member.answered = true;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
const open = async (request, body, runner) => {
|
|
233
|
+
let caller = null;
|
|
234
|
+
if (options.caller !== undefined) {
|
|
235
|
+
try {
|
|
236
|
+
caller = await options.caller(request.headers);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
return json(503, {
|
|
240
|
+
code: 'CALLER_UNAVAILABLE',
|
|
241
|
+
message: 'Could not say who the caller is',
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
if (caller === null)
|
|
245
|
+
return json(401, { code: 'UNAUTHENTICATED', message: 'Sign in first' });
|
|
246
|
+
}
|
|
247
|
+
const parsed = parseSubscriptions(body, maxSubscriptions);
|
|
248
|
+
if (!parsed.ok)
|
|
249
|
+
return json(400, { code: 'BAD_SUBSCRIPTIONS', message: parsed.message });
|
|
250
|
+
const headers = new Headers();
|
|
251
|
+
for (const name of forward) {
|
|
252
|
+
const value = request.headers.get(name);
|
|
253
|
+
if (value !== null)
|
|
254
|
+
headers.set(name, value);
|
|
255
|
+
}
|
|
256
|
+
const shareBase = caller === null ? `h:${versionOf([...headers.entries()])}` : `c:${caller.id}`;
|
|
257
|
+
let stop = () => undefined;
|
|
258
|
+
const bodyStream = new ReadableStream({
|
|
259
|
+
start(controller) {
|
|
260
|
+
let open = true;
|
|
261
|
+
const raw = (text) => {
|
|
262
|
+
if (!open)
|
|
263
|
+
return;
|
|
264
|
+
try {
|
|
265
|
+
controller.enqueue(encoder.encode(text));
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
stop();
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
const stream = {
|
|
272
|
+
caller,
|
|
273
|
+
headers,
|
|
274
|
+
subs: new Set(),
|
|
275
|
+
write: (frame) => {
|
|
276
|
+
raw(encodeFrame(frame));
|
|
277
|
+
},
|
|
278
|
+
end: (reason) => {
|
|
279
|
+
stop(reason);
|
|
280
|
+
},
|
|
281
|
+
};
|
|
282
|
+
const heartbeat = setInterval(() => {
|
|
283
|
+
raw(': ping\n\n');
|
|
284
|
+
}, heartbeatMs);
|
|
285
|
+
const recheck = options.caller === undefined || caller === null
|
|
286
|
+
? undefined
|
|
287
|
+
: setInterval(() => {
|
|
288
|
+
void options.caller?.(request.headers).then((now) => {
|
|
289
|
+
if (now === null)
|
|
290
|
+
stop('signed-out');
|
|
291
|
+
else if (now.id !== caller.id)
|
|
292
|
+
stop('caller-changed');
|
|
293
|
+
}, () => undefined);
|
|
294
|
+
}, recheckMs);
|
|
295
|
+
stop = (reason) => {
|
|
296
|
+
if (!open)
|
|
297
|
+
return;
|
|
298
|
+
if (reason !== undefined)
|
|
299
|
+
raw(encodeFrame({ event: 'end', data: { reason } }));
|
|
300
|
+
open = false;
|
|
301
|
+
clearInterval(heartbeat);
|
|
302
|
+
clearInterval(recheck);
|
|
303
|
+
request.signal.removeEventListener('abort', onAbort);
|
|
304
|
+
for (const sub of [...stream.subs])
|
|
305
|
+
leave(sub);
|
|
306
|
+
streams.delete(stream);
|
|
307
|
+
try {
|
|
308
|
+
controller.close();
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
const onAbort = () => {
|
|
314
|
+
stop();
|
|
315
|
+
};
|
|
316
|
+
request.signal.addEventListener('abort', onAbort);
|
|
317
|
+
streams.add(stream);
|
|
318
|
+
raw(': ok\n\n');
|
|
319
|
+
for (const sub of parsed.subscriptions)
|
|
320
|
+
join(stream, sub, sub.version, runner, shareBase);
|
|
321
|
+
},
|
|
322
|
+
cancel() {
|
|
323
|
+
stop();
|
|
324
|
+
},
|
|
325
|
+
});
|
|
326
|
+
return new Response(bodyStream, { headers: SSE_HEADERS });
|
|
327
|
+
};
|
|
328
|
+
const unlisten = source.listen((topics) => {
|
|
329
|
+
for (const topic of topics) {
|
|
330
|
+
if (!topic.endsWith('*')) {
|
|
331
|
+
for (const entry of byTopic.get(topic) ?? [])
|
|
332
|
+
touched(entry);
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
const table = topic.slice(0, -1);
|
|
336
|
+
for (const [name, set] of byTopic) {
|
|
337
|
+
if (name === table || name.startsWith(`${table}:`) || name.startsWith(`${table}@`)) {
|
|
338
|
+
for (const entry of set)
|
|
339
|
+
touched(entry);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}, () => {
|
|
344
|
+
for (const entry of entries.values())
|
|
345
|
+
touched(entry);
|
|
346
|
+
});
|
|
347
|
+
return {
|
|
348
|
+
open,
|
|
349
|
+
emit: (topics) => source.emit(cleanTopics(topics)),
|
|
350
|
+
health: () => ({ source: source.status(), streams: streams.size, runs: entries.size }),
|
|
351
|
+
close: () => {
|
|
352
|
+
for (const stream of [...streams])
|
|
353
|
+
stream.end('shutdown');
|
|
354
|
+
clearTimeout(settle);
|
|
355
|
+
unlisten();
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
const patchable = (previous, next) => {
|
|
360
|
+
const before = previous.keyed?.at;
|
|
361
|
+
const after = next.keyed?.at;
|
|
362
|
+
return before !== undefined && before.key === after?.key && before.rows === after.rows;
|
|
363
|
+
};
|
|
364
|
+
const snapshot = (id, answer) => ({
|
|
365
|
+
event: 'snapshot',
|
|
366
|
+
data: { id, version: answer.version, body: answer.body },
|
|
367
|
+
});
|
|
368
|
+
const unchanged = (id, version) => ({
|
|
369
|
+
event: 'unchanged',
|
|
370
|
+
data: { id, version },
|
|
371
|
+
});
|
|
372
|
+
const errorFrame = (id, result) => ({
|
|
373
|
+
event: 'error',
|
|
374
|
+
data: { id, status: result.status, body: result.body },
|
|
375
|
+
});
|
|
376
|
+
function patchFrame(before, next) {
|
|
377
|
+
const keyed = next.keyed;
|
|
378
|
+
const diff = diffRows(before, keyed.rows, keyed.at.key);
|
|
379
|
+
const rest = keyed.at.rows === undefined ? undefined : rowsOf(next.body, keyed.at)?.rest;
|
|
380
|
+
return {
|
|
381
|
+
event: 'patch',
|
|
382
|
+
data: {
|
|
383
|
+
id: '',
|
|
384
|
+
version: next.version,
|
|
385
|
+
key: keyed.at.key,
|
|
386
|
+
...(keyed.at.rows === undefined ? {} : { rows: keyed.at.rows }),
|
|
387
|
+
upsert: diff.upsert,
|
|
388
|
+
remove: diff.remove,
|
|
389
|
+
...(diff.order === undefined ? {} : { order: diff.order }),
|
|
390
|
+
...(rest === undefined ? {} : { rest }),
|
|
391
|
+
},
|
|
392
|
+
};
|
|
393
|
+
}
|
package/dist/pg.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type SQL } from 'drizzle-orm';
|
|
2
|
+
import { type PgTable } from 'drizzle-orm/pg-core';
|
|
3
|
+
import type { ChangeSource } from './source.js';
|
|
4
|
+
/** The channel triggers and `changed` notify on, unless told another. */
|
|
5
|
+
export declare const DEFAULT_CHANNEL = "live";
|
|
6
|
+
export interface TrackedTable {
|
|
7
|
+
/** A drizzle table, or a table's name. */
|
|
8
|
+
table: PgTable | string;
|
|
9
|
+
/** The table's schema, for a name; a drizzle table says its own. Default `public`. */
|
|
10
|
+
schema?: string | undefined;
|
|
11
|
+
/** The key columns, in order. Default: a drizzle table's primary key; required for a name. */
|
|
12
|
+
key?: readonly (string | {
|
|
13
|
+
name: string;
|
|
14
|
+
})[] | undefined;
|
|
15
|
+
/** Columns whose old and new values become `<table>@<column>=<value>` topics. */
|
|
16
|
+
scope?: readonly (string | {
|
|
17
|
+
name: string;
|
|
18
|
+
})[] | undefined;
|
|
19
|
+
}
|
|
20
|
+
export interface TriggerOptions {
|
|
21
|
+
channel?: string | undefined;
|
|
22
|
+
/** The trigger function's name (created once, shared by every table). Default `live_notify`. */
|
|
23
|
+
functionName?: string | undefined;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The SQL that makes tracked tables notify: one trigger function (shared) and, per table, a row
|
|
27
|
+
* trigger for insert, update and delete and a statement trigger for truncate. Put it in a
|
|
28
|
+
* migration; the library never runs it on its own. Running it again replaces what it made.
|
|
29
|
+
*
|
|
30
|
+
* Every write sends the table's topics: `<table>`, `<table>:<key>` and `<table>@<column>=<value>`
|
|
31
|
+
* for each scope column, old and new values both. A topic longer than 200 characters, a payload
|
|
32
|
+
* past what a notification holds, and a truncate send `<table>*`: everything on the table.
|
|
33
|
+
*/
|
|
34
|
+
export declare function liveTriggers(tables: readonly TrackedTable[], options?: TriggerOptions): string;
|
|
35
|
+
/** The SQL that undoes `liveTriggers` for these tables (the functions stay: others may use them). */
|
|
36
|
+
export declare function dropLiveTriggers(tables: readonly TrackedTable[]): string;
|
|
37
|
+
/** The part of a Postgres client `pgSource` needs: hear a channel, and notify on it. */
|
|
38
|
+
export interface PgListener {
|
|
39
|
+
/**
|
|
40
|
+
* Hear `channel`. `onListen` is called each time the listening connection is (re)made: the
|
|
41
|
+
* first time it is up; after that, notifications may have been missed while it was away.
|
|
42
|
+
* Resolves to how to stop.
|
|
43
|
+
*/
|
|
44
|
+
listen: (channel: string, onPayload: (payload: string) => void, onListen: () => void) => Promise<() => unknown>;
|
|
45
|
+
notify: (channel: string, payload: string) => Promise<unknown>;
|
|
46
|
+
}
|
|
47
|
+
/** postgres.js (`postgres()`): its `listen` keeps its own connection and makes it again. */
|
|
48
|
+
export interface PostgresJsLike {
|
|
49
|
+
listen: (channel: string, onNotify: (payload: string) => void, onListen?: () => void) => Promise<{
|
|
50
|
+
unlisten: () => Promise<unknown>;
|
|
51
|
+
}>;
|
|
52
|
+
notify: (channel: string, payload: string) => Promise<unknown>;
|
|
53
|
+
}
|
|
54
|
+
export declare function postgresJsListener(client: PostgresJsLike): PgListener;
|
|
55
|
+
/** PGlite: one process, so no connection to lose. */
|
|
56
|
+
export interface PGliteLike {
|
|
57
|
+
listen: (channel: string, callback: (payload: string) => void) => Promise<() => Promise<void>>;
|
|
58
|
+
query: (text: string, params: unknown[]) => Promise<unknown>;
|
|
59
|
+
}
|
|
60
|
+
export declare function pgliteListener(pg: PGliteLike): PgListener;
|
|
61
|
+
/**
|
|
62
|
+
* Changes from Postgres: LISTEN on `channel` from boot, through a connection of the listener's
|
|
63
|
+
* own (never one from a pool). A reconnect calls `onReset`: what was notified while it was away is
|
|
64
|
+
* lost, so every subscription runs again.
|
|
65
|
+
*/
|
|
66
|
+
export interface PgSourceOptions {
|
|
67
|
+
channel?: string | undefined;
|
|
68
|
+
log?: ((line: string) => void) | undefined;
|
|
69
|
+
/** The first wait before listening again after a failed attempt, doubling to 30 s. Default 1 s. */
|
|
70
|
+
retryMs?: number | undefined;
|
|
71
|
+
}
|
|
72
|
+
export declare function pgSource(listener: PgListener, options?: PgSourceOptions): ChangeSource;
|
|
73
|
+
/** A drizzle transaction or database: what `changed` writes through. */
|
|
74
|
+
export interface Executor {
|
|
75
|
+
execute: (query: SQL) => Promise<unknown>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Raise `topics` inside the caller's transaction: they are heard when it commits, never if it
|
|
79
|
+
* rolls back. For what a write changes beyond the tracked tables (a computed view, a file).
|
|
80
|
+
*/
|
|
81
|
+
export declare function changed(tx: Executor, topics: readonly string[], channel?: string): Promise<void>;
|
package/dist/pg.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { sql } from 'drizzle-orm';
|
|
2
|
+
import { getTableConfig } from 'drizzle-orm/pg-core';
|
|
3
|
+
import { cleanTopics } from './topics.js';
|
|
4
|
+
export const DEFAULT_CHANNEL = 'live';
|
|
5
|
+
const MAX_PAYLOAD = 7900;
|
|
6
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_$]{0,62}$/;
|
|
7
|
+
function ident(name) {
|
|
8
|
+
if (!IDENT.test(name))
|
|
9
|
+
throw new Error(`live: "${name}" is not a plain SQL identifier`);
|
|
10
|
+
return `"${name}"`;
|
|
11
|
+
}
|
|
12
|
+
function literal(text) {
|
|
13
|
+
return `'${text.replaceAll("'", "''")}'`;
|
|
14
|
+
}
|
|
15
|
+
const nameOf = (column) => typeof column === 'string' ? column : column.name;
|
|
16
|
+
function resolve(tracked, needKey = true) {
|
|
17
|
+
let schema = tracked.schema ?? 'public';
|
|
18
|
+
let name;
|
|
19
|
+
let key = tracked.key?.map(nameOf);
|
|
20
|
+
if (typeof tracked.table === 'string') {
|
|
21
|
+
name = tracked.table;
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
const config = getTableConfig(tracked.table);
|
|
25
|
+
name = config.name;
|
|
26
|
+
schema = config.schema ?? schema;
|
|
27
|
+
key ??= [
|
|
28
|
+
...config.columns.filter((column) => column.primary).map((column) => column.name),
|
|
29
|
+
...(config.primaryKeys[0]?.columns.map((column) => column.name) ?? []),
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
if (needKey && (key === undefined || key.length === 0)) {
|
|
33
|
+
throw new Error(`live: table "${name}" needs its key columns (key: [...])`);
|
|
34
|
+
}
|
|
35
|
+
const scope = tracked.scope?.map(nameOf) ?? [];
|
|
36
|
+
for (const column of [name, schema, ...(key ?? []), ...scope])
|
|
37
|
+
ident(column);
|
|
38
|
+
return { schema, name, key: key ?? [], scope };
|
|
39
|
+
}
|
|
40
|
+
export function liveTriggers(tables, options = {}) {
|
|
41
|
+
const channel = options.channel ?? DEFAULT_CHANNEL;
|
|
42
|
+
const fn = ident(options.functionName ?? 'live_notify');
|
|
43
|
+
const truncateFn = ident(`${options.functionName ?? 'live_notify'}_truncate`);
|
|
44
|
+
const parts = [
|
|
45
|
+
`CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql AS $live$
|
|
46
|
+
DECLARE
|
|
47
|
+
key_columns text[] := string_to_array(TG_ARGV[1], ',');
|
|
48
|
+
scope_columns text[] := coalesce(string_to_array(nullif(TG_ARGV[2], ''), ','), ARRAY[]::text[]);
|
|
49
|
+
records jsonb[] := ARRAY[]::jsonb[];
|
|
50
|
+
r jsonb;
|
|
51
|
+
c text;
|
|
52
|
+
k text;
|
|
53
|
+
topic text;
|
|
54
|
+
topics text[] := ARRAY[TG_TABLE_NAME::text];
|
|
55
|
+
payload text;
|
|
56
|
+
BEGIN
|
|
57
|
+
IF TG_OP IN ('UPDATE', 'DELETE') THEN records := records || to_jsonb(OLD); END IF;
|
|
58
|
+
IF TG_OP IN ('UPDATE', 'INSERT') THEN records := records || to_jsonb(NEW); END IF;
|
|
59
|
+
FOREACH r IN ARRAY records LOOP
|
|
60
|
+
SELECT string_agg(coalesce(r ->> u.col, ''), ',' ORDER BY u.ord) INTO k
|
|
61
|
+
FROM unnest(key_columns) WITH ORDINALITY AS u(col, ord);
|
|
62
|
+
topic := TG_TABLE_NAME || ':' || k;
|
|
63
|
+
topics := topics || CASE WHEN length(topic) > 200 THEN TG_TABLE_NAME || '*' ELSE topic END;
|
|
64
|
+
FOREACH c IN ARRAY scope_columns LOOP
|
|
65
|
+
topic := TG_TABLE_NAME || '@' || c || '=' || coalesce(r ->> c, '');
|
|
66
|
+
topics := topics || CASE WHEN length(topic) > 200 THEN TG_TABLE_NAME || '*' ELSE topic END;
|
|
67
|
+
END LOOP;
|
|
68
|
+
END LOOP;
|
|
69
|
+
payload := json_build_object('topics', (SELECT array_agg(DISTINCT t) FROM unnest(topics) AS t))::text;
|
|
70
|
+
IF octet_length(payload) > 7900 THEN
|
|
71
|
+
payload := json_build_object('topics', ARRAY[TG_TABLE_NAME || '*'])::text;
|
|
72
|
+
END IF;
|
|
73
|
+
PERFORM pg_notify(TG_ARGV[0], payload);
|
|
74
|
+
RETURN NULL;
|
|
75
|
+
END
|
|
76
|
+
$live$;`,
|
|
77
|
+
`CREATE OR REPLACE FUNCTION ${truncateFn}() RETURNS trigger LANGUAGE plpgsql AS $live$
|
|
78
|
+
BEGIN
|
|
79
|
+
PERFORM pg_notify(TG_ARGV[0], json_build_object('topics', ARRAY[TG_TABLE_NAME || '*'])::text);
|
|
80
|
+
RETURN NULL;
|
|
81
|
+
END
|
|
82
|
+
$live$;`,
|
|
83
|
+
];
|
|
84
|
+
for (const tracked of tables) {
|
|
85
|
+
const { schema, name, key, scope } = resolve(tracked);
|
|
86
|
+
const table = `${ident(schema)}.${ident(name)}`;
|
|
87
|
+
const row = ident(`${name}_live`);
|
|
88
|
+
const truncate = ident(`${name}_live_truncate`);
|
|
89
|
+
const args = [channel, key.join(','), scope.join(',')].map(literal).join(', ');
|
|
90
|
+
parts.push(`DROP TRIGGER IF EXISTS ${row} ON ${table};`, `CREATE TRIGGER ${row} AFTER INSERT OR UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION ${fn}(${args});`, `DROP TRIGGER IF EXISTS ${truncate} ON ${table};`, `CREATE TRIGGER ${truncate} AFTER TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION ${truncateFn}(${literal(channel)});`);
|
|
91
|
+
}
|
|
92
|
+
return `${parts.join('\n')}\n`;
|
|
93
|
+
}
|
|
94
|
+
export function dropLiveTriggers(tables) {
|
|
95
|
+
return `${tables
|
|
96
|
+
.flatMap((tracked) => {
|
|
97
|
+
const { schema, name } = resolve(tracked, false);
|
|
98
|
+
const table = `${ident(schema)}.${ident(name)}`;
|
|
99
|
+
return [
|
|
100
|
+
`DROP TRIGGER IF EXISTS ${ident(`${name}_live`)} ON ${table};`,
|
|
101
|
+
`DROP TRIGGER IF EXISTS ${ident(`${name}_live_truncate`)} ON ${table};`,
|
|
102
|
+
];
|
|
103
|
+
})
|
|
104
|
+
.join('\n')}\n`;
|
|
105
|
+
}
|
|
106
|
+
export function postgresJsListener(client) {
|
|
107
|
+
return {
|
|
108
|
+
listen: async (channel, onPayload, onListen) => {
|
|
109
|
+
const { unlisten } = await client.listen(channel, onPayload, onListen);
|
|
110
|
+
return unlisten;
|
|
111
|
+
},
|
|
112
|
+
notify: (channel, payload) => client.notify(channel, payload),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export function pgliteListener(pg) {
|
|
116
|
+
return {
|
|
117
|
+
listen: async (channel, onPayload, onListen) => {
|
|
118
|
+
const stop = await pg.listen(channel, onPayload);
|
|
119
|
+
onListen();
|
|
120
|
+
return stop;
|
|
121
|
+
},
|
|
122
|
+
notify: (channel, payload) => pg.query('SELECT pg_notify($1, $2)', [channel, payload]),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const MAX_RETRY_MS = 30_000;
|
|
126
|
+
export function pgSource(listener, options = {}) {
|
|
127
|
+
const channel = options.channel ?? DEFAULT_CHANNEL;
|
|
128
|
+
const log = options.log ??
|
|
129
|
+
((line) => {
|
|
130
|
+
console.error(line);
|
|
131
|
+
});
|
|
132
|
+
const firstRetry = options.retryMs ?? 1000;
|
|
133
|
+
let status = 'connecting';
|
|
134
|
+
return {
|
|
135
|
+
listen(onChange, onReset) {
|
|
136
|
+
let missed = false;
|
|
137
|
+
let up = false;
|
|
138
|
+
let stopped = false;
|
|
139
|
+
let stop;
|
|
140
|
+
let wait = firstRetry;
|
|
141
|
+
let timer;
|
|
142
|
+
const attempt = () => {
|
|
143
|
+
listener
|
|
144
|
+
.listen(channel, (payload) => {
|
|
145
|
+
const topics = topicsOf(payload);
|
|
146
|
+
if (topics.length > 0)
|
|
147
|
+
onChange(topics);
|
|
148
|
+
}, () => {
|
|
149
|
+
status = 'connected';
|
|
150
|
+
wait = firstRetry;
|
|
151
|
+
if (up || missed)
|
|
152
|
+
onReset();
|
|
153
|
+
up = true;
|
|
154
|
+
missed = false;
|
|
155
|
+
})
|
|
156
|
+
.then((unlisten) => {
|
|
157
|
+
if (stopped)
|
|
158
|
+
void unlisten();
|
|
159
|
+
else
|
|
160
|
+
stop = unlisten;
|
|
161
|
+
}, (error) => {
|
|
162
|
+
status = 'reconnecting';
|
|
163
|
+
missed = true;
|
|
164
|
+
log(`live: could not listen on "${channel}": ${String(error)}; trying again in ${wait} ms`);
|
|
165
|
+
if (stopped)
|
|
166
|
+
return;
|
|
167
|
+
timer = setTimeout(attempt, wait);
|
|
168
|
+
wait = Math.min(wait * 2, MAX_RETRY_MS);
|
|
169
|
+
});
|
|
170
|
+
};
|
|
171
|
+
attempt();
|
|
172
|
+
return () => {
|
|
173
|
+
stopped = true;
|
|
174
|
+
clearTimeout(timer);
|
|
175
|
+
void stop?.();
|
|
176
|
+
};
|
|
177
|
+
},
|
|
178
|
+
emit: async (topics) => {
|
|
179
|
+
for (const payload of payloads(cleanTopics(topics)))
|
|
180
|
+
await listener.notify(channel, payload);
|
|
181
|
+
},
|
|
182
|
+
status: () => status,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function topicsOf(payload) {
|
|
186
|
+
try {
|
|
187
|
+
const parsed = JSON.parse(payload);
|
|
188
|
+
return Array.isArray(parsed?.topics) ? cleanTopics(parsed.topics) : [];
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function payloads(topics) {
|
|
195
|
+
const out = [];
|
|
196
|
+
let batch = [];
|
|
197
|
+
for (const topic of topics) {
|
|
198
|
+
const next = [...batch, topic];
|
|
199
|
+
if (batch.length > 0 && JSON.stringify({ topics: next }).length > MAX_PAYLOAD) {
|
|
200
|
+
out.push(JSON.stringify({ topics: batch }));
|
|
201
|
+
batch = [topic];
|
|
202
|
+
}
|
|
203
|
+
else
|
|
204
|
+
batch = next;
|
|
205
|
+
}
|
|
206
|
+
if (batch.length > 0)
|
|
207
|
+
out.push(JSON.stringify({ topics: batch }));
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
export async function changed(tx, topics, channel = DEFAULT_CHANNEL) {
|
|
211
|
+
for (const payload of payloads(cleanTopics(topics))) {
|
|
212
|
+
await tx.execute(sql `SELECT pg_notify(${channel}, ${payload})`);
|
|
213
|
+
}
|
|
214
|
+
}
|