@supatype/client 0.9.1 → 0.10.0
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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +112 -72
- package/.turbo/turbo-typecheck.log +2 -2
- package/CHANGELOG.md +123 -20
- package/README.md +18 -0
- package/dist/auth.d.ts +13 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +53 -13
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +4 -1
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +2 -1
- package/dist/bindings.js.map +1 -1
- package/dist/channel-watch.d.ts +42 -0
- package/dist/channel-watch.d.ts.map +1 -0
- package/dist/channel-watch.js +59 -0
- package/dist/channel-watch.js.map +1 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +31 -0
- package/dist/errors.js.map +1 -1
- package/dist/exact-values.d.ts +18 -5
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +76 -12
- package/dist/exact-values.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +1 -1
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +20 -2
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/latest-rows.d.ts +15 -0
- package/dist/latest-rows.d.ts.map +1 -1
- package/dist/latest-rows.js +14 -7
- package/dist/latest-rows.js.map +1 -1
- package/dist/public-env.d.ts +13 -0
- package/dist/public-env.d.ts.map +1 -0
- package/dist/public-env.js +23 -0
- package/dist/public-env.js.map +1 -0
- package/dist/query-cache.d.ts +2 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +7 -0
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +12 -4
- package/dist/query.js.map +1 -1
- package/dist/realtime-refusals.d.ts +35 -0
- package/dist/realtime-refusals.d.ts.map +1 -0
- package/dist/realtime-refusals.js +73 -0
- package/dist/realtime-refusals.js.map +1 -0
- package/dist/realtime.d.ts +87 -8
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +304 -51
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts +2 -0
- package/dist/runtime-env.d.ts.map +1 -1
- package/dist/runtime-env.js +45 -5
- package/dist/runtime-env.js.map +1 -1
- package/dist/table-subscription.d.ts +27 -11
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +159 -25
- package/dist/table-subscription.js.map +1 -1
- package/dist/types.d.ts +34 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/src/auth.ts +55 -12
- package/src/bindings.ts +4 -1
- package/src/channel-watch.ts +86 -0
- package/src/errors.ts +54 -0
- package/src/exact-values.ts +101 -13
- package/src/field-kinds-registry.ts +2 -3
- package/src/index.ts +14 -2
- package/src/latest-rows.ts +24 -7
- package/src/public-env.ts +22 -0
- package/src/query-cache.ts +2 -1
- package/src/query.ts +12 -4
- package/src/realtime-refusals.ts +100 -0
- package/src/realtime.ts +385 -56
- package/src/runtime-env.ts +53 -5
- package/src/table-subscription.ts +190 -32
- package/src/types.ts +40 -1
- package/tests/auth-restore-user.test.ts +84 -0
- package/tests/auth-sso.test.ts +32 -1
- package/tests/auth.test.ts +11 -0
- package/tests/channel-watch-private.test.ts +105 -0
- package/tests/channel-watch.test.ts +97 -0
- package/tests/exact-response.test.ts +101 -0
- package/tests/exact-values.test.ts +57 -0
- package/tests/examples-runtime-env.test.ts +135 -0
- package/tests/field-kinds-registry.test.ts +12 -0
- package/tests/helpers/close-event.ts +12 -0
- package/tests/helpers/fake-client.ts +38 -0
- package/tests/helpers/mock-websocket.ts +22 -0
- package/tests/helpers/reactive-options-binding.ts +99 -0
- package/tests/public-env.test.ts +43 -0
- package/tests/query-cache.test.ts +1 -1
- package/tests/query.test.ts +39 -2
- package/tests/realtime-connection.test.ts +228 -0
- package/tests/realtime-exact-values.test.ts +42 -0
- package/tests/realtime-multi-tenant-integration.test.ts +0 -1
- package/tests/realtime-private-channels.test.ts +377 -0
- package/tests/realtime-refusal-error.test.ts +80 -0
- package/tests/realtime-rows-after-broadcast.test.ts +205 -0
- package/tests/realtime-session-auth.test.ts +0 -1
- package/tests/realtime-shared-channel.test.ts +9 -27
- package/tests/realtime-typed-channels.test.ts +49 -0
- package/tests/runtime-env-expo.test.ts +58 -0
- package/tests/runtime-env.test.ts +49 -0
- package/tests/subscribe-frame.test.ts +48 -0
- package/tests/table-subscription-rows.test.ts +136 -0
- package/tests/table-subscription.test.ts +4 -3
- package/tsconfig.json +2 -1
- package/tsconfig.tsbuildinfo +1 -1
- package/type-tests/declared-channels.ts +30 -0
- package/type-tests/tsconfig.json +4 -0
package/dist/realtime.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { asHeadersProvider, bearerToken } from "./query.js";
|
|
2
2
|
import { settle } from "./runtime-env.js";
|
|
3
|
-
import { coerceRecordKinds } from "./exact-values.js";
|
|
3
|
+
import { coerceRecordKinds, knownExactKinds } from "./exact-values.js";
|
|
4
|
+
import { PRIVATE_CHANNELS_FEATURE, channelRefusal, classifyRefusal, isActionRefusal, unsupportedServer, } from "./realtime-refusals.js";
|
|
4
5
|
import { isArrayOf, isJsonObject, isOneOf, isRecordOf, isShape, isString, nullable, optional } from "./json.js";
|
|
5
6
|
/**
|
|
6
7
|
* Turn the exact columns of one record into the types the generated schema declares.
|
|
@@ -44,6 +45,22 @@ function parseChannelName(name) {
|
|
|
44
45
|
return { schema: parts[0], table: parts[1] };
|
|
45
46
|
return { schema: "public", table: name };
|
|
46
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* The schema and table a listener on channel `name` is for.
|
|
50
|
+
*
|
|
51
|
+
* The name is read as `schema:table` only when it supplies the table as well. A listener that
|
|
52
|
+
* names its table and no schema means `public`, as the docs say. 0.9.1 release test (RB4): the
|
|
53
|
+
* schema was taken from the name whatever the listener said, so the documented
|
|
54
|
+
* `channel("post:42").on(..., { table: "comment" })` joined `post.comment`, reported SUBSCRIBED
|
|
55
|
+
* and delivered nothing. The server's `resolveTarget` reads a frame the same way.
|
|
56
|
+
*/
|
|
57
|
+
function listenerTarget(name, opts) {
|
|
58
|
+
if (opts.table === undefined) {
|
|
59
|
+
const named = parseChannelName(name);
|
|
60
|
+
return { schema: opts.schema ?? named.schema, table: named.table };
|
|
61
|
+
}
|
|
62
|
+
return { schema: opts.schema ?? "public", table: opts.table };
|
|
63
|
+
}
|
|
47
64
|
// Each guard is declared as the interface it checks, so the compiler holds the two to the same shape.
|
|
48
65
|
const isRecordOrNull = nullable(isJsonObject);
|
|
49
66
|
const isPresenceEntries = isArrayOf(isShape({ user_id: isString }));
|
|
@@ -52,7 +69,7 @@ const isChangeMessage = isShape({
|
|
|
52
69
|
channel: isString,
|
|
53
70
|
event: isOneOf(["INSERT", "UPDATE", "DELETE"]),
|
|
54
71
|
payload: isShape({ old: isRecordOrNull, new: isRecordOrNull }),
|
|
55
|
-
exactColumns: optional(isRecordOf(
|
|
72
|
+
exactColumns: optional(isRecordOf(isString)),
|
|
56
73
|
timestamp: isString,
|
|
57
74
|
});
|
|
58
75
|
const isPresenceMessage = isShape({
|
|
@@ -72,7 +89,9 @@ const isSystemMessage = isShape({
|
|
|
72
89
|
status: isOneOf(["ok", "error"]),
|
|
73
90
|
message: isString,
|
|
74
91
|
channel: optional(isString),
|
|
92
|
+
code: optional(isString),
|
|
75
93
|
ref: optional(isString),
|
|
94
|
+
features: optional(isArrayOf(isString)),
|
|
76
95
|
});
|
|
77
96
|
/** A frame from the realtime service (packages/realtime/src/types.ts) in one of the four shapes. */
|
|
78
97
|
function isServerMessage(value) {
|
|
@@ -80,6 +99,13 @@ function isServerMessage(value) {
|
|
|
80
99
|
}
|
|
81
100
|
/** How the server's acknowledgement of a join begins; the channel name follows. */
|
|
82
101
|
const SUBSCRIBED_TO = "subscribed to ";
|
|
102
|
+
/** The longest wait between reconnect attempts. Without it ten doublings from one second reach 512 s. */
|
|
103
|
+
const MAX_RECONNECT_DELAY_MS = 30_000;
|
|
104
|
+
/**
|
|
105
|
+
* How long a socket may stay CONNECTING. One opened while realtime restarts behind the gateway can
|
|
106
|
+
* stay there with no error and no close, and the client would wait on it for good.
|
|
107
|
+
*/
|
|
108
|
+
const CONNECT_TIMEOUT_MS = 10_000;
|
|
83
109
|
// ─── Realtime client ─────────────────────────────────────────────────────────
|
|
84
110
|
export class RealtimeClient {
|
|
85
111
|
base;
|
|
@@ -90,6 +116,8 @@ export class RealtimeClient {
|
|
|
90
116
|
reconnectAttempts = 0;
|
|
91
117
|
maxReconnectAttempts = 10;
|
|
92
118
|
baseReconnectDelay = 1000;
|
|
119
|
+
connection = "disconnected";
|
|
120
|
+
connectionListeners = new Set();
|
|
93
121
|
/** The token the live socket was opened with, so an auth change can tell whether it still holds. */
|
|
94
122
|
currentToken;
|
|
95
123
|
/**
|
|
@@ -104,6 +132,11 @@ export class RealtimeClient {
|
|
|
104
132
|
attempt = null;
|
|
105
133
|
/** The last `ref` a join was sent with. Unique for the life of the client, across sockets. */
|
|
106
134
|
lastRef = 0;
|
|
135
|
+
/**
|
|
136
|
+
* What the server on the live socket announced on its first frame: undefined until that frame
|
|
137
|
+
* arrives, an empty set for a server that announces nothing (one that predates private channels).
|
|
138
|
+
*/
|
|
139
|
+
serverFeatures;
|
|
107
140
|
/**
|
|
108
141
|
* `auth` is either a headers provider or a fixed set of headers: the same pair `QueryBuilder` and
|
|
109
142
|
* `MutationBuilder` accept, normalised by the same helper.
|
|
@@ -117,6 +150,37 @@ export class RealtimeClient {
|
|
|
117
150
|
this.base = url;
|
|
118
151
|
this.getHeaders = asHeadersProvider(auth);
|
|
119
152
|
}
|
|
153
|
+
/** The socket's own state. A channel's status cannot say this: it reads SUBSCRIBING for a drop and a first connect alike. */
|
|
154
|
+
get connectionState() {
|
|
155
|
+
return this.connection;
|
|
156
|
+
}
|
|
157
|
+
/** True while the socket is open. A channel may still be waiting on its join. */
|
|
158
|
+
get isConnected() {
|
|
159
|
+
return this.connection === "connected";
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Call `listener` each time the connection state changes. It is not called with the current state
|
|
163
|
+
* on registering: read `connectionState` or `isConnected` for that. Returns a function that stops it.
|
|
164
|
+
*/
|
|
165
|
+
onConnectionChange(listener) {
|
|
166
|
+
this.connectionListeners.add(listener);
|
|
167
|
+
return () => {
|
|
168
|
+
this.connectionListeners.delete(listener);
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
setConnection(next) {
|
|
172
|
+
if (this.connection === next)
|
|
173
|
+
return;
|
|
174
|
+
this.connection = next;
|
|
175
|
+
for (const listener of [...this.connectionListeners]) {
|
|
176
|
+
try {
|
|
177
|
+
listener(next);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
// One listener's bug must not stop the others hearing, or stop the socket doing its work.
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
120
184
|
/** The socket's address, as ws(s) for an http(s) one. Read when connecting, not before. */
|
|
121
185
|
get url() {
|
|
122
186
|
return settle(this.base).replace(/^http/, "ws");
|
|
@@ -181,6 +245,7 @@ export class RealtimeClient {
|
|
|
181
245
|
const old = this.ws;
|
|
182
246
|
this.ws = null;
|
|
183
247
|
this.currentToken = undefined;
|
|
248
|
+
this.serverFeatures = undefined;
|
|
184
249
|
if (old !== null) {
|
|
185
250
|
old.onopen = null;
|
|
186
251
|
old.onmessage = null;
|
|
@@ -207,17 +272,8 @@ export class RealtimeClient {
|
|
|
207
272
|
state.joined = undefined;
|
|
208
273
|
state.joining = undefined;
|
|
209
274
|
state.joinRef = undefined;
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
}
|
|
213
|
-
forgetMembers(state) {
|
|
214
|
-
if (state.members.length === 0)
|
|
215
|
-
return;
|
|
216
|
-
const leaves = state.members;
|
|
217
|
-
state.members = [];
|
|
218
|
-
for (const handle of state.handles) {
|
|
219
|
-
for (const listener of handle.presenceListeners)
|
|
220
|
-
listener({ joins: [], leaves });
|
|
275
|
+
state.joinedPrivate = false;
|
|
276
|
+
forgetMembers(state);
|
|
221
277
|
}
|
|
222
278
|
}
|
|
223
279
|
/**
|
|
@@ -229,28 +285,30 @@ export class RealtimeClient {
|
|
|
229
285
|
* `useSubscription` hooks with one channel name broke each other when either unmounted. The join
|
|
230
286
|
* is now left only when the last handle on the name unsubscribes.
|
|
231
287
|
*/
|
|
232
|
-
channel(name) {
|
|
288
|
+
channel(name, opts = {}) {
|
|
233
289
|
const state = this.getOrCreateChannel(name);
|
|
234
290
|
const handle = {
|
|
235
291
|
pgListeners: [],
|
|
236
292
|
presenceListeners: [],
|
|
237
293
|
broadcastListeners: new Map(),
|
|
294
|
+
refusalListeners: [],
|
|
238
295
|
statusCallback: null,
|
|
296
|
+
private: opts.private === true,
|
|
239
297
|
};
|
|
240
298
|
state.handles.add(handle);
|
|
241
299
|
const sub = {
|
|
242
|
-
on(_event, opts, callback) {
|
|
243
|
-
//
|
|
244
|
-
//
|
|
245
|
-
// named `app:orders` was registered against `public.orders`.
|
|
246
|
-
const named = parseChannelName(name);
|
|
300
|
+
on: (_event, opts, callback) => {
|
|
301
|
+
// A channel named `app:orders` with no table on the listener is `app.orders`, the way the
|
|
302
|
+
// server's fallback reads it; a listener naming its table defaults to `public`.
|
|
247
303
|
handle.pgListeners.push({
|
|
248
304
|
event: opts.event,
|
|
249
|
-
|
|
250
|
-
table: opts.table ?? named.table,
|
|
305
|
+
...listenerTarget(name, opts),
|
|
251
306
|
filter: opts.filter,
|
|
252
307
|
callback: forCallerRows(callback),
|
|
253
308
|
});
|
|
309
|
+
// A join already sent for broadcast or presence alone delivers no rows, and `subscribe()`
|
|
310
|
+
// will not send another, so the first row listener on it joins again here.
|
|
311
|
+
this.rejoinIfUnheard(state);
|
|
254
312
|
return sub;
|
|
255
313
|
},
|
|
256
314
|
onPresence(callback) {
|
|
@@ -263,14 +321,24 @@ export class RealtimeClient {
|
|
|
263
321
|
handle.broadcastListeners.set(event, listeners);
|
|
264
322
|
return sub;
|
|
265
323
|
},
|
|
324
|
+
onRefused(callback) {
|
|
325
|
+
handle.refusalListeners.push(callback);
|
|
326
|
+
return sub;
|
|
327
|
+
},
|
|
266
328
|
subscribe: (callback) => {
|
|
267
329
|
handle.statusCallback = callback ?? null;
|
|
268
330
|
// Joining twice is a no-op rather than a second frame, so `from(table).subscribe()` can
|
|
269
331
|
// join on its own and a caller can still call this afterwards just to watch the status.
|
|
270
332
|
// A join already acknowledged will not be acknowledged again, so say so here or the new
|
|
271
333
|
// callback waits for a SUBSCRIBED that is never coming.
|
|
272
|
-
if (state.subscribed)
|
|
334
|
+
if (state.subscribed && serves(state.joined, handle))
|
|
273
335
|
callback?.("SUBSCRIBED");
|
|
336
|
+
// An app subscribing again after a withdrawal is asking to try the join again.
|
|
337
|
+
if (state.withdrawn) {
|
|
338
|
+
state.withdrawn = false;
|
|
339
|
+
state.joinSent = false;
|
|
340
|
+
}
|
|
341
|
+
this.rejoinForPrivacy(state);
|
|
274
342
|
this.ensureConnection();
|
|
275
343
|
this.sendSubscribe(state);
|
|
276
344
|
return sub;
|
|
@@ -333,6 +401,7 @@ export class RealtimeClient {
|
|
|
333
401
|
*/
|
|
334
402
|
disconnect() {
|
|
335
403
|
this.abandonSocket("client disconnect");
|
|
404
|
+
this.setConnection("disconnected");
|
|
336
405
|
this.notifyChannels("CLOSED");
|
|
337
406
|
}
|
|
338
407
|
// ─── Internal ──────────────────────────────────────────────────────────
|
|
@@ -347,6 +416,9 @@ export class RealtimeClient {
|
|
|
347
416
|
joined: undefined,
|
|
348
417
|
joining: undefined,
|
|
349
418
|
joinRef: undefined,
|
|
419
|
+
joinedPrivate: false,
|
|
420
|
+
withdrawn: false,
|
|
421
|
+
unsupported: false,
|
|
350
422
|
members: [],
|
|
351
423
|
};
|
|
352
424
|
this.channels.set(name, state);
|
|
@@ -367,6 +439,7 @@ export class RealtimeClient {
|
|
|
367
439
|
// Read here, synchronously, so a client with no address or anon key throws from the subscribe
|
|
368
440
|
// that asked for the socket rather than from a background attempt nobody is waiting on.
|
|
369
441
|
const url = this.url;
|
|
442
|
+
this.setConnection("connecting");
|
|
370
443
|
let attempt;
|
|
371
444
|
const isCurrent = () => this.attempt === attempt;
|
|
372
445
|
// Started on a microtask so `this.attempt` is assigned before `openSocket` can ask whether it
|
|
@@ -409,11 +482,18 @@ export class RealtimeClient {
|
|
|
409
482
|
if (!isCurrent())
|
|
410
483
|
return;
|
|
411
484
|
this.currentToken = token;
|
|
485
|
+
this.serverFeatures = undefined;
|
|
412
486
|
const wsUrl = token ? `${url}?token=${encodeURIComponent(token)}` : url;
|
|
413
487
|
const ws = new WebSocket(wsUrl);
|
|
414
488
|
this.ws = ws;
|
|
489
|
+
const handshake = setTimeout(() => {
|
|
490
|
+
if (ws.readyState === WebSocket.CONNECTING)
|
|
491
|
+
this.socketLost(ws);
|
|
492
|
+
}, CONNECT_TIMEOUT_MS);
|
|
415
493
|
ws.onopen = () => {
|
|
494
|
+
clearTimeout(handshake);
|
|
416
495
|
this.reconnectAttempts = 0;
|
|
496
|
+
this.setConnection("connected");
|
|
417
497
|
// Re-subscribe all channels
|
|
418
498
|
for (const state of this.channels.values()) {
|
|
419
499
|
if (!state.subscribed) {
|
|
@@ -432,25 +512,41 @@ export class RealtimeClient {
|
|
|
432
512
|
// Ignore unparseable messages
|
|
433
513
|
}
|
|
434
514
|
};
|
|
435
|
-
ws.onclose = () =>
|
|
436
|
-
this.ws = null;
|
|
437
|
-
this.forgetJoins();
|
|
438
|
-
// Attempt reconnection with exponential backoff
|
|
439
|
-
if (this.channels.size > 0) {
|
|
440
|
-
this.scheduleReconnect();
|
|
441
|
-
}
|
|
442
|
-
};
|
|
515
|
+
ws.onclose = () => this.socketLost(ws);
|
|
443
516
|
ws.onerror = () => {
|
|
444
|
-
//
|
|
517
|
+
// An open socket's error is followed by its close. One that never opened may not be: Node's
|
|
518
|
+
// built-in WebSocket, refused by a gateway answering 502, fires error and then nothing, and
|
|
519
|
+
// counted as live it was never replaced. So that one is dropped here.
|
|
520
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
521
|
+
this.socketLost(ws);
|
|
445
522
|
};
|
|
446
523
|
}
|
|
524
|
+
/** `ws` closed or failed to open: forget it and reconnect with backoff, once per socket. */
|
|
525
|
+
socketLost(ws) {
|
|
526
|
+
if (this.ws !== ws)
|
|
527
|
+
return;
|
|
528
|
+
ws.onclose = null;
|
|
529
|
+
ws.onerror = null;
|
|
530
|
+
if (ws.readyState !== WebSocket.CLOSED)
|
|
531
|
+
ws.close();
|
|
532
|
+
this.ws = null;
|
|
533
|
+
this.forgetJoins();
|
|
534
|
+
if (this.channels.size > 0) {
|
|
535
|
+
this.scheduleReconnect();
|
|
536
|
+
}
|
|
537
|
+
else {
|
|
538
|
+
this.setConnection("disconnected");
|
|
539
|
+
}
|
|
540
|
+
}
|
|
447
541
|
scheduleReconnect() {
|
|
448
542
|
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
543
|
+
this.setConnection("disconnected");
|
|
449
544
|
this.notifyChannels("TIMED_OUT");
|
|
450
545
|
return;
|
|
451
546
|
}
|
|
452
|
-
const delay = this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts);
|
|
547
|
+
const delay = Math.min(MAX_RECONNECT_DELAY_MS, this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts));
|
|
453
548
|
this.reconnectAttempts++;
|
|
549
|
+
this.setConnection("connecting");
|
|
454
550
|
this.notifyChannels("SUBSCRIBING");
|
|
455
551
|
this.reconnectTimer = setTimeout(() => {
|
|
456
552
|
this.ensureConnection();
|
|
@@ -473,6 +569,10 @@ export class RealtimeClient {
|
|
|
473
569
|
}
|
|
474
570
|
}
|
|
475
571
|
handleSystem(msg) {
|
|
572
|
+
if (this.serverFeatures === undefined && msg.status === "ok" && !msg.message.startsWith(SUBSCRIBED_TO)) {
|
|
573
|
+
this.serverFeatures = new Set(msg.features ?? []);
|
|
574
|
+
this.joinWaitingChannels();
|
|
575
|
+
}
|
|
476
576
|
if (msg.status === "ok" && msg.message.startsWith(SUBSCRIBED_TO)) {
|
|
477
577
|
const state = this.answeredJoin(msg.message.slice(SUBSCRIBED_TO.length), msg.ref);
|
|
478
578
|
if (state !== undefined)
|
|
@@ -502,17 +602,35 @@ export class RealtimeClient {
|
|
|
502
602
|
* whose refused join it has since replaced, is told nothing.
|
|
503
603
|
*/
|
|
504
604
|
handleRefusal(msg) {
|
|
605
|
+
const kind = msg.channel === undefined ? undefined : classifyRefusal(msg.code, msg.message);
|
|
606
|
+
// A refused send is not a failed channel: it goes to `onRefused` and the status stays as it was.
|
|
607
|
+
if (msg.channel !== undefined && kind !== undefined && isActionRefusal(kind)) {
|
|
608
|
+
refuseAction(this.channels.get(msg.channel), { channel: msg.channel, code: kind, message: msg.message });
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
505
611
|
const affected = msg.channel === undefined ? [...this.channels.values()] : [this.answeredJoin(msg.channel, msg.ref)];
|
|
506
612
|
for (const state of affected) {
|
|
507
613
|
if (state === undefined)
|
|
508
614
|
continue;
|
|
615
|
+
const refusal = msg.channel === undefined || kind === undefined
|
|
616
|
+
? new Error(msg.message)
|
|
617
|
+
: channelRefusal(msg.channel, msg.message, kind);
|
|
618
|
+
if (msg.channel !== undefined && state.subscribed) {
|
|
619
|
+
if (kind === "withdrawn")
|
|
620
|
+
withdrawJoin(state, refusal);
|
|
621
|
+
else
|
|
622
|
+
refuseRejoin(state, refusal);
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
509
625
|
// A refused join registered nothing on the server, so a channel not yet confirmed may
|
|
510
626
|
// join again on this socket. Marked as sent, a retry after authenticating sent nothing.
|
|
511
627
|
if (!state.subscribed)
|
|
512
628
|
state.joinSent = false;
|
|
513
629
|
if (msg.ref !== undefined)
|
|
514
630
|
state.joinRef = undefined;
|
|
515
|
-
|
|
631
|
+
// The server's reason goes to the callback (N-FF5): "table public.notes does not exist"
|
|
632
|
+
// tells the developer what to fix, and a bare CHANNEL_ERROR did not.
|
|
633
|
+
notifyHandles(state, "CHANNEL_ERROR", refusal);
|
|
516
634
|
}
|
|
517
635
|
}
|
|
518
636
|
handleChange(msg) {
|
|
@@ -522,7 +640,7 @@ export class RealtimeClient {
|
|
|
522
640
|
// A bigint column arrives as a string and becomes a native bigint here, and a numeric stays
|
|
523
641
|
// the exact string `@supatype/types` declares for Decimal and Money. The same coercion the
|
|
524
642
|
// REST path uses, so a row read either way holds the same values.
|
|
525
|
-
const exact = msg.exactColumns ?? {};
|
|
643
|
+
const exact = knownExactKinds(msg.exactColumns ?? {});
|
|
526
644
|
const newRecord = coerceRecord(msg.payload.new, exact);
|
|
527
645
|
const oldRecord = coerceRecord(msg.payload.old, exact);
|
|
528
646
|
// The channel is subscribed to the table `sendSubscribe` registered, so a change is that
|
|
@@ -574,35 +692,85 @@ export class RealtimeClient {
|
|
|
574
692
|
return;
|
|
575
693
|
if (state.joinSent)
|
|
576
694
|
return;
|
|
695
|
+
const asPrivate = isPrivate(state);
|
|
696
|
+
if (asPrivate && !this.mayJoinPrivately(state))
|
|
697
|
+
return;
|
|
577
698
|
state.joinSent = true;
|
|
699
|
+
state.joinedPrivate = asPrivate;
|
|
578
700
|
const target = joinTargetOf(state);
|
|
579
701
|
state.joining = target;
|
|
580
702
|
// A first join's rows are its own from the start. A join sent again on this socket replaces one
|
|
581
703
|
// the server delivers for until it acknowledges this one, so the old target stays until then.
|
|
582
704
|
state.joined ??= target;
|
|
583
705
|
state.joinRef = String(++this.lastRef);
|
|
584
|
-
this.sendMessage(subscribeFrame(state.name, target, state.joinRef));
|
|
706
|
+
this.sendMessage(subscribeFrame(state.name, target, state.joinRef, asPrivate));
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Whether a private join may be sent on this socket now.
|
|
710
|
+
*
|
|
711
|
+
* Not before the server's first frame says what it can do: the join waits for it. And not at all
|
|
712
|
+
* to a server that does not announce `private_channels`: it would ignore the flag and admit an
|
|
713
|
+
* open channel, so the join is failed here instead and never sent.
|
|
714
|
+
*/
|
|
715
|
+
mayJoinPrivately(state) {
|
|
716
|
+
if (this.serverFeatures === undefined)
|
|
717
|
+
return false;
|
|
718
|
+
if (this.serverFeatures.has(PRIVATE_CHANNELS_FEATURE))
|
|
719
|
+
return true;
|
|
720
|
+
if (!state.unsupported) {
|
|
721
|
+
state.unsupported = true;
|
|
722
|
+
notifyHandles(state, "CHANNEL_ERROR", unsupportedServer(state.name));
|
|
723
|
+
}
|
|
724
|
+
return false;
|
|
725
|
+
}
|
|
726
|
+
/** The server's first frame has arrived: send the joins that were waiting for it. */
|
|
727
|
+
joinWaitingChannels() {
|
|
728
|
+
for (const state of this.channels.values()) {
|
|
729
|
+
state.unsupported = false;
|
|
730
|
+
if (!state.subscribed)
|
|
731
|
+
this.sendSubscribe(state);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* A handle asking for `private: true` on a name already joined as open joins again as private,
|
|
736
|
+
* in place, as `rejoinIfUnheard` does: the open join stands until the server takes the new one.
|
|
737
|
+
*/
|
|
738
|
+
rejoinForPrivacy(state) {
|
|
739
|
+
if (state.joinSent && !state.joinedPrivate && isPrivate(state)) {
|
|
740
|
+
state.joinSent = false;
|
|
741
|
+
if (state.subscribed)
|
|
742
|
+
notifyUnserved(state, "SUBSCRIBING");
|
|
743
|
+
}
|
|
585
744
|
}
|
|
586
745
|
/**
|
|
587
|
-
* Join `state` again when
|
|
746
|
+
* Join `state` again when the join it holds delivers rows to no listener left on it.
|
|
588
747
|
*
|
|
589
748
|
* Handles share one join, made for the oldest row listener. When that listener's handle left, the
|
|
590
749
|
* join stayed registered for its table, and every other handle reported SUBSCRIBED and was sent
|
|
591
|
-
* nothing.
|
|
592
|
-
*
|
|
593
|
-
*
|
|
750
|
+
* nothing. A join sent before any row listener asked for no rows, so a row listener added after it
|
|
751
|
+
* was never sent any either (0.9.2 release test, FF-1). Joined again in place, without leaving
|
|
752
|
+
* first: the server replaces a channel's subscription on a second join, where leaving would drop
|
|
753
|
+
* the presence this socket tracks there.
|
|
754
|
+
*
|
|
755
|
+
* An acknowledged join stays registered and serving until the server takes this one, and for good
|
|
756
|
+
* if it refuses it. So the handles it serves stay SUBSCRIBED and its members stay present, and
|
|
757
|
+
* only a handle it does not serve is told SUBSCRIBING. Every handle used to be, and a refused
|
|
758
|
+
* rejoin then left them all in CHANNEL_ERROR with broadcast still arriving (0.9.2 round 4, S-1).
|
|
594
759
|
*/
|
|
595
760
|
rejoinIfUnheard(state) {
|
|
596
761
|
const held = state.joining ?? state.joined;
|
|
597
762
|
if (!state.joinSent || held === undefined)
|
|
598
763
|
return;
|
|
599
764
|
const listeners = pgListenersOf(state);
|
|
600
|
-
if (listeners.length === 0
|
|
765
|
+
if (listeners.length === 0)
|
|
766
|
+
return;
|
|
767
|
+
if (held.rows && listeners.some((listener) => sameJoin(listener, held)))
|
|
601
768
|
return;
|
|
602
|
-
state.subscribed = false;
|
|
603
769
|
state.joinSent = false;
|
|
604
|
-
|
|
605
|
-
|
|
770
|
+
if (state.subscribed)
|
|
771
|
+
notifyUnserved(state, "SUBSCRIBING");
|
|
772
|
+
else
|
|
773
|
+
notifyHandles(state, "SUBSCRIBING");
|
|
606
774
|
this.sendSubscribe(state);
|
|
607
775
|
}
|
|
608
776
|
sendUnsubscribe(state) {
|
|
@@ -621,9 +789,10 @@ export class RealtimeClient {
|
|
|
621
789
|
*/
|
|
622
790
|
function joinTargetOf(state) {
|
|
623
791
|
const first = pgListenersOf(state)[0];
|
|
624
|
-
if (first !== undefined)
|
|
625
|
-
return { schema: first.schema, table: first.table, event: first.event, filter: first.filter };
|
|
626
|
-
|
|
792
|
+
if (first !== undefined) {
|
|
793
|
+
return { schema: first.schema, table: first.table, event: first.event, filter: first.filter, rows: true };
|
|
794
|
+
}
|
|
795
|
+
return { ...parseChannelName(state.name), event: "*", filter: undefined, rows: false };
|
|
627
796
|
}
|
|
628
797
|
/** Whether a listener is for exactly what a join registered. */
|
|
629
798
|
function sameJoin(listener, join) {
|
|
@@ -646,15 +815,20 @@ function pgListenersOf(state) {
|
|
|
646
815
|
* `lobby-chat` carrying `table: "chat_message"` (which is what `useSubscription` exists to let you
|
|
647
816
|
* write), registered against a table no change can match. The socket reported SUBSCRIBED and
|
|
648
817
|
* delivered nothing, which is indistinguishable from a quiet table.
|
|
818
|
+
*
|
|
819
|
+
* `changes` says whether the join has a row listener. Only a row join has its table checked and is
|
|
820
|
+
* sent row changes: broadcast and presence on `room:x` were refused as a join for room.x (R2-RB2).
|
|
649
821
|
*/
|
|
650
|
-
function subscribeFrame(channel, target, ref) {
|
|
822
|
+
function subscribeFrame(channel, target, ref, asPrivate) {
|
|
651
823
|
return {
|
|
652
824
|
type: "subscribe",
|
|
653
825
|
channel,
|
|
654
826
|
event: target.event,
|
|
655
827
|
table: target.table,
|
|
656
828
|
schema: target.schema,
|
|
829
|
+
changes: target.rows,
|
|
657
830
|
filter: filterFrame(target.filter),
|
|
831
|
+
...(asPrivate && { private: true }),
|
|
658
832
|
ref,
|
|
659
833
|
};
|
|
660
834
|
}
|
|
@@ -670,19 +844,98 @@ function filterFrame(filter) {
|
|
|
670
844
|
}
|
|
671
845
|
return Object.keys(parsed).length > 0 ? parsed : undefined;
|
|
672
846
|
}
|
|
673
|
-
/**
|
|
847
|
+
/**
|
|
848
|
+
* The server took the join `state` was waiting on: from now on its rows are that join's.
|
|
849
|
+
*
|
|
850
|
+
* Over a join it had acknowledged, the server tells the new join who is present all over again,
|
|
851
|
+
* straight after this reply, so the members known now leave first. The handles the old join served
|
|
852
|
+
* were never told otherwise than SUBSCRIBED, so only the others are told it now.
|
|
853
|
+
*/
|
|
674
854
|
function acknowledgeJoin(state) {
|
|
855
|
+
const replaced = state.subscribed;
|
|
856
|
+
if (replaced) {
|
|
857
|
+
forgetMembers(state);
|
|
858
|
+
notifyUnserved(state, "SUBSCRIBED");
|
|
859
|
+
}
|
|
675
860
|
state.subscribed = true;
|
|
676
861
|
if (state.joining !== undefined)
|
|
677
862
|
state.joined = state.joining;
|
|
678
863
|
state.joining = undefined;
|
|
679
864
|
state.joinRef = undefined;
|
|
680
|
-
|
|
865
|
+
if (!replaced)
|
|
866
|
+
notifyHandles(state, "SUBSCRIBED");
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* The server refused a rejoin, so the acknowledged join it was to replace still stands, and stays
|
|
870
|
+
* the one this socket holds. Only a handle with a row listener it does not serve gets the refusal.
|
|
871
|
+
*/
|
|
872
|
+
function refuseRejoin(state, refusal) {
|
|
873
|
+
state.joinSent = true;
|
|
874
|
+
state.joining = undefined;
|
|
875
|
+
state.joinRef = undefined;
|
|
876
|
+
notifyUnserved(state, "CHANNEL_ERROR", refusal);
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* Whether `join` delivers rows to every row listener of `handle`, as `handleChange` routes them: by
|
|
880
|
+
* the join's table. Always, for a handle listening for none.
|
|
881
|
+
*/
|
|
882
|
+
function serves(join, handle) {
|
|
883
|
+
return handle.pgListeners.every((listener) => join?.rows === true && listener.schema === join.schema && listener.table === join.table);
|
|
884
|
+
}
|
|
885
|
+
/** Whether any handle on the channel asked for `private: true`: the shared join then does. */
|
|
886
|
+
function isPrivate(state) {
|
|
887
|
+
for (const handle of state.handles)
|
|
888
|
+
if (handle.private)
|
|
889
|
+
return true;
|
|
890
|
+
return false;
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* The server removed this client from a channel it held: the token changed, a re-check ran, or the
|
|
894
|
+
* declaration went. Every handle is told, and the client does not join again by itself, since the
|
|
895
|
+
* server would refuse it again. The app joins again by subscribing again.
|
|
896
|
+
*/
|
|
897
|
+
function withdrawJoin(state, refusal) {
|
|
898
|
+
state.subscribed = false;
|
|
899
|
+
state.joinSent = true;
|
|
900
|
+
state.withdrawn = true;
|
|
901
|
+
state.joined = undefined;
|
|
902
|
+
state.joining = undefined;
|
|
903
|
+
state.joinRef = undefined;
|
|
904
|
+
state.joinedPrivate = false;
|
|
905
|
+
forgetMembers(state);
|
|
906
|
+
notifyHandles(state, "CHANNEL_ERROR", refusal);
|
|
907
|
+
}
|
|
908
|
+
/** Hand a refused send, track or payload to the `onRefused` listeners of every handle on the channel. */
|
|
909
|
+
function refuseAction(state, refusal) {
|
|
910
|
+
if (state === undefined)
|
|
911
|
+
return;
|
|
912
|
+
for (const handle of state.handles) {
|
|
913
|
+
for (const listener of handle.refusalListeners)
|
|
914
|
+
listener(refusal);
|
|
915
|
+
}
|
|
681
916
|
}
|
|
682
917
|
/** Tell each handle on a channel its status. */
|
|
683
|
-
function notifyHandles(state, status) {
|
|
918
|
+
function notifyHandles(state, status, err) {
|
|
684
919
|
for (const handle of state.handles)
|
|
685
|
-
handle.statusCallback?.(status);
|
|
920
|
+
handle.statusCallback?.(status, err);
|
|
921
|
+
}
|
|
922
|
+
/** Tell its status to each handle the join `state` holds does not serve. */
|
|
923
|
+
function notifyUnserved(state, status, err) {
|
|
924
|
+
for (const handle of state.handles) {
|
|
925
|
+
if (!serves(state.joined, handle))
|
|
926
|
+
handle.statusCallback?.(status, err);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
/** Every member this socket was told of leaves, as the next join is told them all again. */
|
|
930
|
+
function forgetMembers(state) {
|
|
931
|
+
if (state.members.length === 0)
|
|
932
|
+
return;
|
|
933
|
+
const leaves = state.members;
|
|
934
|
+
state.members = [];
|
|
935
|
+
for (const handle of state.handles) {
|
|
936
|
+
for (const listener of handle.presenceListeners)
|
|
937
|
+
listener({ joins: [], leaves });
|
|
938
|
+
}
|
|
686
939
|
}
|
|
687
940
|
/** `members` with one entry removed per leave: a user on two tabs is two entries and leaves twice. */
|
|
688
941
|
function withoutLeaves(members, leaves) {
|