@supatype/client 0.9.2 → 0.10.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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +98 -75
- package/.turbo/turbo-typecheck.log +2 -2
- package/CHANGELOG.md +123 -20
- package/README.md +18 -0
- package/dist/auth.d.ts +4 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +38 -13
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +3 -0
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +1 -0
- 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 +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.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.js +1 -1
- 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 +70 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +198 -18
- 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 +5 -0
- package/dist/runtime-env.js.map +1 -1
- package/dist/table-subscription.d.ts +23 -9
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +155 -23
- package/dist/table-subscription.js.map +1 -1
- package/dist/types.d.ts +29 -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 +40 -12
- package/src/bindings.ts +3 -0
- 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 +13 -1
- package/src/public-env.ts +22 -0
- package/src/query-cache.ts +2 -1
- package/src/query.ts +1 -1
- package/src/realtime-refusals.ts +100 -0
- package/src/realtime.ts +256 -20
- package/src/runtime-env.ts +6 -0
- package/src/table-subscription.ts +186 -30
- package/src/types.ts +35 -1
- package/tests/auth-restore-user.test.ts +84 -0
- 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/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/public-env.test.ts +43 -0
- package/tests/query-cache.test.ts +1 -1
- package/tests/realtime-connection.test.ts +228 -0
- package/tests/realtime-exact-values.test.ts +42 -0
- package/tests/realtime-private-channels.test.ts +377 -0
- package/tests/realtime-refusal-error.test.ts +2 -1
- package/tests/realtime-typed-channels.test.ts +49 -0
- package/tests/runtime-env.test.ts +14 -0
- package/tests/table-subscription-rows.test.ts +136 -0
- package/tests/table-subscription.test.ts +4 -3
- package/tsconfig.tsbuildinfo +1 -1
- package/type-tests/declared-channels.ts +30 -0
- package/type-tests/tsconfig.json +4 -0
package/src/realtime.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import { asHeadersProvider, bearerToken, type HeadersProvider } from "./query.js"
|
|
2
2
|
import { settle, type Deferred } from "./runtime-env.js"
|
|
3
|
-
import {
|
|
3
|
+
import type { ChannelName } from "./types.js"
|
|
4
|
+
import { coerceRecordKinds, knownExactKinds, type ExactFields } from "./exact-values.js"
|
|
5
|
+
import {
|
|
6
|
+
PRIVATE_CHANNELS_FEATURE,
|
|
7
|
+
channelRefusal,
|
|
8
|
+
classifyRefusal,
|
|
9
|
+
isActionRefusal,
|
|
10
|
+
unsupportedServer,
|
|
11
|
+
type ChannelActionRefusal,
|
|
12
|
+
} from "./realtime-refusals.js"
|
|
4
13
|
import { isArrayOf, isJsonObject, isOneOf, isRecordOf, isShape, isString, nullable, optional, type Guard } from "./json.js"
|
|
5
14
|
|
|
6
15
|
export type RealtimeEvent = "INSERT" | "UPDATE" | "DELETE" | "*"
|
|
@@ -18,6 +27,18 @@ type RealtimeCallback<TRow> = (payload: RealtimePayload<TRow>) => void
|
|
|
18
27
|
|
|
19
28
|
export type ChannelStatus = "SUBSCRIBED" | "SUBSCRIBING" | "CLOSED" | "CHANNEL_ERROR" | "TIMED_OUT"
|
|
20
29
|
|
|
30
|
+
/**
|
|
31
|
+
* The socket itself, as opposed to any one channel's join on it.
|
|
32
|
+
*
|
|
33
|
+
* "connected": the socket is open. "connecting": it is opening for the first time, reopening after
|
|
34
|
+
* a drop or a sign-in swap, or waiting out a backoff. "disconnected": nothing is open and nothing
|
|
35
|
+
* is scheduled, because no channel has subscribed, disconnect() was called, or every retry failed.
|
|
36
|
+
*/
|
|
37
|
+
export type RealtimeConnectionState = "connected" | "connecting" | "disconnected"
|
|
38
|
+
|
|
39
|
+
/** Called each time the connection state changes, with the new state. */
|
|
40
|
+
export type RealtimeConnectionListener = (state: RealtimeConnectionState) => void
|
|
41
|
+
|
|
21
42
|
/**
|
|
22
43
|
* Told each status a channel reaches. `err` carries the server's reason with a CHANNEL_ERROR it
|
|
23
44
|
* refused, such as a join for a table that does not exist, and is undefined otherwise: the same
|
|
@@ -25,7 +46,24 @@ export type ChannelStatus = "SUBSCRIBED" | "SUBSCRIBING" | "CLOSED" | "CHANNEL_E
|
|
|
25
46
|
*/
|
|
26
47
|
export type ChannelStatusCallback = (status: ChannelStatus, err?: Error | undefined) => void
|
|
27
48
|
|
|
28
|
-
|
|
49
|
+
/** What a channel can be opened with. */
|
|
50
|
+
export interface ChannelOptions {
|
|
51
|
+
/**
|
|
52
|
+
* Assert that this channel is private: guarded by a `Channel` declaration in the schema.
|
|
53
|
+
*
|
|
54
|
+
* The server enforces every declared channel whether or not this is set, so it never loosens
|
|
55
|
+
* anything. What it adds is two refusals instead of two silent open channels. A name no
|
|
56
|
+
* declaration matches is refused (`RealtimeChannelError` reason `not_declared`), which catches a
|
|
57
|
+
* typo at once. And a server that does not announce private channel support is not asked at all
|
|
58
|
+
* (reason `unsupported_server`), since an older server would ignore the flag and admit an open
|
|
59
|
+
* channel. Both arrive as `CHANNEL_ERROR` on the status callback.
|
|
60
|
+
*
|
|
61
|
+
* Handles on one channel name share one join: if any handle says `private: true`, the join does.
|
|
62
|
+
*/
|
|
63
|
+
private?: boolean | undefined
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface ChannelSubscription<TRow> {
|
|
29
67
|
on(
|
|
30
68
|
event: "postgres_changes",
|
|
31
69
|
opts: {
|
|
@@ -45,6 +83,12 @@ interface ChannelSubscription<TRow> {
|
|
|
45
83
|
event: string,
|
|
46
84
|
callback: (payload: Record<string, unknown>) => void,
|
|
47
85
|
): ChannelSubscription<TRow>
|
|
86
|
+
/**
|
|
87
|
+
* Listen for a broadcast, presence track or payload the server refused on this channel (a
|
|
88
|
+
* `ChannelActionRefusal`: `send_denied`, `track_denied` or `payload_refused`). The channel is
|
|
89
|
+
* still joined, so its status does not change; this is where the app learns its send went nowhere.
|
|
90
|
+
*/
|
|
91
|
+
onRefused(callback: (refusal: ChannelActionRefusal) => void): ChannelSubscription<TRow>
|
|
48
92
|
/** Subscribe to the channel, opening the WebSocket if needed. */
|
|
49
93
|
subscribe(callback?: ChannelStatusCallback | undefined): ChannelSubscription<TRow>
|
|
50
94
|
/** Unsubscribe and clean up. */
|
|
@@ -142,8 +186,11 @@ interface ServerChangeMessage {
|
|
|
142
186
|
*
|
|
143
187
|
* The service reads them from the database's own declared types, so this is authoritative in a
|
|
144
188
|
* way the local registry is not: a project that never generated still gets the right value.
|
|
189
|
+
*
|
|
190
|
+
* The kind is any string: one this client does not know is ignored, and that column passes through
|
|
191
|
+
* as sent, so a kind added later never drops a change.
|
|
145
192
|
*/
|
|
146
|
-
exactColumns?:
|
|
193
|
+
exactColumns?: Readonly<Record<string, string>>
|
|
147
194
|
timestamp: string
|
|
148
195
|
}
|
|
149
196
|
|
|
@@ -167,8 +214,12 @@ interface ServerSystemMessage {
|
|
|
167
214
|
message: string
|
|
168
215
|
/** The channel a refusal is about; an error without one is about the socket. */
|
|
169
216
|
channel?: string
|
|
217
|
+
/** Why, as a fixed code (packages/realtime `refusal-codes.ts`). A server that predates codes sends none. */
|
|
218
|
+
code?: string
|
|
170
219
|
/** The `ref` of the join this answers. A server that predates refs sends none. */
|
|
171
220
|
ref?: string
|
|
221
|
+
/** What the server can do beyond the base protocol, on the first frame of a socket. */
|
|
222
|
+
features?: string[]
|
|
172
223
|
}
|
|
173
224
|
|
|
174
225
|
type ServerMessage = ServerChangeMessage | ServerPresenceMessage | ServerBroadcastMessage | ServerSystemMessage
|
|
@@ -182,7 +233,7 @@ const isChangeMessage: Guard<ServerChangeMessage> = isShape({
|
|
|
182
233
|
channel: isString,
|
|
183
234
|
event: isOneOf(["INSERT", "UPDATE", "DELETE"]),
|
|
184
235
|
payload: isShape({ old: isRecordOrNull, new: isRecordOrNull }),
|
|
185
|
-
exactColumns: optional(isRecordOf(
|
|
236
|
+
exactColumns: optional(isRecordOf(isString)),
|
|
186
237
|
timestamp: isString,
|
|
187
238
|
})
|
|
188
239
|
|
|
@@ -205,7 +256,9 @@ const isSystemMessage: Guard<ServerSystemMessage> = isShape({
|
|
|
205
256
|
status: isOneOf(["ok", "error"]),
|
|
206
257
|
message: isString,
|
|
207
258
|
channel: optional(isString),
|
|
259
|
+
code: optional(isString),
|
|
208
260
|
ref: optional(isString),
|
|
261
|
+
features: optional(isArrayOf(isString)),
|
|
209
262
|
})
|
|
210
263
|
|
|
211
264
|
/** A frame from the realtime service (packages/realtime/src/types.ts) in one of the four shapes. */
|
|
@@ -216,6 +269,15 @@ function isServerMessage(value: unknown): value is ServerMessage {
|
|
|
216
269
|
/** How the server's acknowledgement of a join begins; the channel name follows. */
|
|
217
270
|
const SUBSCRIBED_TO = "subscribed to "
|
|
218
271
|
|
|
272
|
+
/** The longest wait between reconnect attempts. Without it ten doublings from one second reach 512 s. */
|
|
273
|
+
const MAX_RECONNECT_DELAY_MS = 30_000
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* How long a socket may stay CONNECTING. One opened while realtime restarts behind the gateway can
|
|
277
|
+
* stay there with no error and no close, and the client would wait on it for good.
|
|
278
|
+
*/
|
|
279
|
+
const CONNECT_TIMEOUT_MS = 10_000
|
|
280
|
+
|
|
219
281
|
// ─── Realtime client ─────────────────────────────────────────────────────────
|
|
220
282
|
|
|
221
283
|
export class RealtimeClient {
|
|
@@ -227,6 +289,8 @@ export class RealtimeClient {
|
|
|
227
289
|
private reconnectAttempts = 0
|
|
228
290
|
private maxReconnectAttempts = 10
|
|
229
291
|
private baseReconnectDelay = 1000
|
|
292
|
+
private connection: RealtimeConnectionState = "disconnected"
|
|
293
|
+
private readonly connectionListeners = new Set<RealtimeConnectionListener>()
|
|
230
294
|
/** The token the live socket was opened with, so an auth change can tell whether it still holds. */
|
|
231
295
|
private currentToken: string | undefined
|
|
232
296
|
/**
|
|
@@ -241,6 +305,11 @@ export class RealtimeClient {
|
|
|
241
305
|
private attempt: Promise<void> | null = null
|
|
242
306
|
/** The last `ref` a join was sent with. Unique for the life of the client, across sockets. */
|
|
243
307
|
private lastRef = 0
|
|
308
|
+
/**
|
|
309
|
+
* What the server on the live socket announced on its first frame: undefined until that frame
|
|
310
|
+
* arrives, an empty set for a server that announces nothing (one that predates private channels).
|
|
311
|
+
*/
|
|
312
|
+
private serverFeatures: ReadonlySet<string> | undefined
|
|
244
313
|
|
|
245
314
|
/**
|
|
246
315
|
* `auth` is either a headers provider or a fixed set of headers: the same pair `QueryBuilder` and
|
|
@@ -256,6 +325,39 @@ export class RealtimeClient {
|
|
|
256
325
|
this.getHeaders = asHeadersProvider(auth)
|
|
257
326
|
}
|
|
258
327
|
|
|
328
|
+
/** The socket's own state. A channel's status cannot say this: it reads SUBSCRIBING for a drop and a first connect alike. */
|
|
329
|
+
get connectionState(): RealtimeConnectionState {
|
|
330
|
+
return this.connection
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** True while the socket is open. A channel may still be waiting on its join. */
|
|
334
|
+
get isConnected(): boolean {
|
|
335
|
+
return this.connection === "connected"
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Call `listener` each time the connection state changes. It is not called with the current state
|
|
340
|
+
* on registering: read `connectionState` or `isConnected` for that. Returns a function that stops it.
|
|
341
|
+
*/
|
|
342
|
+
onConnectionChange(listener: RealtimeConnectionListener): () => void {
|
|
343
|
+
this.connectionListeners.add(listener)
|
|
344
|
+
return () => {
|
|
345
|
+
this.connectionListeners.delete(listener)
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
private setConnection(next: RealtimeConnectionState): void {
|
|
350
|
+
if (this.connection === next) return
|
|
351
|
+
this.connection = next
|
|
352
|
+
for (const listener of [...this.connectionListeners]) {
|
|
353
|
+
try {
|
|
354
|
+
listener(next)
|
|
355
|
+
} catch {
|
|
356
|
+
// One listener's bug must not stop the others hearing, or stop the socket doing its work.
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
259
361
|
/** The socket's address, as ws(s) for an http(s) one. Read when connecting, not before. */
|
|
260
362
|
private get url(): string {
|
|
261
363
|
return settle(this.base).replace(/^http/, "ws")
|
|
@@ -321,6 +423,7 @@ export class RealtimeClient {
|
|
|
321
423
|
const old = this.ws
|
|
322
424
|
this.ws = null
|
|
323
425
|
this.currentToken = undefined
|
|
426
|
+
this.serverFeatures = undefined
|
|
324
427
|
if (old !== null) {
|
|
325
428
|
old.onopen = null
|
|
326
429
|
old.onmessage = null
|
|
@@ -348,6 +451,7 @@ export class RealtimeClient {
|
|
|
348
451
|
state.joined = undefined
|
|
349
452
|
state.joining = undefined
|
|
350
453
|
state.joinRef = undefined
|
|
454
|
+
state.joinedPrivate = false
|
|
351
455
|
forgetMembers(state)
|
|
352
456
|
}
|
|
353
457
|
}
|
|
@@ -361,13 +465,15 @@ export class RealtimeClient {
|
|
|
361
465
|
* `useSubscription` hooks with one channel name broke each other when either unmounted. The join
|
|
362
466
|
* is now left only when the last handle on the name unsubscribes.
|
|
363
467
|
*/
|
|
364
|
-
channel<TRow = Record<string, unknown>>(name:
|
|
468
|
+
channel<TRow = Record<string, unknown>>(name: ChannelName, opts: ChannelOptions = {}): ChannelSubscription<TRow> {
|
|
365
469
|
const state = this.getOrCreateChannel(name)
|
|
366
470
|
const handle: ChannelHandle = {
|
|
367
471
|
pgListeners: [],
|
|
368
472
|
presenceListeners: [],
|
|
369
473
|
broadcastListeners: new Map(),
|
|
474
|
+
refusalListeners: [],
|
|
370
475
|
statusCallback: null,
|
|
476
|
+
private: opts.private === true,
|
|
371
477
|
}
|
|
372
478
|
state.handles.add(handle)
|
|
373
479
|
|
|
@@ -399,6 +505,11 @@ export class RealtimeClient {
|
|
|
399
505
|
return sub
|
|
400
506
|
},
|
|
401
507
|
|
|
508
|
+
onRefused(callback) {
|
|
509
|
+
handle.refusalListeners.push(callback)
|
|
510
|
+
return sub
|
|
511
|
+
},
|
|
512
|
+
|
|
402
513
|
subscribe: (callback) => {
|
|
403
514
|
handle.statusCallback = callback ?? null
|
|
404
515
|
// Joining twice is a no-op rather than a second frame, so `from(table).subscribe()` can
|
|
@@ -406,6 +517,12 @@ export class RealtimeClient {
|
|
|
406
517
|
// A join already acknowledged will not be acknowledged again, so say so here or the new
|
|
407
518
|
// callback waits for a SUBSCRIBED that is never coming.
|
|
408
519
|
if (state.subscribed && serves(state.joined, handle)) callback?.("SUBSCRIBED")
|
|
520
|
+
// An app subscribing again after a withdrawal is asking to try the join again.
|
|
521
|
+
if (state.withdrawn) {
|
|
522
|
+
state.withdrawn = false
|
|
523
|
+
state.joinSent = false
|
|
524
|
+
}
|
|
525
|
+
this.rejoinForPrivacy(state)
|
|
409
526
|
this.ensureConnection()
|
|
410
527
|
this.sendSubscribe(state)
|
|
411
528
|
return sub
|
|
@@ -472,6 +589,7 @@ export class RealtimeClient {
|
|
|
472
589
|
*/
|
|
473
590
|
disconnect(): void {
|
|
474
591
|
this.abandonSocket("client disconnect")
|
|
592
|
+
this.setConnection("disconnected")
|
|
475
593
|
this.notifyChannels("CLOSED")
|
|
476
594
|
}
|
|
477
595
|
|
|
@@ -488,6 +606,9 @@ export class RealtimeClient {
|
|
|
488
606
|
joined: undefined,
|
|
489
607
|
joining: undefined,
|
|
490
608
|
joinRef: undefined,
|
|
609
|
+
joinedPrivate: false,
|
|
610
|
+
withdrawn: false,
|
|
611
|
+
unsupported: false,
|
|
491
612
|
members: [],
|
|
492
613
|
}
|
|
493
614
|
this.channels.set(name, state)
|
|
@@ -508,6 +629,7 @@ export class RealtimeClient {
|
|
|
508
629
|
// Read here, synchronously, so a client with no address or anon key throws from the subscribe
|
|
509
630
|
// that asked for the socket rather than from a background attempt nobody is waiting on.
|
|
510
631
|
const url = this.url
|
|
632
|
+
this.setConnection("connecting")
|
|
511
633
|
|
|
512
634
|
let attempt: Promise<void>
|
|
513
635
|
const isCurrent = (): boolean => this.attempt === attempt
|
|
@@ -553,12 +675,18 @@ export class RealtimeClient {
|
|
|
553
675
|
if (!isCurrent()) return
|
|
554
676
|
|
|
555
677
|
this.currentToken = token
|
|
678
|
+
this.serverFeatures = undefined
|
|
556
679
|
const wsUrl = token ? `${url}?token=${encodeURIComponent(token)}` : url
|
|
557
680
|
const ws = new WebSocket(wsUrl)
|
|
558
681
|
this.ws = ws
|
|
682
|
+
const handshake = setTimeout(() => {
|
|
683
|
+
if (ws.readyState === WebSocket.CONNECTING) this.socketLost(ws)
|
|
684
|
+
}, CONNECT_TIMEOUT_MS)
|
|
559
685
|
|
|
560
686
|
ws.onopen = () => {
|
|
687
|
+
clearTimeout(handshake)
|
|
561
688
|
this.reconnectAttempts = 0
|
|
689
|
+
this.setConnection("connected")
|
|
562
690
|
// Re-subscribe all channels
|
|
563
691
|
for (const state of this.channels.values()) {
|
|
564
692
|
if (!state.subscribed) {
|
|
@@ -577,28 +705,41 @@ export class RealtimeClient {
|
|
|
577
705
|
}
|
|
578
706
|
}
|
|
579
707
|
|
|
580
|
-
ws.onclose = () =>
|
|
581
|
-
this.ws = null
|
|
582
|
-
this.forgetJoins()
|
|
583
|
-
// Attempt reconnection with exponential backoff
|
|
584
|
-
if (this.channels.size > 0) {
|
|
585
|
-
this.scheduleReconnect()
|
|
586
|
-
}
|
|
587
|
-
}
|
|
708
|
+
ws.onclose = () => this.socketLost(ws)
|
|
588
709
|
|
|
589
710
|
ws.onerror = () => {
|
|
590
|
-
//
|
|
711
|
+
// An open socket's error is followed by its close. One that never opened may not be: Node's
|
|
712
|
+
// built-in WebSocket, refused by a gateway answering 502, fires error and then nothing, and
|
|
713
|
+
// counted as live it was never replaced. So that one is dropped here.
|
|
714
|
+
if (ws.readyState !== WebSocket.OPEN) this.socketLost(ws)
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** `ws` closed or failed to open: forget it and reconnect with backoff, once per socket. */
|
|
719
|
+
private socketLost(ws: WebSocket): void {
|
|
720
|
+
if (this.ws !== ws) return
|
|
721
|
+
ws.onclose = null
|
|
722
|
+
ws.onerror = null
|
|
723
|
+
if (ws.readyState !== WebSocket.CLOSED) ws.close()
|
|
724
|
+
this.ws = null
|
|
725
|
+
this.forgetJoins()
|
|
726
|
+
if (this.channels.size > 0) {
|
|
727
|
+
this.scheduleReconnect()
|
|
728
|
+
} else {
|
|
729
|
+
this.setConnection("disconnected")
|
|
591
730
|
}
|
|
592
731
|
}
|
|
593
732
|
|
|
594
733
|
private scheduleReconnect(): void {
|
|
595
734
|
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
735
|
+
this.setConnection("disconnected")
|
|
596
736
|
this.notifyChannels("TIMED_OUT")
|
|
597
737
|
return
|
|
598
738
|
}
|
|
599
739
|
|
|
600
|
-
const delay = this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts)
|
|
740
|
+
const delay = Math.min(MAX_RECONNECT_DELAY_MS, this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts))
|
|
601
741
|
this.reconnectAttempts++
|
|
742
|
+
this.setConnection("connecting")
|
|
602
743
|
|
|
603
744
|
this.notifyChannels("SUBSCRIBING")
|
|
604
745
|
|
|
@@ -625,6 +766,10 @@ export class RealtimeClient {
|
|
|
625
766
|
}
|
|
626
767
|
|
|
627
768
|
private handleSystem(msg: ServerSystemMessage): void {
|
|
769
|
+
if (this.serverFeatures === undefined && msg.status === "ok" && !msg.message.startsWith(SUBSCRIBED_TO)) {
|
|
770
|
+
this.serverFeatures = new Set(msg.features ?? [])
|
|
771
|
+
this.joinWaitingChannels()
|
|
772
|
+
}
|
|
628
773
|
if (msg.status === "ok" && msg.message.startsWith(SUBSCRIBED_TO)) {
|
|
629
774
|
const state = this.answeredJoin(msg.message.slice(SUBSCRIBED_TO.length), msg.ref)
|
|
630
775
|
if (state !== undefined) acknowledgeJoin(state)
|
|
@@ -653,11 +798,22 @@ export class RealtimeClient {
|
|
|
653
798
|
* whose refused join it has since replaced, is told nothing.
|
|
654
799
|
*/
|
|
655
800
|
private handleRefusal(msg: ServerSystemMessage): void {
|
|
801
|
+
const kind = msg.channel === undefined ? undefined : classifyRefusal(msg.code, msg.message)
|
|
802
|
+
// A refused send is not a failed channel: it goes to `onRefused` and the status stays as it was.
|
|
803
|
+
if (msg.channel !== undefined && kind !== undefined && isActionRefusal(kind)) {
|
|
804
|
+
refuseAction(this.channels.get(msg.channel), { channel: msg.channel, code: kind, message: msg.message })
|
|
805
|
+
return
|
|
806
|
+
}
|
|
656
807
|
const affected = msg.channel === undefined ? [...this.channels.values()] : [this.answeredJoin(msg.channel, msg.ref)]
|
|
657
808
|
for (const state of affected) {
|
|
658
809
|
if (state === undefined) continue
|
|
810
|
+
const refusal =
|
|
811
|
+
msg.channel === undefined || kind === undefined
|
|
812
|
+
? new Error(msg.message)
|
|
813
|
+
: channelRefusal(msg.channel, msg.message, kind)
|
|
659
814
|
if (msg.channel !== undefined && state.subscribed) {
|
|
660
|
-
|
|
815
|
+
if (kind === "withdrawn") withdrawJoin(state, refusal)
|
|
816
|
+
else refuseRejoin(state, refusal)
|
|
661
817
|
continue
|
|
662
818
|
}
|
|
663
819
|
// A refused join registered nothing on the server, so a channel not yet confirmed may
|
|
@@ -666,7 +822,7 @@ export class RealtimeClient {
|
|
|
666
822
|
if (msg.ref !== undefined) state.joinRef = undefined
|
|
667
823
|
// The server's reason goes to the callback (N-FF5): "table public.notes does not exist"
|
|
668
824
|
// tells the developer what to fix, and a bare CHANNEL_ERROR did not.
|
|
669
|
-
notifyHandles(state, "CHANNEL_ERROR",
|
|
825
|
+
notifyHandles(state, "CHANNEL_ERROR", refusal)
|
|
670
826
|
}
|
|
671
827
|
}
|
|
672
828
|
|
|
@@ -677,7 +833,7 @@ export class RealtimeClient {
|
|
|
677
833
|
// A bigint column arrives as a string and becomes a native bigint here, and a numeric stays
|
|
678
834
|
// the exact string `@supatype/types` declares for Decimal and Money. The same coercion the
|
|
679
835
|
// REST path uses, so a row read either way holds the same values.
|
|
680
|
-
const exact = msg.exactColumns ?? {}
|
|
836
|
+
const exact = knownExactKinds(msg.exactColumns ?? {})
|
|
681
837
|
const newRecord = coerceRecord(msg.payload.new, exact)
|
|
682
838
|
const oldRecord = coerceRecord(msg.payload.old, exact)
|
|
683
839
|
|
|
@@ -728,7 +884,10 @@ export class RealtimeClient {
|
|
|
728
884
|
private sendSubscribe(state: ChannelState): void {
|
|
729
885
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return
|
|
730
886
|
if (state.joinSent) return
|
|
887
|
+
const asPrivate = isPrivate(state)
|
|
888
|
+
if (asPrivate && !this.mayJoinPrivately(state)) return
|
|
731
889
|
state.joinSent = true
|
|
890
|
+
state.joinedPrivate = asPrivate
|
|
732
891
|
|
|
733
892
|
const target = joinTargetOf(state)
|
|
734
893
|
state.joining = target
|
|
@@ -736,7 +895,43 @@ export class RealtimeClient {
|
|
|
736
895
|
// the server delivers for until it acknowledges this one, so the old target stays until then.
|
|
737
896
|
state.joined ??= target
|
|
738
897
|
state.joinRef = String(++this.lastRef)
|
|
739
|
-
this.sendMessage(subscribeFrame(state.name, target, state.joinRef))
|
|
898
|
+
this.sendMessage(subscribeFrame(state.name, target, state.joinRef, asPrivate))
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* Whether a private join may be sent on this socket now.
|
|
903
|
+
*
|
|
904
|
+
* Not before the server's first frame says what it can do: the join waits for it. And not at all
|
|
905
|
+
* to a server that does not announce `private_channels`: it would ignore the flag and admit an
|
|
906
|
+
* open channel, so the join is failed here instead and never sent.
|
|
907
|
+
*/
|
|
908
|
+
private mayJoinPrivately(state: ChannelState): boolean {
|
|
909
|
+
if (this.serverFeatures === undefined) return false
|
|
910
|
+
if (this.serverFeatures.has(PRIVATE_CHANNELS_FEATURE)) return true
|
|
911
|
+
if (!state.unsupported) {
|
|
912
|
+
state.unsupported = true
|
|
913
|
+
notifyHandles(state, "CHANNEL_ERROR", unsupportedServer(state.name))
|
|
914
|
+
}
|
|
915
|
+
return false
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/** The server's first frame has arrived: send the joins that were waiting for it. */
|
|
919
|
+
private joinWaitingChannels(): void {
|
|
920
|
+
for (const state of this.channels.values()) {
|
|
921
|
+
state.unsupported = false
|
|
922
|
+
if (!state.subscribed) this.sendSubscribe(state)
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* A handle asking for `private: true` on a name already joined as open joins again as private,
|
|
928
|
+
* in place, as `rejoinIfUnheard` does: the open join stands until the server takes the new one.
|
|
929
|
+
*/
|
|
930
|
+
private rejoinForPrivacy(state: ChannelState): void {
|
|
931
|
+
if (state.joinSent && !state.joinedPrivate && isPrivate(state)) {
|
|
932
|
+
state.joinSent = false
|
|
933
|
+
if (state.subscribed) notifyUnserved(state, "SUBSCRIBING")
|
|
934
|
+
}
|
|
740
935
|
}
|
|
741
936
|
|
|
742
937
|
/**
|
|
@@ -792,7 +987,10 @@ interface ChannelHandle {
|
|
|
792
987
|
pgListeners: PgListener[]
|
|
793
988
|
presenceListeners: Array<(event: { joins: PresenceEntry[]; leaves: PresenceEntry[] }) => void>
|
|
794
989
|
broadcastListeners: Map<string, Array<(payload: Record<string, unknown>) => void>>
|
|
990
|
+
refusalListeners: Array<(refusal: ChannelActionRefusal) => void>
|
|
795
991
|
statusCallback: ChannelStatusCallback | null
|
|
992
|
+
/** Whether this handle asked for `private: true`. */
|
|
993
|
+
private: boolean
|
|
796
994
|
}
|
|
797
995
|
|
|
798
996
|
/** One channel name's join on the socket, shared by every handle on that name. */
|
|
@@ -823,6 +1021,12 @@ interface ChannelState {
|
|
|
823
1021
|
* reply carrying any other ref answers a join since replaced or left, and is not this one's.
|
|
824
1022
|
*/
|
|
825
1023
|
joinRef: string | undefined
|
|
1024
|
+
/** The join sent on the current socket asked for `private: true`. */
|
|
1025
|
+
joinedPrivate: boolean
|
|
1026
|
+
/** The server took this channel back, and the client does not join it again until the app asks. */
|
|
1027
|
+
withdrawn: boolean
|
|
1028
|
+
/** The channel's private join was failed on this socket for want of server support. */
|
|
1029
|
+
unsupported: boolean
|
|
826
1030
|
/** Who the current socket has said is tracked on this channel, one entry per tracking socket. */
|
|
827
1031
|
members: PresenceEntry[]
|
|
828
1032
|
}
|
|
@@ -878,7 +1082,7 @@ function pgListenersOf(state: ChannelState): PgListener[] {
|
|
|
878
1082
|
* `changes` says whether the join has a row listener. Only a row join has its table checked and is
|
|
879
1083
|
* sent row changes: broadcast and presence on `room:x` were refused as a join for room.x (R2-RB2).
|
|
880
1084
|
*/
|
|
881
|
-
function subscribeFrame(channel: string, target: JoinTarget, ref: string): Record<string, unknown> {
|
|
1085
|
+
function subscribeFrame(channel: string, target: JoinTarget, ref: string, asPrivate: boolean): Record<string, unknown> {
|
|
882
1086
|
return {
|
|
883
1087
|
type: "subscribe",
|
|
884
1088
|
channel,
|
|
@@ -887,6 +1091,7 @@ function subscribeFrame(channel: string, target: JoinTarget, ref: string): Recor
|
|
|
887
1091
|
schema: target.schema,
|
|
888
1092
|
changes: target.rows,
|
|
889
1093
|
filter: filterFrame(target.filter),
|
|
1094
|
+
...(asPrivate && { private: true }),
|
|
890
1095
|
ref,
|
|
891
1096
|
}
|
|
892
1097
|
}
|
|
@@ -943,6 +1148,37 @@ function serves(join: JoinTarget | undefined, handle: ChannelHandle): boolean {
|
|
|
943
1148
|
)
|
|
944
1149
|
}
|
|
945
1150
|
|
|
1151
|
+
/** Whether any handle on the channel asked for `private: true`: the shared join then does. */
|
|
1152
|
+
function isPrivate(state: ChannelState): boolean {
|
|
1153
|
+
for (const handle of state.handles) if (handle.private) return true
|
|
1154
|
+
return false
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* The server removed this client from a channel it held: the token changed, a re-check ran, or the
|
|
1159
|
+
* declaration went. Every handle is told, and the client does not join again by itself, since the
|
|
1160
|
+
* server would refuse it again. The app joins again by subscribing again.
|
|
1161
|
+
*/
|
|
1162
|
+
function withdrawJoin(state: ChannelState, refusal: Error): void {
|
|
1163
|
+
state.subscribed = false
|
|
1164
|
+
state.joinSent = true
|
|
1165
|
+
state.withdrawn = true
|
|
1166
|
+
state.joined = undefined
|
|
1167
|
+
state.joining = undefined
|
|
1168
|
+
state.joinRef = undefined
|
|
1169
|
+
state.joinedPrivate = false
|
|
1170
|
+
forgetMembers(state)
|
|
1171
|
+
notifyHandles(state, "CHANNEL_ERROR", refusal)
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/** Hand a refused send, track or payload to the `onRefused` listeners of every handle on the channel. */
|
|
1175
|
+
function refuseAction(state: ChannelState | undefined, refusal: ChannelActionRefusal): void {
|
|
1176
|
+
if (state === undefined) return
|
|
1177
|
+
for (const handle of state.handles) {
|
|
1178
|
+
for (const listener of handle.refusalListeners) listener(refusal)
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
|
|
946
1182
|
/** Tell each handle on a channel its status. */
|
|
947
1183
|
function notifyHandles(state: ChannelState, status: ChannelStatus, err?: Error | undefined): void {
|
|
948
1184
|
for (const handle of state.handles) handle.statusCallback?.(status, err)
|
package/src/runtime-env.ts
CHANGED
|
@@ -254,6 +254,12 @@ export class ClientTarget {
|
|
|
254
254
|
return this.#findUrl() ?? ""
|
|
255
255
|
}
|
|
256
256
|
|
|
257
|
+
/** The anon key if it can be found now, else an empty string. Never throws. */
|
|
258
|
+
currentAnonKey(): string {
|
|
259
|
+
this.#anonKey ??= present(pageEnv().anonKey)
|
|
260
|
+
return this.#anonKey ?? ""
|
|
261
|
+
}
|
|
262
|
+
|
|
257
263
|
/** The address as given or as the page has set it, kept once found. */
|
|
258
264
|
#findUrl(): string | undefined {
|
|
259
265
|
this.#url ??= httpUrl(pageEnv().url)
|