@fluixi/realtime 0.0.0-stage → 1.0.0-alpha.110
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 +24 -2
- package/dist/bus.cjs +127 -0
- package/dist/bus.d.ts +58 -0
- package/dist/bus.d.ts.map +1 -0
- package/dist/bus.js +118 -0
- package/dist/bus.mjs +8 -0
- package/dist/channel-protocol.cjs +42 -0
- package/dist/channel-protocol.d.ts +40 -0
- package/dist/channel-protocol.d.ts.map +1 -0
- package/dist/channel-protocol.js +24 -0
- package/dist/channel-protocol.mjs +8 -0
- package/dist/channel-server.cjs +291 -0
- package/dist/channel-server.d.ts +29 -0
- package/dist/channel-server.d.ts.map +1 -0
- package/dist/channel-server.js +122 -0
- package/dist/channel-server.mjs +9 -0
- package/dist/channels.cjs +426 -0
- package/dist/channels.d.ts +38 -0
- package/dist/channels.d.ts.map +1 -0
- package/dist/channels.js +82 -0
- package/dist/channels.mjs +9 -0
- package/dist/chunk-4CEAXWJN.mjs +31 -0
- package/dist/chunk-AWS4MP5D.mjs +107 -0
- package/dist/chunk-DNVSSCJA.mjs +22 -0
- package/dist/chunk-GAAZQJJ4.mjs +145 -0
- package/dist/chunk-MGON7IDW.mjs +77 -0
- package/dist/chunk-Q3NDGSX6.mjs +107 -0
- package/dist/chunk-UAZIXYV5.mjs +315 -0
- package/dist/chunk-X73D2DE2.mjs +19 -0
- package/dist/endpoint.cjs +165 -0
- package/dist/endpoint.d.ts +80 -0
- package/dist/endpoint.d.ts.map +1 -0
- package/dist/endpoint.js +168 -0
- package/dist/endpoint.mjs +8 -0
- package/dist/index.cjs +445 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.mjs +29 -0
- package/dist/serializers.cjs +39 -0
- package/dist/serializers.d.ts +12 -0
- package/dist/serializers.d.ts.map +1 -0
- package/dist/serializers.js +16 -0
- package/dist/serializers.mjs +8 -0
- package/dist/server.cjs +385 -0
- package/dist/server.d.ts +5 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +3 -0
- package/dist/server.mjs +20 -0
- package/dist/socket.cjs +362 -0
- package/dist/socket.d.ts +137 -0
- package/dist/socket.d.ts.map +1 -0
- package/dist/socket.js +351 -0
- package/dist/socket.mjs +16 -0
- package/dist/transport.cjs +51 -0
- package/dist/transport.d.ts +33 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +36 -0
- package/dist/transport.mjs +8 -0
- package/dist/tsconfig.lib.tsbuildinfo +1 -0
- package/package.json +65 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ibrahima Touré
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @fluixi/realtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A WebSocket client whose state is signals: status, last message, last error. It reconnects
|
|
4
|
+
with backoff, queues what you send while it connects, encodes messages the way you choose,
|
|
5
|
+
and opens nothing during server rendering.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createWebSocket, json } from '@fluixi/realtime';
|
|
9
|
+
|
|
10
|
+
const live = createWebSocket('/live', { serializer: json<Incoming, Outgoing>() });
|
|
11
|
+
|
|
12
|
+
live.status(); // 'connecting', then 'open'
|
|
13
|
+
live.send({ type: 'watch', id: 'p-12' }); // 'queued' until open, then 'sent'
|
|
14
|
+
live.subscribe((message) => refresh(message));
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- Created in a component, the connection closes with it; created in a module, it is shared
|
|
18
|
+
and `subscribe` and `on` end with the component that called them.
|
|
19
|
+
- `send` returns what happened (`sent`, `queued`, `queue-full`, `too-large`, `closed`); a
|
|
20
|
+
message is never dropped quietly.
|
|
21
|
+
- Text and binary frames, raw by default, `json()` or your own serializer.
|
|
22
|
+
- Reconnection, connect timeout, heartbeat by silence, size and queue limits.
|
|
23
|
+
- Depends on `@fluixi/reactive` only; works outside Fluixi components too.
|
|
24
|
+
|
|
25
|
+
Docs: [Realtime](https://docs.fluixi.com/v1/en/realtime).
|
package/dist/bus.cjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/bus.ts
|
|
21
|
+
var bus_exports = {};
|
|
22
|
+
__export(bus_exports, {
|
|
23
|
+
memoryBus: () => memoryBus,
|
|
24
|
+
postgresBus: () => postgresBus
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(bus_exports);
|
|
27
|
+
function memoryBus() {
|
|
28
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
29
|
+
return {
|
|
30
|
+
async publish(channel, message) {
|
|
31
|
+
for (const handler of handlers) handler(channel, message);
|
|
32
|
+
},
|
|
33
|
+
subscribe(handler) {
|
|
34
|
+
handlers.add(handler);
|
|
35
|
+
return () => void handlers.delete(handler);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
var MAX_PAYLOAD = 7999;
|
|
40
|
+
function postgresBus(options) {
|
|
41
|
+
const pgChannel = options.channel ?? "fluixi_realtime";
|
|
42
|
+
if (!/^[a-z_][a-z0-9_]*$/.test(pgChannel)) throw new Error(`postgresBus: "${pgChannel}" is not a plain lowercase identifier`);
|
|
43
|
+
const make = typeof options.listen === "function" ? options.listen : null;
|
|
44
|
+
let client = make ? make() : options.listen;
|
|
45
|
+
const notify = () => options.notify ?? client;
|
|
46
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
47
|
+
const gaps = /* @__PURE__ */ new Set();
|
|
48
|
+
const firstDelay = options.reconnectDelay ?? 500;
|
|
49
|
+
let closed = false;
|
|
50
|
+
let retry;
|
|
51
|
+
const listener = (notification) => {
|
|
52
|
+
if (notification.channel !== pgChannel || !notification.payload) return;
|
|
53
|
+
let parsed;
|
|
54
|
+
try {
|
|
55
|
+
parsed = JSON.parse(notification.payload);
|
|
56
|
+
} catch {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
for (const handler of handlers) handler(parsed.c, parsed.m);
|
|
60
|
+
};
|
|
61
|
+
const attach = async (next) => {
|
|
62
|
+
let lost = false;
|
|
63
|
+
const onLost = () => {
|
|
64
|
+
if (lost || closed || !make) return;
|
|
65
|
+
lost = true;
|
|
66
|
+
next.off?.("notification", listener);
|
|
67
|
+
void next.end?.().catch(() => {
|
|
68
|
+
});
|
|
69
|
+
replace(firstDelay);
|
|
70
|
+
};
|
|
71
|
+
next.on("notification", listener);
|
|
72
|
+
next.on("error", onLost);
|
|
73
|
+
next.on("end", onLost);
|
|
74
|
+
try {
|
|
75
|
+
if (make) await next.connect?.();
|
|
76
|
+
await next.query(`LISTEN ${pgChannel}`);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
lost = true;
|
|
79
|
+
next.off?.("notification", listener);
|
|
80
|
+
void next.end?.().catch(() => {
|
|
81
|
+
});
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const replace = (delay) => {
|
|
86
|
+
retry = setTimeout(async () => {
|
|
87
|
+
if (closed) return;
|
|
88
|
+
try {
|
|
89
|
+
client = make();
|
|
90
|
+
await attach(client);
|
|
91
|
+
for (const gap of [...gaps]) gap();
|
|
92
|
+
} catch {
|
|
93
|
+
replace(Math.min(delay * 2, 3e4));
|
|
94
|
+
}
|
|
95
|
+
}, delay);
|
|
96
|
+
retry.unref?.();
|
|
97
|
+
};
|
|
98
|
+
return {
|
|
99
|
+
async start() {
|
|
100
|
+
await attach(client);
|
|
101
|
+
},
|
|
102
|
+
async close() {
|
|
103
|
+
closed = true;
|
|
104
|
+
clearTimeout(retry);
|
|
105
|
+
client.off?.("notification", listener);
|
|
106
|
+
await client.query(`UNLISTEN ${pgChannel}`).catch(() => {
|
|
107
|
+
});
|
|
108
|
+
if (make) await client.end?.().catch(() => {
|
|
109
|
+
});
|
|
110
|
+
},
|
|
111
|
+
onGap(handler) {
|
|
112
|
+
gaps.add(handler);
|
|
113
|
+
return () => void gaps.delete(handler);
|
|
114
|
+
},
|
|
115
|
+
async publish(channel, message) {
|
|
116
|
+
const payload = JSON.stringify({ c: channel, m: message });
|
|
117
|
+
if (new TextEncoder().encode(payload).length > MAX_PAYLOAD) {
|
|
118
|
+
throw new Error(`postgresBus: a message on "${channel}" is over ${MAX_PAYLOAD} bytes; publish ids and let clients fetch`);
|
|
119
|
+
}
|
|
120
|
+
await notify().query("SELECT pg_notify($1, $2)", [pgChannel, payload]);
|
|
121
|
+
},
|
|
122
|
+
subscribe(handler) {
|
|
123
|
+
handlers.add(handler);
|
|
124
|
+
return () => void handlers.delete(handler);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
}
|
package/dist/bus.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { ChannelMessage } from './channel-protocol.js';
|
|
2
|
+
/**
|
|
3
|
+
* Carries published messages to every server instance, the publishing one included. One process
|
|
4
|
+
* needs no more than `memoryBus()`; several need a shared bus such as `postgresBus`.
|
|
5
|
+
*/
|
|
6
|
+
export interface RealtimeBus {
|
|
7
|
+
publish(channel: string, message: ChannelMessage): Promise<void>;
|
|
8
|
+
subscribe(handler: (channel: string, message: ChannelMessage) => void): () => void;
|
|
9
|
+
/** Called by the channel server's `start()`. */
|
|
10
|
+
start?(): Promise<void>;
|
|
11
|
+
/** Called by the channel server's `close()`. */
|
|
12
|
+
close?(): Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* Calls `handler` when messages may have been missed: the bus lost its connection and has it
|
|
15
|
+
* back. The channel server answers with `resync` to every member.
|
|
16
|
+
*/
|
|
17
|
+
onGap?(handler: () => void): () => void;
|
|
18
|
+
}
|
|
19
|
+
/** Delivers within this process only. */
|
|
20
|
+
export declare function memoryBus(): RealtimeBus;
|
|
21
|
+
type Notification = {
|
|
22
|
+
channel: string;
|
|
23
|
+
payload?: string;
|
|
24
|
+
};
|
|
25
|
+
/** The part of a Postgres client the bus uses; `pg`'s `Client` is one. */
|
|
26
|
+
export interface PostgresNotifyClient {
|
|
27
|
+
query(sql: string, params?: unknown[]): Promise<unknown>;
|
|
28
|
+
on(event: 'notification', listener: (notification: Notification) => void): unknown;
|
|
29
|
+
/** The connection failed or ended: with a factory for `listen`, the bus opens another. */
|
|
30
|
+
on(event: 'error' | 'end', listener: (error?: unknown) => void): unknown;
|
|
31
|
+
off?(event: 'notification', listener: (notification: Notification) => void): unknown;
|
|
32
|
+
/** Opens the connection, for a client made unconnected (`new pg.Client(...)`); called before `LISTEN`. */
|
|
33
|
+
connect?(): Promise<unknown>;
|
|
34
|
+
/** Closes the connection; called when the bus closes or replaces it. */
|
|
35
|
+
end?(): Promise<unknown>;
|
|
36
|
+
}
|
|
37
|
+
export interface PostgresBusOptions {
|
|
38
|
+
/**
|
|
39
|
+
* The client kept for listening: a direct connection, since a pooler in transaction mode drops
|
|
40
|
+
* `LISTEN`. A function making one lets the bus replace a connection that fails or ends: it
|
|
41
|
+
* tries again with growing waits, and once listening again reports a gap (`onGap`), since
|
|
42
|
+
* what was published meanwhile was missed. A client given as is is not replaced.
|
|
43
|
+
*/
|
|
44
|
+
listen: PostgresNotifyClient | (() => PostgresNotifyClient);
|
|
45
|
+
/** First wait before opening a lost listening connection again, in ms; doubles up to 30 s. Default: 500 */
|
|
46
|
+
reconnectDelay?: number;
|
|
47
|
+
/** Where `NOTIFY` goes; a pooled client is fine. Default: `listen` */
|
|
48
|
+
notify?: Pick<PostgresNotifyClient, 'query'>;
|
|
49
|
+
/** The Postgres channel. Default: 'fluixi_realtime' */
|
|
50
|
+
channel?: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Fans out through Postgres `LISTEN`/`NOTIFY`, so every server on the same database delivers
|
|
54
|
+
* what any of them publishes. Payloads stay under 8000 bytes: publish ids, not records.
|
|
55
|
+
*/
|
|
56
|
+
export declare function postgresBus(options: PostgresBusOptions): RealtimeBus;
|
|
57
|
+
export {};
|
|
58
|
+
//# sourceMappingURL=bus.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bus.d.ts","sourceRoot":"","sources":["../src/bus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5D;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjE,SAAS,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IACnF,gDAAgD;IAChD,KAAK,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB,gDAAgD;IAChD,KAAK,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB;;;OAGG;IACH,KAAK,CAAC,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;CACzC;AAED,yCAAyC;AACzC,wBAAgB,SAAS,IAAI,WAAW,CAWvC;AAED,KAAK,YAAY,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAE1D,0EAA0E;AAC1E,MAAM,WAAW,oBAAoB;IACnC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACzD,EAAE,CAAC,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC;IACnF,0FAA0F;IAC1F,EAAE,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,EAAE,QAAQ,EAAE,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC;IACzE,GAAG,CAAC,CAAC,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,CAAC,YAAY,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC;IACrF,0GAA0G;IAC1G,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7B,wEAAwE;IACxE,GAAG,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CAC1B;AAED,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,MAAM,EAAE,oBAAoB,GAAG,CAAC,MAAM,oBAAoB,CAAC,CAAC;IAC5D,2GAA2G;IAC3G,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,sEAAsE;IACtE,MAAM,CAAC,EAAE,IAAI,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC;IAC7C,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAKD;;;GAGG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,WAAW,CAwFpE"}
|
package/dist/bus.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** Delivers within this process only. */
|
|
2
|
+
export function memoryBus() {
|
|
3
|
+
const handlers = new Set();
|
|
4
|
+
return {
|
|
5
|
+
async publish(channel, message) {
|
|
6
|
+
for (const handler of handlers)
|
|
7
|
+
handler(channel, message);
|
|
8
|
+
},
|
|
9
|
+
subscribe(handler) {
|
|
10
|
+
handlers.add(handler);
|
|
11
|
+
return () => void handlers.delete(handler);
|
|
12
|
+
},
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** Postgres refuses a NOTIFY payload of 8000 bytes or more. */
|
|
16
|
+
const MAX_PAYLOAD = 7999;
|
|
17
|
+
/**
|
|
18
|
+
* Fans out through Postgres `LISTEN`/`NOTIFY`, so every server on the same database delivers
|
|
19
|
+
* what any of them publishes. Payloads stay under 8000 bytes: publish ids, not records.
|
|
20
|
+
*/
|
|
21
|
+
export function postgresBus(options) {
|
|
22
|
+
const pgChannel = options.channel ?? 'fluixi_realtime';
|
|
23
|
+
if (!/^[a-z_][a-z0-9_]*$/.test(pgChannel))
|
|
24
|
+
throw new Error(`postgresBus: "${pgChannel}" is not a plain lowercase identifier`);
|
|
25
|
+
const make = typeof options.listen === 'function' ? options.listen : null;
|
|
26
|
+
let client = make ? make() : options.listen;
|
|
27
|
+
const notify = () => options.notify ?? client;
|
|
28
|
+
const handlers = new Set();
|
|
29
|
+
const gaps = new Set();
|
|
30
|
+
const firstDelay = options.reconnectDelay ?? 500;
|
|
31
|
+
let closed = false;
|
|
32
|
+
let retry;
|
|
33
|
+
const listener = (notification) => {
|
|
34
|
+
if (notification.channel !== pgChannel || !notification.payload)
|
|
35
|
+
return;
|
|
36
|
+
let parsed;
|
|
37
|
+
try {
|
|
38
|
+
parsed = JSON.parse(notification.payload);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
for (const handler of handlers)
|
|
44
|
+
handler(parsed.c, parsed.m);
|
|
45
|
+
};
|
|
46
|
+
/** Listens on `next`, and replaces it when it fails, if the bus can make another. */
|
|
47
|
+
const attach = async (next) => {
|
|
48
|
+
let lost = false;
|
|
49
|
+
const onLost = () => {
|
|
50
|
+
if (lost || closed || !make)
|
|
51
|
+
return;
|
|
52
|
+
lost = true;
|
|
53
|
+
next.off?.('notification', listener);
|
|
54
|
+
void next.end?.().catch(() => { });
|
|
55
|
+
replace(firstDelay);
|
|
56
|
+
};
|
|
57
|
+
next.on('notification', listener);
|
|
58
|
+
next.on('error', onLost);
|
|
59
|
+
next.on('end', onLost);
|
|
60
|
+
try {
|
|
61
|
+
// A client the bus made is the bus's to connect; one given as is is connected already.
|
|
62
|
+
if (make)
|
|
63
|
+
await next.connect?.();
|
|
64
|
+
await next.query(`LISTEN ${pgChannel}`);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
// The caller retries; this connection's own error event must not schedule another.
|
|
68
|
+
lost = true;
|
|
69
|
+
next.off?.('notification', listener);
|
|
70
|
+
void next.end?.().catch(() => { });
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const replace = (delay) => {
|
|
75
|
+
retry = setTimeout(async () => {
|
|
76
|
+
if (closed)
|
|
77
|
+
return;
|
|
78
|
+
try {
|
|
79
|
+
client = make();
|
|
80
|
+
await attach(client);
|
|
81
|
+
for (const gap of [...gaps])
|
|
82
|
+
gap();
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
replace(Math.min(delay * 2, 30_000));
|
|
86
|
+
}
|
|
87
|
+
}, delay);
|
|
88
|
+
retry.unref?.();
|
|
89
|
+
};
|
|
90
|
+
return {
|
|
91
|
+
async start() {
|
|
92
|
+
await attach(client);
|
|
93
|
+
},
|
|
94
|
+
async close() {
|
|
95
|
+
closed = true;
|
|
96
|
+
clearTimeout(retry);
|
|
97
|
+
client.off?.('notification', listener);
|
|
98
|
+
await client.query(`UNLISTEN ${pgChannel}`).catch(() => { });
|
|
99
|
+
if (make)
|
|
100
|
+
await client.end?.().catch(() => { });
|
|
101
|
+
},
|
|
102
|
+
onGap(handler) {
|
|
103
|
+
gaps.add(handler);
|
|
104
|
+
return () => void gaps.delete(handler);
|
|
105
|
+
},
|
|
106
|
+
async publish(channel, message) {
|
|
107
|
+
const payload = JSON.stringify({ c: channel, m: message });
|
|
108
|
+
if (new TextEncoder().encode(payload).length > MAX_PAYLOAD) {
|
|
109
|
+
throw new Error(`postgresBus: a message on "${channel}" is over ${MAX_PAYLOAD} bytes; publish ids and let clients fetch`);
|
|
110
|
+
}
|
|
111
|
+
await notify().query('SELECT pg_notify($1, $2)', [pgChannel, payload]);
|
|
112
|
+
},
|
|
113
|
+
subscribe(handler) {
|
|
114
|
+
handlers.add(handler);
|
|
115
|
+
return () => void handlers.delete(handler);
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
package/dist/bus.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/channel-protocol.ts
|
|
21
|
+
var channel_protocol_exports = {};
|
|
22
|
+
__export(channel_protocol_exports, {
|
|
23
|
+
PING_FRAME: () => PING_FRAME,
|
|
24
|
+
parseClientFrame: () => parseClientFrame
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(channel_protocol_exports);
|
|
27
|
+
var PING_FRAME = '{"t":"ping"}';
|
|
28
|
+
function parseClientFrame(text) {
|
|
29
|
+
let frame;
|
|
30
|
+
try {
|
|
31
|
+
frame = JSON.parse(text);
|
|
32
|
+
} catch {
|
|
33
|
+
return void 0;
|
|
34
|
+
}
|
|
35
|
+
if (!frame || typeof frame !== "object") return void 0;
|
|
36
|
+
const { t, c, since } = frame;
|
|
37
|
+
if (typeof c !== "string" || !c || c.length > 200) return void 0;
|
|
38
|
+
if (t === "leave") return { t, c };
|
|
39
|
+
if (t !== "join") return void 0;
|
|
40
|
+
if (since === void 0) return { t, c };
|
|
41
|
+
return typeof since === "string" && since.length <= 200 ? { t, c, since } : void 0;
|
|
42
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A message on a channel. `id` orders a channel's messages for the app that publishes them (an
|
|
3
|
+
* event sequence, say); a client sends back the last one it saw to catch up after a reconnect.
|
|
4
|
+
*/
|
|
5
|
+
export interface ChannelMessage<T = unknown> {
|
|
6
|
+
id: string;
|
|
7
|
+
type: string;
|
|
8
|
+
data: T;
|
|
9
|
+
}
|
|
10
|
+
/** Frames a client sends. */
|
|
11
|
+
export type ClientFrame = {
|
|
12
|
+
t: 'join';
|
|
13
|
+
c: string;
|
|
14
|
+
since?: string;
|
|
15
|
+
} | {
|
|
16
|
+
t: 'leave';
|
|
17
|
+
c: string;
|
|
18
|
+
};
|
|
19
|
+
/** Frames the server sends. */
|
|
20
|
+
export type ServerFrame = {
|
|
21
|
+
t: 'msg';
|
|
22
|
+
c: string;
|
|
23
|
+
m: ChannelMessage;
|
|
24
|
+
} | {
|
|
25
|
+
t: 'joined';
|
|
26
|
+
c: string;
|
|
27
|
+
} | {
|
|
28
|
+
t: 'denied';
|
|
29
|
+
c: string;
|
|
30
|
+
} | {
|
|
31
|
+
t: 'resync';
|
|
32
|
+
c: string;
|
|
33
|
+
} | {
|
|
34
|
+
t: 'ping';
|
|
35
|
+
};
|
|
36
|
+
/** The keep-alive frame, sent on every protocol ping so browsers can watch for silence. */
|
|
37
|
+
export declare const PING_FRAME = "{\"t\":\"ping\"}";
|
|
38
|
+
/** A client frame, or undefined for anything else. */
|
|
39
|
+
export declare function parseClientFrame(text: string): ClientFrame | undefined;
|
|
40
|
+
//# sourceMappingURL=channel-protocol.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"channel-protocol.d.ts","sourceRoot":"","sources":["../src/channel-protocol.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,cAAc,CAAC,CAAC,GAAG,OAAO;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,CAAC,CAAC;CACT;AAED,6BAA6B;AAC7B,MAAM,MAAM,WAAW,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,CAAC,EAAE,OAAO,CAAC;IAAC,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/F,+BAA+B;AAC/B,MAAM,MAAM,WAAW,GACnB;IAAE,CAAC,EAAE,KAAK,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,cAAc,CAAA;CAAE,GAC1C;IAAE,CAAC,EAAE,QAAQ,CAAC;IAAC,CAAC,EAAE,MAAM,CAAA;CAAE,GAC1B;IAAE,CAAC,EAAE,QAAQ,CAAC;IAAC,CAAC,EAAE,MAAM,CAAA;CAAE,GAC1B;IAAE,CAAC,EAAE,QAAQ,CAAC;IAAC,CAAC,EAAE,MAAM,CAAA;CAAE,GAC1B;IAAE,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAElB,2FAA2F;AAC3F,eAAO,MAAM,UAAU,qBAAiB,CAAC;AAEzC,sDAAsD;AACtD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CActE"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** The keep-alive frame, sent on every protocol ping so browsers can watch for silence. */
|
|
2
|
+
export const PING_FRAME = '{"t":"ping"}';
|
|
3
|
+
/** A client frame, or undefined for anything else. */
|
|
4
|
+
export function parseClientFrame(text) {
|
|
5
|
+
let frame;
|
|
6
|
+
try {
|
|
7
|
+
frame = JSON.parse(text);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
if (!frame || typeof frame !== 'object')
|
|
13
|
+
return undefined;
|
|
14
|
+
const { t, c, since } = frame;
|
|
15
|
+
if (typeof c !== 'string' || !c || c.length > 200)
|
|
16
|
+
return undefined;
|
|
17
|
+
if (t === 'leave')
|
|
18
|
+
return { t, c };
|
|
19
|
+
if (t !== 'join')
|
|
20
|
+
return undefined;
|
|
21
|
+
if (since === undefined)
|
|
22
|
+
return { t, c };
|
|
23
|
+
return typeof since === 'string' && since.length <= 200 ? { t, c, since } : undefined;
|
|
24
|
+
}
|