@supatype/client 0.3.3 → 0.3.5
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 +31 -29
- package/.turbo/turbo-typecheck.log +1 -1
- package/dist/index.d.ts +10 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +23 -4
- package/dist/index.js.map +1 -1
- package/dist/realtime.d.ts +2 -0
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +65 -23
- package/dist/realtime.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +23 -3
- package/src/realtime.ts +70 -25
- package/tests/subscribe-frame.test.ts +61 -1
- package/tests/table-subscribe.test.ts +290 -0
- package/tsconfig.tsbuildinfo +1 -1
package/src/realtime.ts
CHANGED
|
@@ -68,6 +68,18 @@ function coerceRecord(
|
|
|
68
68
|
return coerceExactKinds(record, exact) as Record<string, unknown>
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/**
|
|
72
|
+
* The schema and table a channel name implies, when a listener does not say.
|
|
73
|
+
*
|
|
74
|
+
* `schema:table`, or a bare `table` in `public`. The same reading as the server's `parseChannel`
|
|
75
|
+
* fallback, so the two agree on any name; anything after a second colon is not part of either.
|
|
76
|
+
*/
|
|
77
|
+
function parseChannelName(name: string): { schema: string; table: string } {
|
|
78
|
+
const parts = name.split(":")
|
|
79
|
+
if (parts.length >= 2) return { schema: parts[0]!, table: parts[1]! }
|
|
80
|
+
return { schema: "public", table: name }
|
|
81
|
+
}
|
|
82
|
+
|
|
71
83
|
// ─── Server message types (subset matching @supatype/realtime) ───────────────
|
|
72
84
|
|
|
73
85
|
interface ServerChangeMessage {
|
|
@@ -176,9 +188,6 @@ export class RealtimeClient {
|
|
|
176
188
|
/** Abandon the current socket and immediately open a replacement, keeping every channel. */
|
|
177
189
|
private cycleConnection(token: string | undefined): void {
|
|
178
190
|
this.abandonSocket("reauthenticating")
|
|
179
|
-
for (const state of this.channels.values()) {
|
|
180
|
-
state.subscribed = false
|
|
181
|
-
}
|
|
182
191
|
this.ensureConnection(token)
|
|
183
192
|
}
|
|
184
193
|
|
|
@@ -205,6 +214,17 @@ export class RealtimeClient {
|
|
|
205
214
|
old.close(1000, reason)
|
|
206
215
|
}
|
|
207
216
|
this.reconnectAttempts = 0
|
|
217
|
+
// Here rather than at each caller. `disconnect()` left every channel marked subscribed, so a
|
|
218
|
+
// channel that subscribed again afterwards opened a fresh socket and was never re-joined on it.
|
|
219
|
+
this.forgetJoins()
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Every join belonged to the socket that just went away; the next one has to make its own. */
|
|
223
|
+
private forgetJoins(): void {
|
|
224
|
+
for (const state of this.channels.values()) {
|
|
225
|
+
state.subscribed = false
|
|
226
|
+
state.joinSent = false
|
|
227
|
+
}
|
|
208
228
|
}
|
|
209
229
|
|
|
210
230
|
channel<TRow = Record<string, unknown>>(name: string): ChannelSubscription<TRow> {
|
|
@@ -212,10 +232,14 @@ export class RealtimeClient {
|
|
|
212
232
|
|
|
213
233
|
const sub: ChannelSubscription<TRow> = {
|
|
214
234
|
on(_event, opts, callback) {
|
|
235
|
+
// Defaults read the channel name the way the server's fallback does. The schema used to
|
|
236
|
+
// default to "public" regardless, and since the frame always carries a schema, a channel
|
|
237
|
+
// named `app:orders` was registered against `public.orders`.
|
|
238
|
+
const named = parseChannelName(name)
|
|
215
239
|
state.pgListeners.push({
|
|
216
240
|
event: opts.event,
|
|
217
|
-
schema: opts.schema ??
|
|
218
|
-
table: opts.table ??
|
|
241
|
+
schema: opts.schema ?? named.schema,
|
|
242
|
+
table: opts.table ?? named.table,
|
|
219
243
|
filter: opts.filter,
|
|
220
244
|
callback: callback as RealtimeCallback<Record<string, unknown>>,
|
|
221
245
|
})
|
|
@@ -237,6 +261,11 @@ export class RealtimeClient {
|
|
|
237
261
|
|
|
238
262
|
subscribe: (callback) => {
|
|
239
263
|
state.statusCallback = callback ?? null
|
|
264
|
+
// Joining twice is a no-op rather than a second frame, so `from(table).subscribe()` can
|
|
265
|
+
// join on its own and a caller can still call this afterwards just to watch the status.
|
|
266
|
+
// A join already acknowledged will not be acknowledged again, so say so here or the new
|
|
267
|
+
// callback waits for a SUBSCRIBED that is never coming.
|
|
268
|
+
if (state.subscribed) callback?.("SUBSCRIBED")
|
|
240
269
|
this.ensureConnection()
|
|
241
270
|
this.sendSubscribe(state)
|
|
242
271
|
return sub
|
|
@@ -315,6 +344,7 @@ export class RealtimeClient {
|
|
|
315
344
|
broadcastListeners: new Map(),
|
|
316
345
|
statusCallback: null,
|
|
317
346
|
subscribed: false,
|
|
347
|
+
joinSent: false,
|
|
318
348
|
}
|
|
319
349
|
this.channels.set(name, state)
|
|
320
350
|
}
|
|
@@ -400,10 +430,7 @@ export class RealtimeClient {
|
|
|
400
430
|
|
|
401
431
|
ws.onclose = () => {
|
|
402
432
|
this.ws = null
|
|
403
|
-
|
|
404
|
-
for (const state of this.channels.values()) {
|
|
405
|
-
state.subscribed = false
|
|
406
|
-
}
|
|
433
|
+
this.forgetJoins()
|
|
407
434
|
// Attempt reconnection with exponential backoff
|
|
408
435
|
if (this.channels.size > 0) {
|
|
409
436
|
this.scheduleReconnect()
|
|
@@ -466,6 +493,9 @@ export class RealtimeClient {
|
|
|
466
493
|
if (msg.status === "error") {
|
|
467
494
|
// Find which channel this error relates to, broadcast to all as fallback
|
|
468
495
|
for (const state of this.channels.values()) {
|
|
496
|
+
// A refused join registered nothing on the server, so a channel not yet confirmed may
|
|
497
|
+
// join again on this socket. Marked as sent, a retry after authenticating sent nothing.
|
|
498
|
+
if (!state.subscribed) state.joinSent = false
|
|
469
499
|
state.statusCallback?.("CHANNEL_ERROR")
|
|
470
500
|
}
|
|
471
501
|
}
|
|
@@ -475,27 +505,32 @@ export class RealtimeClient {
|
|
|
475
505
|
const state = this.channels.get(msg.channel)
|
|
476
506
|
if (!state) return
|
|
477
507
|
|
|
478
|
-
// Parse channel to get schema/table
|
|
479
|
-
const parts = msg.channel.split(":")
|
|
480
|
-
const schema = parts.length >= 2 ? parts[0]! : "public"
|
|
481
|
-
const table = parts.length >= 2 ? parts[1]! : parts[0]!
|
|
482
|
-
|
|
483
508
|
// A bigint column arrives as a string and becomes a native bigint here, and a numeric stays
|
|
484
509
|
// the exact string `@supatype/types` declares for Decimal and Money. The same coercion the
|
|
485
510
|
// REST path uses, so a row read either way holds the same values.
|
|
486
511
|
const exact = msg.exactColumns ?? {}
|
|
487
|
-
const payload
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
512
|
+
const newRecord = coerceRecord(msg.payload.new, exact)
|
|
513
|
+
const oldRecord = coerceRecord(msg.payload.old, exact)
|
|
514
|
+
|
|
515
|
+
// The channel is subscribed to the first listener's table, which is what `sendSubscribe`
|
|
516
|
+
// registers, so a change is that table's and goes only to listeners for it. Schema and table
|
|
517
|
+
// come from there, not from splitting the channel name: a channel named for its purpose told
|
|
518
|
+
// a `chat_message` listener its rows came from a table called `lobby-chat`. A listener for a
|
|
519
|
+
// different table on the same channel is never served by it, rather than handed these rows
|
|
520
|
+
// under its own table's name.
|
|
521
|
+
const subscribed = state.pgListeners[0]
|
|
522
|
+
if (!subscribed) return
|
|
496
523
|
for (const listener of state.pgListeners) {
|
|
524
|
+
if (listener.schema !== subscribed.schema || listener.table !== subscribed.table) continue
|
|
497
525
|
if (listener.event !== "*" && listener.event !== msg.event) continue
|
|
498
|
-
listener.callback(
|
|
526
|
+
listener.callback({
|
|
527
|
+
eventType: msg.event,
|
|
528
|
+
new: newRecord,
|
|
529
|
+
old: oldRecord,
|
|
530
|
+
schema: subscribed.schema,
|
|
531
|
+
table: subscribed.table,
|
|
532
|
+
commitTimestamp: msg.timestamp,
|
|
533
|
+
})
|
|
499
534
|
}
|
|
500
535
|
}
|
|
501
536
|
|
|
@@ -522,6 +557,8 @@ export class RealtimeClient {
|
|
|
522
557
|
|
|
523
558
|
private sendSubscribe(state: ChannelState): void {
|
|
524
559
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return
|
|
560
|
+
if (state.joinSent) return
|
|
561
|
+
state.joinSent = true
|
|
525
562
|
|
|
526
563
|
// Build filter from the first pg listener (if any)
|
|
527
564
|
const firstListener = state.pgListeners[0]
|
|
@@ -541,7 +578,7 @@ export class RealtimeClient {
|
|
|
541
578
|
//
|
|
542
579
|
// They were resolved here and then dropped, and the server falls back to reading the channel
|
|
543
580
|
// name as `schema:table`. So a subscription worked only when the channel happened to be named
|
|
544
|
-
// after its table,
|
|
581
|
+
// after its table, as `from(table).subscribe()` names its own. Anything else -- a channel
|
|
545
582
|
// called `lobby-chat` carrying `table: "chat_message"`, which is what `useSubscription` exists
|
|
546
583
|
// to let you write -- registered against a table no change can match. The socket reported
|
|
547
584
|
// SUBSCRIBED and delivered nothing, which is indistinguishable from a quiet table.
|
|
@@ -582,5 +619,13 @@ interface ChannelState {
|
|
|
582
619
|
presenceListeners: Array<(event: { joins: PresenceEntry[]; leaves: PresenceEntry[] }) => void>
|
|
583
620
|
broadcastListeners: Map<string, Array<(payload: Record<string, unknown>) => void>>
|
|
584
621
|
statusCallback: ((status: ChannelStatus) => void) | null
|
|
622
|
+
/** The server acknowledged the join on the current socket. */
|
|
585
623
|
subscribed: boolean
|
|
624
|
+
/**
|
|
625
|
+
* A join frame went out on the current socket, acknowledged or not.
|
|
626
|
+
*
|
|
627
|
+
* Separate from `subscribed` because the gap between the two is where a second `subscribe()`
|
|
628
|
+
* used to send a second frame.
|
|
629
|
+
*/
|
|
630
|
+
joinSent: boolean
|
|
586
631
|
}
|
|
@@ -13,7 +13,11 @@
|
|
|
13
13
|
|
|
14
14
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
15
15
|
import { RealtimeClient } from "../src/realtime.js"
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
createMockWebSocketClass,
|
|
18
|
+
simulateServerMessage,
|
|
19
|
+
type MockWebSocketInstance,
|
|
20
|
+
} from "./helpers/mock-websocket.js"
|
|
17
21
|
|
|
18
22
|
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
19
23
|
|
|
@@ -98,5 +102,61 @@ describe("the subscribe frame", () => {
|
|
|
98
102
|
await settle()
|
|
99
103
|
|
|
100
104
|
expect(subscribeFrames()[0]!["table"]).toBe("orders")
|
|
105
|
+
// The schema falls back the same way. It defaulted to "public" instead, and because the frame
|
|
106
|
+
// always carries a schema, that default overrode the "app" the server would have read.
|
|
107
|
+
expect(subscribeFrames()[0]!["schema"]).toBe("app")
|
|
108
|
+
})
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
describe("joining again after disconnect()", () => {
|
|
112
|
+
it("sends a fresh subscribe frame on the new socket", async () => {
|
|
113
|
+
// disconnect() dropped the socket but left the channel marked subscribed, so the new socket's
|
|
114
|
+
// open handler skipped it and the channel sat on a live socket it had never joined.
|
|
115
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
116
|
+
const channel = client
|
|
117
|
+
.channel("public:task")
|
|
118
|
+
.on("postgres_changes", { event: "*" }, () => {})
|
|
119
|
+
.subscribe()
|
|
120
|
+
await settle()
|
|
121
|
+
simulateServerMessage(instances[0]!, {
|
|
122
|
+
type: "system",
|
|
123
|
+
status: "ok",
|
|
124
|
+
message: "subscribed to public:task",
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
client.disconnect()
|
|
128
|
+
channel.subscribe()
|
|
129
|
+
await settle()
|
|
130
|
+
|
|
131
|
+
expect(instances).toHaveLength(2)
|
|
132
|
+
const onNewSocket = instances[1]!.send.mock.calls
|
|
133
|
+
.map((c) => JSON.parse(c[0] as string) as Record<string, unknown>)
|
|
134
|
+
.filter((m) => m["type"] === "subscribe")
|
|
135
|
+
expect(onNewSocket).toHaveLength(1)
|
|
136
|
+
})
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
describe("the payload a listener is handed", () => {
|
|
140
|
+
it("names the listener's table, not the channel's name", async () => {
|
|
141
|
+
// A channel named for its purpose was split on ":" to fill in `table`, so a listener on
|
|
142
|
+
// `chat_message` was told its rows came from a table called "lobby-chat".
|
|
143
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
144
|
+
let table: string | undefined
|
|
145
|
+
client
|
|
146
|
+
.channel("lobby-chat")
|
|
147
|
+
.on("postgres_changes", { event: "*", table: "chat_message" }, (payload) => {
|
|
148
|
+
table = payload.table
|
|
149
|
+
})
|
|
150
|
+
.subscribe()
|
|
151
|
+
await settle()
|
|
152
|
+
|
|
153
|
+
simulateServerMessage(instances[0]!, {
|
|
154
|
+
type: "change",
|
|
155
|
+
channel: "lobby-chat",
|
|
156
|
+
event: "INSERT",
|
|
157
|
+
payload: { old: null, new: { id: 1 } },
|
|
158
|
+
timestamp: "2026-01-01T00:00:00Z",
|
|
159
|
+
})
|
|
160
|
+
expect(table).toBe("chat_message")
|
|
101
161
|
})
|
|
102
162
|
})
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `from(table).subscribe()` on its own delivers changes.
|
|
3
|
+
*
|
|
4
|
+
* It registered a listener and returned, and never joined the channel: `on()` only records a
|
|
5
|
+
* listener, and the socket and the subscribe frame belong to the channel's own `subscribe()`. So a
|
|
6
|
+
* caller who used the documented typed API, and nothing else, waited for events that never came.
|
|
7
|
+
* It looked fine whenever something else on the same client had already subscribed a channel of
|
|
8
|
+
* the same name, because the two shared that channel's state.
|
|
9
|
+
*
|
|
10
|
+
* Every case here uses a client with no other subscription, which is the case the bug hid in.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
14
|
+
import { createClient } from "../src/index.js"
|
|
15
|
+
import type { RealtimePayload } from "../src/realtime.js"
|
|
16
|
+
import {
|
|
17
|
+
createMockWebSocketClass,
|
|
18
|
+
simulateServerMessage,
|
|
19
|
+
type MockWebSocketInstance,
|
|
20
|
+
} from "./helpers/mock-websocket.js"
|
|
21
|
+
|
|
22
|
+
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
23
|
+
|
|
24
|
+
let instances: MockWebSocketInstance[]
|
|
25
|
+
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
const mock = createMockWebSocketClass()
|
|
28
|
+
instances = mock.instances
|
|
29
|
+
vi.stubGlobal("WebSocket", mock.MockWebSocket)
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
afterEach(() => {
|
|
33
|
+
vi.unstubAllGlobals()
|
|
34
|
+
vi.restoreAllMocks()
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
function newClient(): ReturnType<typeof createClient> {
|
|
38
|
+
return createClient({ url: "http://localhost:18473", anonKey: "anon-key" })
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Every frame the client put on any socket, parsed. */
|
|
42
|
+
function sentFrames(): Array<Record<string, unknown>> {
|
|
43
|
+
return instances
|
|
44
|
+
.flatMap((i) => i.send.mock.calls.map((c) => c[0] as string))
|
|
45
|
+
.map((raw) => JSON.parse(raw) as Record<string, unknown>)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function framesOfType(type: string): Array<Record<string, unknown>> {
|
|
49
|
+
return sentFrames().filter((m) => m["type"] === type)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The only socket opened so far. A second one would mean a subscribe orphaned the first. */
|
|
53
|
+
function onlySocket(): MockWebSocketInstance {
|
|
54
|
+
expect(instances).toHaveLength(1)
|
|
55
|
+
return instances[0]!
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A change frame as the service sends one, addressed to the channel the client subscribed. */
|
|
59
|
+
function changeOn(
|
|
60
|
+
channel: string,
|
|
61
|
+
event: "INSERT" | "UPDATE" | "DELETE",
|
|
62
|
+
row: Record<string, unknown>,
|
|
63
|
+
): Record<string, unknown> {
|
|
64
|
+
return {
|
|
65
|
+
type: "change",
|
|
66
|
+
channel,
|
|
67
|
+
event,
|
|
68
|
+
payload: { old: null, new: row },
|
|
69
|
+
timestamp: "2026-01-01T00:00:00Z",
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function ack(channel: string): Record<string, unknown> {
|
|
74
|
+
return { type: "system", status: "ok", message: `subscribed to ${channel}` }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
describe("from(table).subscribe() alone", () => {
|
|
78
|
+
it("opens a socket, sends the subscribe frame, and delivers a change", async () => {
|
|
79
|
+
const client = newClient()
|
|
80
|
+
const seen: Array<RealtimePayload<Record<string, unknown>>> = []
|
|
81
|
+
|
|
82
|
+
client.from("post").subscribe((payload) => seen.push(payload))
|
|
83
|
+
await settle()
|
|
84
|
+
|
|
85
|
+
const ws = onlySocket()
|
|
86
|
+
const frames = framesOfType("subscribe")
|
|
87
|
+
expect(frames).toHaveLength(1)
|
|
88
|
+
const frame = frames[0]!
|
|
89
|
+
expect(frame["table"]).toBe("post")
|
|
90
|
+
expect(frame["schema"]).toBe("public")
|
|
91
|
+
expect(frame["event"]).toBe("*")
|
|
92
|
+
|
|
93
|
+
simulateServerMessage(ws, changeOn(frame["channel"] as string, "INSERT", { id: 1 }))
|
|
94
|
+
expect(seen).toHaveLength(1)
|
|
95
|
+
expect(seen[0]!.eventType).toBe("INSERT")
|
|
96
|
+
expect(seen[0]!.table).toBe("post")
|
|
97
|
+
expect(seen[0]!.schema).toBe("public")
|
|
98
|
+
expect(seen[0]!.new).toEqual({ id: 1 })
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it("sends the filter and event to the server, and drops other events", async () => {
|
|
102
|
+
const client = newClient()
|
|
103
|
+
const seen: Array<RealtimePayload<Record<string, unknown>>> = []
|
|
104
|
+
|
|
105
|
+
client
|
|
106
|
+
.from("post")
|
|
107
|
+
.subscribe((payload) => seen.push(payload), { event: "INSERT", filter: "slug=eq.hello" })
|
|
108
|
+
await settle()
|
|
109
|
+
|
|
110
|
+
const ws = onlySocket()
|
|
111
|
+
const frame = framesOfType("subscribe")[0]!
|
|
112
|
+
// The server applies the filter; the client only has to have said it.
|
|
113
|
+
expect(frame["filter"]).toEqual({ slug: "eq.hello" })
|
|
114
|
+
expect(frame["event"]).toBe("INSERT")
|
|
115
|
+
|
|
116
|
+
const channel = frame["channel"] as string
|
|
117
|
+
simulateServerMessage(ws, changeOn(channel, "UPDATE", { id: 1 }))
|
|
118
|
+
simulateServerMessage(ws, changeOn(channel, "INSERT", { id: 2 }))
|
|
119
|
+
expect(seen.map((p) => p.new)).toEqual([{ id: 2 }])
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
it("honours a non-default schema", async () => {
|
|
123
|
+
const client = newClient()
|
|
124
|
+
client.from("post").subscribe(() => {}, { schema: "app" })
|
|
125
|
+
await settle()
|
|
126
|
+
|
|
127
|
+
const frame = framesOfType("subscribe")[0]!
|
|
128
|
+
expect(frame["schema"]).toBe("app")
|
|
129
|
+
expect(frame["table"]).toBe("post")
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
it("closes the socket when its only subscription unsubscribes", async () => {
|
|
133
|
+
const client = newClient()
|
|
134
|
+
const sub = client.from("post").subscribe(() => {})
|
|
135
|
+
await settle()
|
|
136
|
+
|
|
137
|
+
const ws = onlySocket()
|
|
138
|
+
const channel = framesOfType("subscribe")[0]!["channel"]
|
|
139
|
+
sub.unsubscribe()
|
|
140
|
+
|
|
141
|
+
expect(framesOfType("unsubscribe")).toEqual([{ type: "unsubscribe", channel }])
|
|
142
|
+
expect(ws.close).toHaveBeenCalled()
|
|
143
|
+
})
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
describe("the status callback on the returned channel", () => {
|
|
147
|
+
it("still reports SUBSCRIBED without sending a second subscribe frame", async () => {
|
|
148
|
+
// The examples call `sub.channel.subscribe(cb)` to watch status, because that call used to be
|
|
149
|
+
// the only thing that joined. It has to keep working, and must not join twice.
|
|
150
|
+
const client = newClient()
|
|
151
|
+
const statuses: string[] = []
|
|
152
|
+
|
|
153
|
+
const sub = client.from("post").subscribe(() => {})
|
|
154
|
+
sub.channel.subscribe((s) => statuses.push(s))
|
|
155
|
+
await settle()
|
|
156
|
+
|
|
157
|
+
const ws = onlySocket()
|
|
158
|
+
const frames = framesOfType("subscribe")
|
|
159
|
+
expect(frames).toHaveLength(1)
|
|
160
|
+
simulateServerMessage(ws, ack(frames[0]!["channel"] as string))
|
|
161
|
+
expect(statuses).toEqual(["SUBSCRIBED"])
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
it("is told SUBSCRIBED when attached after the join was acknowledged", async () => {
|
|
165
|
+
// No second acknowledgement is coming, so a callback attached late would otherwise wait on
|
|
166
|
+
// nothing. Re-sending the frame to provoke one is the double join the case above forbids.
|
|
167
|
+
const client = newClient()
|
|
168
|
+
const sub = client.from("post").subscribe(() => {})
|
|
169
|
+
await settle()
|
|
170
|
+
|
|
171
|
+
const ws = onlySocket()
|
|
172
|
+
simulateServerMessage(ws, ack(framesOfType("subscribe")[0]!["channel"] as string))
|
|
173
|
+
|
|
174
|
+
const statuses: string[] = []
|
|
175
|
+
sub.channel.subscribe((s) => statuses.push(s))
|
|
176
|
+
expect(statuses).toEqual(["SUBSCRIBED"])
|
|
177
|
+
expect(framesOfType("subscribe")).toHaveLength(1)
|
|
178
|
+
})
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
describe("two subscriptions to the same table on one client", () => {
|
|
182
|
+
it("each joins with its own filter and receives its own events", async () => {
|
|
183
|
+
const client = newClient()
|
|
184
|
+
const first: unknown[] = []
|
|
185
|
+
const second: unknown[] = []
|
|
186
|
+
|
|
187
|
+
client.from("post").subscribe((p) => first.push(p.new), { filter: "slug=eq.a" })
|
|
188
|
+
client.from("post").subscribe((p) => second.push(p.new), { filter: "slug=eq.b" })
|
|
189
|
+
await settle()
|
|
190
|
+
|
|
191
|
+
const ws = onlySocket()
|
|
192
|
+
const frames = framesOfType("subscribe")
|
|
193
|
+
expect(frames).toHaveLength(2)
|
|
194
|
+
expect(frames.map((f) => f["filter"])).toEqual([{ slug: "eq.a" }, { slug: "eq.b" }])
|
|
195
|
+
// Distinct channels, because the server keys a subscription by its channel: a second join
|
|
196
|
+
// under the same name would replace the first one's filter rather than add to it.
|
|
197
|
+
expect(frames[0]!["channel"]).not.toBe(frames[1]!["channel"])
|
|
198
|
+
|
|
199
|
+
// The server addresses each change to the subscription it matched.
|
|
200
|
+
simulateServerMessage(ws, changeOn(frames[0]!["channel"] as string, "INSERT", { slug: "a" }))
|
|
201
|
+
simulateServerMessage(ws, changeOn(frames[1]!["channel"] as string, "INSERT", { slug: "b" }))
|
|
202
|
+
expect(first).toEqual([{ slug: "a" }])
|
|
203
|
+
expect(second).toEqual([{ slug: "b" }])
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
it("unsubscribing one leaves the other delivering on the same socket", async () => {
|
|
207
|
+
const client = newClient()
|
|
208
|
+
const second: unknown[] = []
|
|
209
|
+
|
|
210
|
+
const a = client.from("post").subscribe(() => {})
|
|
211
|
+
client.from("post").subscribe((p) => second.push(p.new))
|
|
212
|
+
await settle()
|
|
213
|
+
|
|
214
|
+
const ws = onlySocket()
|
|
215
|
+
const [frameA, frameB] = framesOfType("subscribe")
|
|
216
|
+
a.unsubscribe()
|
|
217
|
+
|
|
218
|
+
expect(framesOfType("unsubscribe")).toEqual([
|
|
219
|
+
{ type: "unsubscribe", channel: frameA!["channel"] },
|
|
220
|
+
])
|
|
221
|
+
expect(ws.close).not.toHaveBeenCalled()
|
|
222
|
+
simulateServerMessage(ws, changeOn(frameB!["channel"] as string, "INSERT", { id: 7 }))
|
|
223
|
+
expect(second).toEqual([{ id: 7 }])
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
it("does not share state with a raw channel named after the table", async () => {
|
|
227
|
+
// The raw channel is what used to hide the bug: it joined, and the table subscription rode on
|
|
228
|
+
// its state. Unsubscribing either must not tear down the other.
|
|
229
|
+
const client = newClient()
|
|
230
|
+
const fromTable: unknown[] = []
|
|
231
|
+
|
|
232
|
+
const raw = client.realtime
|
|
233
|
+
.channel("public:post")
|
|
234
|
+
.on("postgres_changes", { event: "*" }, () => {})
|
|
235
|
+
.subscribe()
|
|
236
|
+
const sub = client.from("post").subscribe((p) => fromTable.push(p.new))
|
|
237
|
+
await settle()
|
|
238
|
+
|
|
239
|
+
const ws = onlySocket()
|
|
240
|
+
const frames = framesOfType("subscribe")
|
|
241
|
+
expect(frames).toHaveLength(2)
|
|
242
|
+
const tableChannel = frames.find((f) => f["channel"] !== "public:post")!["channel"] as string
|
|
243
|
+
|
|
244
|
+
raw.unsubscribe()
|
|
245
|
+
expect(ws.close).not.toHaveBeenCalled()
|
|
246
|
+
simulateServerMessage(ws, changeOn(tableChannel, "INSERT", { id: 3 }))
|
|
247
|
+
expect(fromTable).toEqual([{ id: 3 }])
|
|
248
|
+
sub.unsubscribe()
|
|
249
|
+
expect(ws.close).toHaveBeenCalled()
|
|
250
|
+
})
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
describe("review fixes", () => {
|
|
254
|
+
it("sends the join again after the server rejected it, on the same socket", async () => {
|
|
255
|
+
// A rejected join registers nothing on the server, so the channel must be joinable again.
|
|
256
|
+
// It stayed marked as sent until the socket went away, and a retry after authenticating sent
|
|
257
|
+
// nothing at all.
|
|
258
|
+
const client = newClient()
|
|
259
|
+
const channel = client.realtime
|
|
260
|
+
.channel("lobby")
|
|
261
|
+
.on("postgres_changes", { event: "*", table: "chat_message" }, () => {})
|
|
262
|
+
channel.subscribe()
|
|
263
|
+
await settle()
|
|
264
|
+
const ws = onlySocket()
|
|
265
|
+
expect(framesOfType("subscribe")).toHaveLength(1)
|
|
266
|
+
|
|
267
|
+
simulateServerMessage(ws, { type: "system", status: "error", message: "authenticate before subscribing" })
|
|
268
|
+
channel.subscribe()
|
|
269
|
+
await settle()
|
|
270
|
+
expect(framesOfType("subscribe")).toHaveLength(2)
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
it("delivers a change only to listeners for the table the channel subscribed, labelled as that table", async () => {
|
|
274
|
+
// The server registers the first listener's table. A second listener for another table on the
|
|
275
|
+
// same channel was handed those rows labelled as its own table.
|
|
276
|
+
const client = newClient()
|
|
277
|
+
const posts: unknown[] = []
|
|
278
|
+
const comments: unknown[] = []
|
|
279
|
+
client.realtime
|
|
280
|
+
.channel("feed")
|
|
281
|
+
.on("postgres_changes", { event: "*", table: "posts" }, (p) => posts.push(p.table))
|
|
282
|
+
.on("postgres_changes", { event: "*", table: "comments" }, (p) => comments.push(p.table))
|
|
283
|
+
.subscribe()
|
|
284
|
+
await settle()
|
|
285
|
+
|
|
286
|
+
simulateServerMessage(onlySocket(), changeOn("feed", "INSERT", { id: 1 }))
|
|
287
|
+
expect(posts).toEqual(["posts"])
|
|
288
|
+
expect(comments).toEqual([])
|
|
289
|
+
})
|
|
290
|
+
})
|