@zukhruf/sqlite-notify 0.0.0-stage → 0.8.19

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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +286 -2
  3. package/dist/columns.d.ts +10 -0
  4. package/dist/columns.d.ts.map +1 -0
  5. package/dist/columns.js +26 -0
  6. package/dist/columns.js.map +1 -0
  7. package/dist/disposed-error.d.ts +5 -0
  8. package/dist/disposed-error.d.ts.map +1 -0
  9. package/dist/disposed-error.js +8 -0
  10. package/dist/disposed-error.js.map +1 -0
  11. package/dist/index.d.ts +6 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +6 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/limits.d.ts +3 -0
  16. package/dist/limits.d.ts.map +1 -0
  17. package/dist/limits.js +16 -0
  18. package/dist/limits.js.map +1 -0
  19. package/dist/listening.d.ts +46 -0
  20. package/dist/listening.d.ts.map +1 -0
  21. package/dist/listening.js +259 -0
  22. package/dist/listening.js.map +1 -0
  23. package/dist/notifications.d.ts +43 -0
  24. package/dist/notifications.d.ts.map +1 -0
  25. package/dist/notifications.js +240 -0
  26. package/dist/notifications.js.map +1 -0
  27. package/dist/queue-full-error.d.ts +7 -0
  28. package/dist/queue-full-error.d.ts.map +1 -0
  29. package/dist/queue-full-error.js +10 -0
  30. package/dist/queue-full-error.js.map +1 -0
  31. package/dist/release.d.ts +8 -0
  32. package/dist/release.d.ts.map +1 -0
  33. package/dist/release.js +27 -0
  34. package/dist/release.js.map +1 -0
  35. package/dist/removal-check.d.ts +15 -0
  36. package/dist/removal-check.d.ts.map +1 -0
  37. package/dist/removal-check.js +45 -0
  38. package/dist/removal-check.js.map +1 -0
  39. package/dist/schema.d.ts +4 -0
  40. package/dist/schema.d.ts.map +1 -0
  41. package/dist/schema.js +40 -0
  42. package/dist/schema.js.map +1 -0
  43. package/dist/steps.d.ts +6 -0
  44. package/dist/steps.d.ts.map +1 -0
  45. package/dist/steps.js +23 -0
  46. package/dist/steps.js.map +1 -0
  47. package/dist/tables.d.ts +6 -0
  48. package/dist/tables.d.ts.map +1 -0
  49. package/dist/tables.js +57 -0
  50. package/dist/tables.js.map +1 -0
  51. package/dist/wakes.d.ts +24 -0
  52. package/dist/wakes.d.ts.map +1 -0
  53. package/dist/wakes.js +176 -0
  54. package/dist/wakes.js.map +1 -0
  55. package/package.json +52 -4
@@ -0,0 +1,259 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { EventEmitter } from 'node:events';
3
+ import { delay } from '@zukhruf/async';
4
+ import { PipeEndpoint } from '@zukhruf/pipes';
5
+ import { UnchangedJournal, open } from '@zukhruf/sqlite-open';
6
+ import { transaction } from '@zukhruf/sqlite-transaction';
7
+ import { integer, text } from "./columns.js";
8
+ import { HIGHEST_ID } from "./schema.js";
9
+ // The backstop reads data_version once a second (ADR 0002), and writes the
10
+ // position at most as often (ADR 0005).
11
+ const BACKSTOP_INTERVAL = 1000;
12
+ // SQLite's BUSY (5): another connection holds the write lock past the busy
13
+ // timeout. A position write that meets it waits for the next backstop.
14
+ const SQLITE_BUSY = 5;
15
+ /** The connections that senders made to the listener's socket. Any byte that comes is a wake. */
16
+ class Inbox extends EventEmitter {
17
+ #sockets = new Set();
18
+ accept(socket) {
19
+ this.#sockets.add(socket);
20
+ socket.on('data', () => this.emit('wake'));
21
+ // A sender that goes away is normal; its close follows.
22
+ socket.on('error', () => { });
23
+ socket.on('close', () => this.#sockets.delete(socket));
24
+ }
25
+ destroy() {
26
+ for (const socket of this.#sockets)
27
+ socket.destroy();
28
+ }
29
+ }
30
+ /**
31
+ * A listener from its registration to its last unlisten: its own connection
32
+ * to the file, its socket, its row and the backstop. Each first `listen`
33
+ * makes a new one, with a new listener id and a new socket.
34
+ */
35
+ export class Listening {
36
+ /** 16 random bytes in hex: the name of the socket and the key of the row. */
37
+ id;
38
+ #database;
39
+ #server;
40
+ #inbox;
41
+ #options;
42
+ // Each channel, with the highest id at the commit of its listen: the
43
+ // channel delivers only the rows above it (C3).
44
+ #channels;
45
+ // Aborts at the end of the listener: the backstop stops, and reads stop.
46
+ #ended = new AbortController();
47
+ #rows;
48
+ #dataVersion;
49
+ #last;
50
+ #position;
51
+ #seenVersion;
52
+ constructor(id, database, server, inbox, registration, options) {
53
+ this.id = id;
54
+ this.#database = database;
55
+ this.#server = server;
56
+ this.#inbox = inbox;
57
+ this.#options = options;
58
+ this.#channels = new Map([[registration.channel, registration.highest]]);
59
+ this.#last = registration.highest;
60
+ this.#position = registration.highest;
61
+ this.#rows = database.prepare('SELECT id, channel, payload, process_id FROM zukhruf_notify_queue WHERE id > ? ORDER BY id');
62
+ this.#dataVersion = database.prepare('PRAGMA data_version');
63
+ this.#seenVersion = this.#readDataVersion();
64
+ inbox.on('wake', () => this.read());
65
+ void this.#runBackstop(this.#ended.signal).catch(options.fail);
66
+ }
67
+ /**
68
+ * The registration: opens the listener's own connection, serves a new
69
+ * socket, and in one BEGIN IMMEDIATE transaction inserts the listener row
70
+ * with its address and the highest id as its position, and the channel row.
71
+ */
72
+ static async register(channel, options) {
73
+ // The listener never sets the journal: the sending connection did.
74
+ const database = open(options.path, { journal: new UnchangedJournal() });
75
+ try {
76
+ const id = randomBytes(16).toHex();
77
+ const endpoint = new PipeEndpoint(id, {
78
+ prefix: 'zukhruf-sqlite-notify',
79
+ });
80
+ const inbox = new Inbox();
81
+ const server = await endpoint.listen((socket) => inbox.accept(socket));
82
+ try {
83
+ const highest = transaction(database, () => {
84
+ const highest = highestId(database);
85
+ database
86
+ .prepare('INSERT INTO zukhruf_notify_listener (id, address, position, process_id) VALUES (?, ?, ?, ?)')
87
+ .run(id, endpoint.address.path, highest, process.pid);
88
+ insertChannel(database, channel, id);
89
+ return highest;
90
+ }, { mode: 'immediate' });
91
+ return new Listening(id, database, server, inbox, { channel, highest }, options);
92
+ }
93
+ catch (error) {
94
+ await closeSocket(server, inbox);
95
+ throw error;
96
+ }
97
+ }
98
+ catch (error) {
99
+ database.close();
100
+ throw error;
101
+ }
102
+ }
103
+ /** A later listen: one BEGIN IMMEDIATE transaction inserts the channel row and reads the highest id. */
104
+ add(channel) {
105
+ if (this.#channels.has(channel))
106
+ return;
107
+ const highest = transaction(this.#database, () => {
108
+ insertChannel(this.#database, channel, this.id);
109
+ return highestId(this.#database);
110
+ }, { mode: 'immediate' });
111
+ this.#channels.set(channel, highest);
112
+ }
113
+ /** Removes the channel row; the last one ends the listener. Resolves `true` when the listener ended. */
114
+ async remove(channel) {
115
+ if (!this.#channels.has(channel))
116
+ return false;
117
+ if (this.#channels.size === 1) {
118
+ await this.end();
119
+ return true;
120
+ }
121
+ this.#channels.delete(channel);
122
+ this.#database
123
+ .prepare('DELETE FROM zukhruf_notify_channel WHERE channel = ? AND listener = ?')
124
+ .run(channel, this.id);
125
+ return false;
126
+ }
127
+ /** Removes this listener's rows, closes its socket, and closes its connection. */
128
+ async end() {
129
+ if (this.#ended.signal.aborted)
130
+ return;
131
+ this.#ended.abort();
132
+ this.#channels.clear();
133
+ try {
134
+ transaction(this.#database, () => {
135
+ this.#database
136
+ .prepare('DELETE FROM zukhruf_notify_channel WHERE listener = ?')
137
+ .run(this.id);
138
+ this.#database
139
+ .prepare('DELETE FROM zukhruf_notify_listener WHERE id = ?')
140
+ .run(this.id);
141
+ }, { mode: 'immediate' });
142
+ }
143
+ finally {
144
+ try {
145
+ await closeSocket(this.#server, this.#inbox);
146
+ }
147
+ finally {
148
+ this.#database.close();
149
+ }
150
+ }
151
+ }
152
+ /**
153
+ * Reads the rows above the last id on the listener's own connection,
154
+ * outside a transaction, with one statement read to the end (research 20b
155
+ * T4), and delivers the rows of its channels.
156
+ */
157
+ read() {
158
+ if (this.#ended.signal.aborted)
159
+ return;
160
+ let rows;
161
+ try {
162
+ rows = this.#rows.all(this.#last).map((row) => ({
163
+ id: integer(row, 'id'),
164
+ channel: text(row, 'channel'),
165
+ payload: text(row, 'payload'),
166
+ processId: integer(row, 'process_id'),
167
+ }));
168
+ }
169
+ catch (error) {
170
+ this.#options.fail(error);
171
+ return;
172
+ }
173
+ for (const row of rows) {
174
+ if (this.#ended.signal.aborted)
175
+ return;
176
+ this.#last = row.id;
177
+ const since = this.#channels.get(row.channel);
178
+ if (since !== undefined && row.id > since)
179
+ this.#options.deliver(row);
180
+ }
181
+ }
182
+ async #runBackstop(signal) {
183
+ for (;;) {
184
+ try {
185
+ await delay(BACKSTOP_INTERVAL, { clock: this.#options.clock, signal });
186
+ }
187
+ catch (error) {
188
+ if (signal.aborted)
189
+ return;
190
+ throw error;
191
+ }
192
+ this.#check();
193
+ }
194
+ }
195
+ // The backstop: reads the queue when data_version changed, then writes the
196
+ // position when it moved. A busy file skips the write until the next check.
197
+ #check() {
198
+ try {
199
+ const version = this.#readDataVersion();
200
+ if (version !== this.#seenVersion) {
201
+ this.#seenVersion = version;
202
+ this.read();
203
+ }
204
+ }
205
+ catch (error) {
206
+ this.#options.fail(error);
207
+ }
208
+ if (this.#ended.signal.aborted || this.#last <= this.#position)
209
+ return;
210
+ try {
211
+ this.#writePosition();
212
+ this.#position = this.#last;
213
+ }
214
+ catch (error) {
215
+ if (!isBusy(error))
216
+ this.#options.fail(error);
217
+ }
218
+ }
219
+ // node:sqlite is synchronous, so a write that waits for the lock stops the
220
+ // event loop of the listener. The busy timeout is a setting of the
221
+ // connection (node:sqlite has none for one statement), so the write runs
222
+ // with a busy timeout of 0: a busy file fails it at once, and the next
223
+ // backstop tries again (ADR 0005).
224
+ #writePosition() {
225
+ const timeout = integer(this.#database.prepare('PRAGMA busy_timeout').get(), 'timeout');
226
+ this.#database.exec('PRAGMA busy_timeout = 0');
227
+ try {
228
+ this.#database
229
+ .prepare('UPDATE zukhruf_notify_listener SET position = ? WHERE id = ?')
230
+ .run(this.#last, this.id);
231
+ }
232
+ finally {
233
+ this.#database.exec(`PRAGMA busy_timeout = ${timeout}`);
234
+ }
235
+ }
236
+ #readDataVersion() {
237
+ return integer(this.#dataVersion.get(), 'data_version');
238
+ }
239
+ }
240
+ function highestId(database) {
241
+ return integer(database.prepare(`SELECT ${HIGHEST_ID} AS id`).get(), 'id');
242
+ }
243
+ function insertChannel(database, channel, listener) {
244
+ database
245
+ .prepare('INSERT INTO zukhruf_notify_channel (channel, listener) VALUES (?, ?)')
246
+ .run(channel, listener);
247
+ }
248
+ // The server stops listening and Node removes the socket file; the
249
+ // connections that are open end in the same step (pipes' rule).
250
+ async function closeSocket(server, inbox) {
251
+ const closed = server.close();
252
+ inbox.destroy();
253
+ await closed;
254
+ }
255
+ function isBusy(error) {
256
+ const code = Reflect.get(Object(error), 'errcode');
257
+ return typeof code === 'number' && (code & 0xff) === SQLITE_BUSY;
258
+ }
259
+ //# sourceMappingURL=listening.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"listening.js","sourceRoot":"","sources":["../src/listening.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAI3C,OAAO,EAAc,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAE1D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAmBzC,2EAA2E;AAC3E,wCAAwC;AACxC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAC/B,2EAA2E;AAC3E,uEAAuE;AACvE,MAAM,WAAW,GAAG,CAAC,CAAC;AAEtB,iGAAiG;AACjG,MAAM,KAAM,SAAQ,YAA0B;IACnC,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;IAEtC,MAAM,CAAC,MAAc;QACnB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3
+ import { type Clock } from '@zukhruf/async';
4
+ export type NotificationsOptions = FileOptions | ConnectionOptions;
5
+ export interface FileOptions {
6
+ path: string;
7
+ database?: never;
8
+ clock: Clock;
9
+ maxQueuedNotifications?: number;
10
+ }
11
+ export interface ConnectionOptions {
12
+ database: DatabaseSync;
13
+ path?: never;
14
+ clock: Clock;
15
+ maxQueuedNotifications?: number;
16
+ }
17
+ /** The `Notification` of `pg` (node-postgres): the same fields and types. */
18
+ export interface Notification {
19
+ processId: number;
20
+ channel: string;
21
+ payload: string;
22
+ }
23
+ /** Postgres's LISTEN and NOTIFY for one SQLite file, among the programs of one computer. */
24
+ export declare class Notifications extends EventEmitter<{
25
+ notification: [Notification];
26
+ error: [unknown];
27
+ }> implements AsyncDisposable {
28
+ #private;
29
+ constructor(options: NotificationsOptions);
30
+ /** Resolves when the registration has committed; each notification that commits after it comes to `notification`. */
31
+ listen(channel: string): Promise<void>;
32
+ /** Stops the notifications of the channel at once; the last one removes the listener's row and closes its socket. */
33
+ unlisten(channel: string): Promise<void>;
34
+ /**
35
+ * Inserts the notification in the current transaction of the sending
36
+ * connection, or in a BEGIN IMMEDIATE transaction of its own. The wakes go
37
+ * out on the next microtask, after the transaction ended (ADR 0004).
38
+ */
39
+ notify(channel: string, payload?: string): void;
40
+ /** Writes the wakes that are due, ends the connections to other listeners, removes this listener's rows, closes its socket and the connections that it opened. */
41
+ [Symbol.asyncDispose](): Promise<void>;
42
+ }
43
+ //# sourceMappingURL=notifications.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notifications.d.ts","sourceRoot":"","sources":["../src/notifications.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAiC,MAAM,aAAa,CAAC;AAE/E,OAAO,EAAE,KAAK,KAAK,EAAS,MAAM,gBAAgB,CAAC;AAenD,MAAM,MAAM,oBAAoB,GAAG,WAAW,GAAG,iBAAiB,CAAC;AAEnE,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,KAAK,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC;IACb,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,YAAY,CAAC;IACvB,IAAI,CAAC,EAAE,KAAK,CAAC;IACb,KAAK,EAAE,KAAK,CAAC;IACb,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,6EAA6E;AAC7E,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB;AAUD,4FAA4F;AAC5F,qBAAa,aACX,SAAQ,YAAY,CAAC;IAAE,YAAY,EAAE,CAAC,YAAY,CAAC,CAAC;IAAC,KAAK,EAAE,CAAC,OAAO,CAAC,CAAA;CAAE,CACvE,YAAW,eAAe;;gBAyBd,OAAO,EAAE,oBAAoB;IAgEzC,qHAAqH;IAC/G,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAyB5C,qHAAqH;IAC/G,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAW9C;;;;OAIG;IACH,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,SAAK,GAAG,IAAI;IAuC3C,kKAAkK;IAC5J,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC;CAyD7C"}
@@ -0,0 +1,240 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { Latch } from '@zukhruf/async';
3
+ import { WriteAheadLog, open } from '@zukhruf/sqlite-open';
4
+ import { transaction } from '@zukhruf/sqlite-transaction';
5
+ import { integer, integerOrNull, text } from "./columns.js";
6
+ import { DisposedError } from "./disposed-error.js";
7
+ import { checkChannel, checkPayload } from "./limits.js";
8
+ import { Listening } from "./listening.js";
9
+ import { QueueFullError } from "./queue-full-error.js";
10
+ import { RemovalCheck } from "./removal-check.js";
11
+ import { HIGHEST_ID } from "./schema.js";
12
+ import { Steps } from "./steps.js";
13
+ import { Tables } from "./tables.js";
14
+ import { Wakes } from "./wakes.js";
15
+ // Postgres's default queue holds at least this many notifications of the
16
+ // largest payload, one for each page (ADR 0005).
17
+ const DEFAULT_MAX_QUEUED = 1_048_576;
18
+ // A trim at most once a second deletes at most this many rows, about 2 ms
19
+ // (research 20i).
20
+ const TRIM_INTERVAL = 1000;
21
+ const TRIM_LIMIT = 10_000;
22
+ /** Postgres's LISTEN and NOTIFY for one SQLite file, among the programs of one computer. */
23
+ export class Notifications extends EventEmitter {
24
+ #database;
25
+ #owned;
26
+ #path;
27
+ #clock;
28
+ #maxQueued;
29
+ #wakes;
30
+ #removalCheck;
31
+ #ends;
32
+ #insert;
33
+ #addresses;
34
+ #trim;
35
+ #laggards;
36
+ #removeChannels;
37
+ #removeListener;
38
+ // The channels as the calls asked, at once: unlisten stops a channel before
39
+ // its row is removed.
40
+ #wanted = new Set();
41
+ // listen, unlisten and dispose change the listener one after another.
42
+ #steps = new Steps();
43
+ #listener = { kind: 'idle' };
44
+ #lastTrim = -Infinity;
45
+ #lifetime = { kind: 'open' };
46
+ constructor(options) {
47
+ super();
48
+ this.#clock = options.clock;
49
+ this.#maxQueued = options.maxQueuedNotifications ?? DEFAULT_MAX_QUEUED;
50
+ if (options.database === undefined) {
51
+ this.#database = open(options.path, {
52
+ journal: new WriteAheadLog({ synchronous: 'full' }),
53
+ });
54
+ this.#owned = true;
55
+ }
56
+ else {
57
+ this.#database = options.database;
58
+ this.#owned = false;
59
+ }
60
+ const path = this.#database.location();
61
+ if (path === null) {
62
+ if (this.#owned)
63
+ this.#database.close();
64
+ throw new TypeError('A database in memory has no file that another program can open; give a database on a file.');
65
+ }
66
+ this.#path = path;
67
+ try {
68
+ Tables.install(this.#database);
69
+ }
70
+ catch (error) {
71
+ if (this.#owned)
72
+ this.#database.close();
73
+ throw error;
74
+ }
75
+ const database = this.#database;
76
+ this.#ends = database.prepare(`SELECT ${HIGHEST_ID} AS highest, (SELECT min(position) FROM zukhruf_notify_listener) AS lowest`);
77
+ this.#insert = database.prepare('INSERT INTO zukhruf_notify_queue (channel, payload, process_id) VALUES (?, ?, ?)');
78
+ this.#addresses = database.prepare('SELECT l.id, l.address FROM zukhruf_notify_listener l JOIN zukhruf_notify_channel c ON c.listener = l.id WHERE c.channel = ?');
79
+ this.#trim = database.prepare(`DELETE FROM zukhruf_notify_queue WHERE id IN (SELECT id FROM zukhruf_notify_queue WHERE id <= coalesce((SELECT min(position) FROM zukhruf_notify_listener), ${HIGHEST_ID}) ORDER BY id LIMIT ${TRIM_LIMIT})`);
80
+ this.#laggards = database.prepare(`SELECT id, address FROM zukhruf_notify_listener WHERE position = (SELECT min(position) FROM zukhruf_notify_listener) AND position < ${HIGHEST_ID}`);
81
+ this.#removeChannels = database.prepare('DELETE FROM zukhruf_notify_channel WHERE listener = ?');
82
+ this.#removeListener = database.prepare('DELETE FROM zukhruf_notify_listener WHERE id = ?');
83
+ this.#wakes = new Wakes((id) => {
84
+ if (this.#listener.kind !== 'listening')
85
+ return false;
86
+ const { listening } = this.#listener;
87
+ if (listening.id !== id)
88
+ return false;
89
+ listening.read();
90
+ return true;
91
+ }, (error) => this.emit('error', error));
92
+ this.#removalCheck = new RemovalCheck(database, this.#wakes, (error) => this.emit('error', error));
93
+ }
94
+ /** Resolves when the registration has committed; each notification that commits after it comes to `notification`. */
95
+ async listen(channel) {
96
+ checkChannel(channel);
97
+ this.#assertOpen();
98
+ this.#wanted.add(channel);
99
+ await this.#steps.run(async () => {
100
+ if (!this.#wanted.has(channel))
101
+ return;
102
+ try {
103
+ if (this.#listener.kind === 'listening') {
104
+ this.#listener.listening.add(channel);
105
+ return;
106
+ }
107
+ const listening = await Listening.register(channel, {
108
+ path: this.#path,
109
+ clock: this.#clock,
110
+ deliver: (row) => this.#deliver(row),
111
+ fail: (error) => this.emit('error', error),
112
+ });
113
+ this.#listener = { kind: 'listening', listening };
114
+ }
115
+ catch (error) {
116
+ this.#wanted.delete(channel);
117
+ throw error;
118
+ }
119
+ });
120
+ }
121
+ /** Stops the notifications of the channel at once; the last one removes the listener's row and closes its socket. */
122
+ async unlisten(channel) {
123
+ checkChannel(channel);
124
+ this.#assertOpen();
125
+ this.#wanted.delete(channel);
126
+ await this.#steps.run(async () => {
127
+ if (this.#listener.kind !== 'listening')
128
+ return;
129
+ if (await this.#listener.listening.remove(channel))
130
+ this.#listener = { kind: 'idle' };
131
+ });
132
+ }
133
+ /**
134
+ * Inserts the notification in the current transaction of the sending
135
+ * connection, or in a BEGIN IMMEDIATE transaction of its own. The wakes go
136
+ * out on the next microtask, after the transaction ended (ADR 0004).
137
+ */
138
+ notify(channel, payload = '') {
139
+ checkChannel(channel);
140
+ checkPayload(payload);
141
+ this.#assertOpen();
142
+ const dead = this.#wakes.dead();
143
+ // A transaction of the call's own that returns has committed the removal
144
+ // of the dead listeners' rows. A removal in a savepoint commits or rolls
145
+ // back with the caller's transaction, whose end node:sqlite does not report
146
+ // (ADR 0004, ADR 0010).
147
+ const own = !this.#database.isTransaction;
148
+ const listeners = transaction(this.#database, () => {
149
+ for (const id of dead.keys()) {
150
+ this.#removeChannels.run(id);
151
+ this.#removeListener.run(id);
152
+ }
153
+ // The highest id minus the lowest position: two reads of indexes,
154
+ // exact, where a count(*) scans the table (research 20i).
155
+ const ends = this.#ends.get();
156
+ const lowest = integerOrNull(ends, 'lowest');
157
+ if (lowest !== null &&
158
+ integer(ends, 'highest') - lowest >= this.#maxQueued)
159
+ throw new QueueFullError();
160
+ this.#insert.run(channel, payload, process.pid);
161
+ return [
162
+ ...addressed(this.#addresses.all(channel)),
163
+ ...this.#trimAtMostOnceASecond(),
164
+ ];
165
+ }, { mode: 'immediate' });
166
+ this.#wakes.sent(listeners);
167
+ if (own)
168
+ this.#wakes.removed(dead);
169
+ else
170
+ this.#removalCheck.removedInCallersTransaction(dead);
171
+ }
172
+ /** Writes the wakes that are due, ends the connections to other listeners, removes this listener's rows, closes its socket and the connections that it opened. */
173
+ async [Symbol.asyncDispose]() {
174
+ if (this.#lifetime.kind === 'open') {
175
+ const ended = new Latch();
176
+ this.#lifetime = { kind: 'disposed', ended };
177
+ const [outcome] = await Promise.allSettled([this.#dispose()]);
178
+ ended.open(outcome);
179
+ }
180
+ const outcome = await this.#lifetime.ended.wait();
181
+ if (outcome.status === 'rejected')
182
+ throw outcome.reason;
183
+ }
184
+ async #dispose() {
185
+ this.#wanted.clear();
186
+ await this.#steps.run(async () => {
187
+ try {
188
+ await this.#wakes.close();
189
+ if (this.#listener.kind === 'listening') {
190
+ const { listening } = this.#listener;
191
+ this.#listener = { kind: 'idle' };
192
+ await listening.end();
193
+ }
194
+ }
195
+ finally {
196
+ if (this.#owned)
197
+ this.#database.close();
198
+ }
199
+ });
200
+ }
201
+ // Gives the laggards, which the trim waits for. They are woken whatever
202
+ // their channels, as Postgres's SignalBackends wakes the listeners that are
203
+ // far behind (ADR 0010): a live one reads, and a dead one refuses the
204
+ // connect.
205
+ #trimAtMostOnceASecond() {
206
+ const now = this.#clock.performance.now();
207
+ if (now - this.#lastTrim < TRIM_INTERVAL)
208
+ return [];
209
+ this.#lastTrim = now;
210
+ this.#trim.run();
211
+ return addressed(this.#laggards.all());
212
+ }
213
+ // A notification listener that throws sends its error to `error`, and the
214
+ // next notifications of the read still come.
215
+ #deliver(row) {
216
+ if (!this.#wanted.has(row.channel))
217
+ return;
218
+ try {
219
+ this.emit('notification', {
220
+ processId: row.processId,
221
+ channel: row.channel,
222
+ payload: row.payload,
223
+ });
224
+ }
225
+ catch (error) {
226
+ this.emit('error', error);
227
+ }
228
+ }
229
+ #assertOpen() {
230
+ if (this.#lifetime.kind === 'disposed')
231
+ throw new DisposedError();
232
+ }
233
+ }
234
+ function addressed(rows) {
235
+ return rows.map((row) => ({
236
+ id: text(row, 'id'),
237
+ address: text(row, 'address'),
238
+ }));
239
+ }
240
+ //# sourceMappingURL=notifications.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notifications.js","sourceRoot":"","sources":["../src/notifications.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAG3C,OAAO,EAAc,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAE1D,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,SAAS,EAA2B,MAAM,gBAAgB,CAAC;AACpE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAkB,KAAK,EAAE,MAAM,YAAY,CAAC;AAyBnD,yEAAyE;AACzE,iDAAiD;AACjD,MAAM,kBAAkB,GAAG,SAAS,CAAC;AACrC,0EAA0E;AAC1E,kBAAkB;AAClB,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,UAAU,GAAG,MAAM,CAAC;AAE1B,4FAA4F;AAC5F,MAAM,OAAO,aACX,SAAQ,YAAgE;IAG/D,SAAS,CAAe;IACxB,MAAM,CAAU;IAChB,KAAK,CAAS;IACd,MAAM,CAAQ;IACd,UAAU,CAAS;IACnB,MAAM,CA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;QACjB,OAAO,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,CAAC;IACzC,CAAC;IAED,0EAA0E;IAC1E,6CAA6C;IAC7C,QAAQ,CAAC,GAAuB;QAC9B,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC;YAAE,OAAO;QAC3C,IAAI,CAAC;YACH,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE;gBACxB,SAAS,EAAE,GAAG,CAAC,SAAS;gBACxB,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,OAAO,EAAE,GAAG,CAAC,OAAO;aACrB,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IAED,WAAW;QACT,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,KAAK,UAAU;YAAE,MAAM,IAAI,aAAa,EAAE,CAAC;IACpE,CAAC;CACF;AAED,SAAS,SAAS,CAAC,IAAsC;IACvD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QACxB,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC;QACnB,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC;KAC9B,CAAC,CAAC,CAAC;AACN,CAAC"}
@@ -0,0 +1,7 @@
1
+ /** The queue holds `maxQueuedNotifications` rows that a listener has not read. Postgres's message and code. */
2
+ export declare class QueueFullError extends Error {
3
+ /** ERRCODE_PROGRAM_LIMIT_EXCEEDED. */
4
+ readonly code = "54000";
5
+ constructor();
6
+ }
7
+ //# sourceMappingURL=queue-full-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-full-error.d.ts","sourceRoot":"","sources":["../src/queue-full-error.ts"],"names":[],"mappings":"AAAA,+GAA+G;AAC/G,qBAAa,cAAe,SAAQ,KAAK;IACvC,sCAAsC;IACtC,QAAQ,CAAC,IAAI,WAAW;;CAMzB"}
@@ -0,0 +1,10 @@
1
+ /** The queue holds `maxQueuedNotifications` rows that a listener has not read. Postgres's message and code. */
2
+ export class QueueFullError extends Error {
3
+ /** ERRCODE_PROGRAM_LIMIT_EXCEEDED. */
4
+ code = '54000';
5
+ constructor() {
6
+ super('too many notifications in the NOTIFY queue');
7
+ this.name = 'QueueFullError';
8
+ }
9
+ }
10
+ //# sourceMappingURL=queue-full-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue-full-error.js","sourceRoot":"","sources":["../src/queue-full-error.ts"],"names":[],"mappings":"AAAA,+GAA+G;AAC/G,MAAM,OAAO,cAAe,SAAQ,KAAK;IACvC,sCAAsC;IAC7B,IAAI,GAAG,OAAO,CAAC;IAExB;QACE,KAAK,CAAC,4CAA4C,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF"}
@@ -0,0 +1,8 @@
1
+ export declare class Release {
2
+ #private;
3
+ static readonly current: Release;
4
+ readonly version: string;
5
+ constructor(version: string);
6
+ isAfter(other: Release): boolean;
7
+ }
8
+ //# sourceMappingURL=release.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"release.d.ts","sourceRoot":"","sources":["../src/release.ts"],"names":[],"mappings":"AAKA,qBAAa,OAAO;;IAElB,MAAM,CAAC,QAAQ,CAAC,OAAO,UAMrB;IAEF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;gBAGb,OAAO,EAAE,MAAM;IAU3B,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO;CAOjC"}
@@ -0,0 +1,27 @@
1
+ import { readFileSync } from 'node:fs';
2
+ // A release of this package, by the version in its package.json. Fixed
3
+ // versioning raises the version at each release, so the versions order the
4
+ // releases and no person keeps a schema number (docs/adr/0009).
5
+ export class Release {
6
+ // ../package.json is the package root from src/ and from dist/ alike.
7
+ static current = new Release(String(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version));
8
+ version;
9
+ #parts;
10
+ constructor(version) {
11
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
12
+ if (match === null)
13
+ throw new Error(`A release version is MAJOR.MINOR.PATCH, not ${version}.`);
14
+ this.version = version;
15
+ this.#parts = [Number(match[1]), Number(match[2]), Number(match[3])];
16
+ }
17
+ isAfter(other) {
18
+ const [major, minor, patch] = this.#parts;
19
+ const [theirMajor, theirMinor, theirPatch] = other.#parts;
20
+ if (major !== theirMajor)
21
+ return major > theirMajor;
22
+ if (minor !== theirMinor)
23
+ return minor > theirMinor;
24
+ return patch > theirPatch;
25
+ }
26
+ }
27
+ //# sourceMappingURL=release.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"release.js","sourceRoot":"","sources":["../src/release.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEvC,uEAAuE;AACvE,2EAA2E;AAC3E,gEAAgE;AAChE,MAAM,OAAO,OAAO;IAClB,sEAAsE;IACtE,MAAM,CAAU,OAAO,GAAG,IAAI,OAAO,CACnC,MAAM,CACJ,IAAI,CAAC,KAAK,CACR,YAAY,CAAC,IAAI,GAAG,CAAC,iBAAiB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAClE,CAAC,OAAO,CACV,CACF,CAAC;IAEO,OAAO,CAAS;IAChB,MAAM,CAAoC;IAEnD,YAAY,OAAe;QACzB,MAAM,KAAK,GAAG,uBAAuB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpD,IAAI,KAAK,KAAK,IAAI;YAChB,MAAM,IAAI,KAAK,CACb,+CAA+C,OAAO,GAAG,CAC1D,CAAC;QACJ,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,KA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