@supatype/client 0.1.0-alpha.10
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 +4 -0
- package/.turbo/turbo-test.log +23 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/dist/auth.d.ts +279 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +848 -0
- package/dist/auth.js.map +1 -0
- package/dist/error-codes-doc.d.ts +31 -0
- package/dist/error-codes-doc.d.ts.map +1 -0
- package/dist/error-codes-doc.js +294 -0
- package/dist/error-codes-doc.js.map +1 -0
- package/dist/errors.d.ts +197 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +162 -0
- package/dist/errors.js.map +1 -0
- package/dist/fetch-with-retry.d.ts +49 -0
- package/dist/fetch-with-retry.d.ts.map +1 -0
- package/dist/fetch-with-retry.js +150 -0
- package/dist/fetch-with-retry.js.map +1 -0
- package/dist/index.d.ts +151 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +285 -0
- package/dist/index.js.map +1 -0
- package/dist/query.d.ts +55 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +264 -0
- package/dist/query.js.map +1 -0
- package/dist/realtime.d.ts +69 -0
- package/dist/realtime.d.ts.map +1 -0
- package/dist/realtime.js +279 -0
- package/dist/realtime.js.map +1 -0
- package/dist/retry.d.ts +24 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +25 -0
- package/dist/retry.js.map +1 -0
- package/dist/serverless-docs.d.ts +38 -0
- package/dist/serverless-docs.d.ts.map +1 -0
- package/dist/serverless-docs.js +83 -0
- package/dist/serverless-docs.js.map +1 -0
- package/dist/storage.d.ts +102 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +169 -0
- package/dist/storage.js.map +1 -0
- package/dist/types.d.ts +212 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +26 -0
- package/src/auth.ts +1024 -0
- package/src/error-codes-doc.ts +315 -0
- package/src/errors.ts +201 -0
- package/src/fetch-with-retry.ts +200 -0
- package/src/index.ts +518 -0
- package/src/query.ts +331 -0
- package/src/realtime.ts +418 -0
- package/src/retry.ts +35 -0
- package/src/serverless-docs.ts +107 -0
- package/src/storage.ts +234 -0
- package/src/types.ts +264 -0
- package/tests/auth.test.ts +351 -0
- package/tests/mfa-totp-integration.test.ts +359 -0
- package/tests/query.test.ts +286 -0
- package/tests/rate-limit-integration.test.ts +185 -0
- package/tests/realtime-multi-tenant-integration.test.ts +372 -0
- package/tests/retry-integration.test.ts +212 -0
- package/tests/serverless.test.ts +115 -0
- package/tests/storage-quota-integration.test.ts +189 -0
- package/tests/storage-upload-limit-integration.test.ts +185 -0
- package/tests/types.test.ts +137 -0
- package/tsconfig.json +11 -0
- package/tsconfig.tsbuildinfo +1 -0
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration test — Task 91: SDK rate limit handling
|
|
3
|
+
*
|
|
4
|
+
* Simulates 429 with Retry-After: 2 -> SDK waits -> retries -> succeeds.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
8
|
+
import { fetchWithRetry } from "../src/fetch-with-retry.js"
|
|
9
|
+
import { RateLimitError } from "../src/errors.js"
|
|
10
|
+
|
|
11
|
+
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
12
|
+
|
|
13
|
+
function mockResponse(status: number, body: unknown = {}, headers?: Record<string, string>): Response {
|
|
14
|
+
const headersObj = new Headers(headers)
|
|
15
|
+
return {
|
|
16
|
+
ok: status >= 200 && status < 300,
|
|
17
|
+
status,
|
|
18
|
+
json: vi.fn().mockResolvedValue(body),
|
|
19
|
+
headers: headersObj,
|
|
20
|
+
statusText: status === 429 ? "Too Many Requests" : "OK",
|
|
21
|
+
} as unknown as Response
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// ─── Tests ───────────────────────────────────────────────────────────────────
|
|
25
|
+
|
|
26
|
+
describe("Task 91 — SDK rate limit integration", () => {
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
vi.restoreAllMocks()
|
|
29
|
+
vi.useFakeTimers()
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
afterEach(() => {
|
|
33
|
+
vi.useRealTimers()
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it("waits Retry-After seconds then retries on 429", async () => {
|
|
37
|
+
const fetchSpy = vi.fn()
|
|
38
|
+
.mockResolvedValueOnce(mockResponse(429, { error: "rate limited" }, { "Retry-After": "2" }))
|
|
39
|
+
.mockResolvedValueOnce(mockResponse(200, { data: "success" }))
|
|
40
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
41
|
+
|
|
42
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 10000 })
|
|
43
|
+
|
|
44
|
+
// First call returns 429 with Retry-After: 2
|
|
45
|
+
// SDK should wait 2000ms before retrying
|
|
46
|
+
await vi.advanceTimersByTimeAsync(2100)
|
|
47
|
+
|
|
48
|
+
const res = await promise
|
|
49
|
+
expect(res.ok).toBe(true)
|
|
50
|
+
expect(res.status).toBe(200)
|
|
51
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it("uses Retry-After header value for wait duration", async () => {
|
|
55
|
+
const timestamps: number[] = []
|
|
56
|
+
const fetchSpy = vi.fn().mockImplementation(async () => {
|
|
57
|
+
timestamps.push(Date.now())
|
|
58
|
+
if (timestamps.length === 1) {
|
|
59
|
+
return mockResponse(429, {}, { "Retry-After": "3" })
|
|
60
|
+
}
|
|
61
|
+
return mockResponse(200, { data: "ok" })
|
|
62
|
+
})
|
|
63
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
64
|
+
|
|
65
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 10000 })
|
|
66
|
+
|
|
67
|
+
// Should not retry before 3 seconds
|
|
68
|
+
await vi.advanceTimersByTimeAsync(2900)
|
|
69
|
+
expect(timestamps).toHaveLength(1) // Only the first call
|
|
70
|
+
|
|
71
|
+
// After 3 seconds, retry should fire
|
|
72
|
+
await vi.advanceTimersByTimeAsync(200)
|
|
73
|
+
const res = await promise
|
|
74
|
+
|
|
75
|
+
expect(res.ok).toBe(true)
|
|
76
|
+
expect(timestamps).toHaveLength(2)
|
|
77
|
+
// The gap between timestamps should be ~3000ms
|
|
78
|
+
expect(timestamps[1]! - timestamps[0]!).toBeGreaterThanOrEqual(3000)
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it("defaults to 5 seconds when Retry-After header is missing", async () => {
|
|
82
|
+
const timestamps: number[] = []
|
|
83
|
+
const fetchSpy = vi.fn().mockImplementation(async () => {
|
|
84
|
+
timestamps.push(Date.now())
|
|
85
|
+
if (timestamps.length === 1) {
|
|
86
|
+
return mockResponse(429, {}) // No Retry-After header
|
|
87
|
+
}
|
|
88
|
+
return mockResponse(200, { data: "ok" })
|
|
89
|
+
})
|
|
90
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
91
|
+
|
|
92
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 30000 })
|
|
93
|
+
|
|
94
|
+
await vi.advanceTimersByTimeAsync(5100)
|
|
95
|
+
const res = await promise
|
|
96
|
+
|
|
97
|
+
expect(res.ok).toBe(true)
|
|
98
|
+
expect(timestamps).toHaveLength(2)
|
|
99
|
+
expect(timestamps[1]! - timestamps[0]!).toBeGreaterThanOrEqual(5000)
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it("throws RateLimitError after exhausting all retries on 429", async () => {
|
|
103
|
+
vi.useRealTimers()
|
|
104
|
+
const fetchSpy = vi.fn().mockResolvedValue(
|
|
105
|
+
mockResponse(429, { error: "rate limited" }, { "Retry-After": "1" }),
|
|
106
|
+
)
|
|
107
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
108
|
+
|
|
109
|
+
// Use maxRetries: 0 to avoid actual wait times and still test the throw
|
|
110
|
+
await expect(
|
|
111
|
+
fetchWithRetry("http://api.test/data", { maxRetries: 0, timeout: 30000 }),
|
|
112
|
+
).rejects.toThrow(RateLimitError)
|
|
113
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
114
|
+
vi.useFakeTimers()
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
it("RateLimitError includes retryAfterSeconds", async () => {
|
|
118
|
+
vi.useRealTimers()
|
|
119
|
+
const fetchSpy = vi.fn().mockResolvedValue(
|
|
120
|
+
mockResponse(429, {}, { "Retry-After": "2" }),
|
|
121
|
+
)
|
|
122
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
await fetchWithRetry("http://api.test/data", { maxRetries: 0, timeout: 30000 })
|
|
126
|
+
expect.fail("Should have thrown RateLimitError")
|
|
127
|
+
} catch (err) {
|
|
128
|
+
expect(err).toBeInstanceOf(RateLimitError)
|
|
129
|
+
expect((err as RateLimitError).retryAfterSeconds).toBe(2)
|
|
130
|
+
expect((err as RateLimitError).statusCode).toBe(429)
|
|
131
|
+
expect((err as RateLimitError).code).toBe("RATE_LIMITED")
|
|
132
|
+
}
|
|
133
|
+
vi.useFakeTimers()
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
it("handles mixed 429 then 503 then 200", async () => {
|
|
137
|
+
const fetchSpy = vi.fn()
|
|
138
|
+
.mockResolvedValueOnce(mockResponse(429, {}, { "Retry-After": "1" }))
|
|
139
|
+
.mockResolvedValueOnce(mockResponse(503))
|
|
140
|
+
.mockResolvedValueOnce(mockResponse(200, { data: "finally" }))
|
|
141
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
142
|
+
|
|
143
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 30000 })
|
|
144
|
+
|
|
145
|
+
// Wait for 429 retry (1s)
|
|
146
|
+
await vi.advanceTimersByTimeAsync(1100)
|
|
147
|
+
// Wait for 503 retry (1000ms — second retry delay)
|
|
148
|
+
await vi.advanceTimersByTimeAsync(1100)
|
|
149
|
+
|
|
150
|
+
const res = await promise
|
|
151
|
+
expect(res.ok).toBe(true)
|
|
152
|
+
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
it("429 is not retried when retry: false", async () => {
|
|
156
|
+
const fetchSpy = vi.fn().mockResolvedValue(
|
|
157
|
+
mockResponse(429, {}, { "Retry-After": "2" }),
|
|
158
|
+
)
|
|
159
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
160
|
+
|
|
161
|
+
// With retry: false, maxRetries becomes 0
|
|
162
|
+
await expect(
|
|
163
|
+
fetchWithRetry("http://api.test/data", { retry: false, timeout: 5000 }),
|
|
164
|
+
).rejects.toThrow(RateLimitError)
|
|
165
|
+
|
|
166
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
it("succeeds after one 429 retry with correct response data", async () => {
|
|
170
|
+
const expectedData = { users: [{ id: 1, name: "Alice" }], total: 1 }
|
|
171
|
+
const fetchSpy = vi.fn()
|
|
172
|
+
.mockResolvedValueOnce(mockResponse(429, {}, { "Retry-After": "1" }))
|
|
173
|
+
.mockResolvedValueOnce(mockResponse(200, expectedData))
|
|
174
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
175
|
+
|
|
176
|
+
const promise = fetchWithRetry("http://api.test/users", { maxRetries: 3, timeout: 10000 })
|
|
177
|
+
|
|
178
|
+
await vi.advanceTimersByTimeAsync(1100)
|
|
179
|
+
|
|
180
|
+
const res = await promise
|
|
181
|
+
expect(res.ok).toBe(true)
|
|
182
|
+
const data = await res.json()
|
|
183
|
+
expect(data).toEqual(expectedData)
|
|
184
|
+
})
|
|
185
|
+
})
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration test — Task 94: Realtime multi-tenant isolation
|
|
3
|
+
*
|
|
4
|
+
* Tests: subscribe to project A -> insert in A -> event received ->
|
|
5
|
+
* insert in B -> no event on A's subscription.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
9
|
+
import { RealtimeClient, type RealtimePayload } from "../src/realtime.js"
|
|
10
|
+
|
|
11
|
+
// ─── Mock WebSocket ──────────────────────────────────────────────────────────
|
|
12
|
+
|
|
13
|
+
interface MockWebSocketInstance {
|
|
14
|
+
url: string
|
|
15
|
+
readyState: number
|
|
16
|
+
onopen: ((event: Event) => void) | null
|
|
17
|
+
onclose: ((event: CloseEvent) => void) | null
|
|
18
|
+
onmessage: ((event: MessageEvent) => void) | null
|
|
19
|
+
onerror: ((event: Event) => void) | null
|
|
20
|
+
send: ReturnType<typeof vi.fn>
|
|
21
|
+
close: ReturnType<typeof vi.fn>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function createMockWebSocketClass() {
|
|
25
|
+
const instances: MockWebSocketInstance[] = []
|
|
26
|
+
|
|
27
|
+
class MockWebSocket {
|
|
28
|
+
static OPEN = 1
|
|
29
|
+
static CONNECTING = 0
|
|
30
|
+
static CLOSED = 3
|
|
31
|
+
|
|
32
|
+
url: string
|
|
33
|
+
readyState = 0
|
|
34
|
+
onopen: ((event: Event) => void) | null = null
|
|
35
|
+
onclose: ((event: CloseEvent) => void) | null = null
|
|
36
|
+
onmessage: ((event: MessageEvent) => void) | null = null
|
|
37
|
+
onerror: ((event: Event) => void) | null = null
|
|
38
|
+
send = vi.fn()
|
|
39
|
+
close = vi.fn()
|
|
40
|
+
|
|
41
|
+
constructor(url: string) {
|
|
42
|
+
this.url = url
|
|
43
|
+
instances.push(this as unknown as MockWebSocketInstance)
|
|
44
|
+
|
|
45
|
+
// Auto-open after a microtask
|
|
46
|
+
queueMicrotask(() => {
|
|
47
|
+
this.readyState = 1 // OPEN
|
|
48
|
+
this.onopen?.({} as Event)
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return { MockWebSocket, instances }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Simulate a server message arriving on a WebSocket instance. */
|
|
57
|
+
function simulateServerMessage(ws: MockWebSocketInstance, msg: Record<string, unknown>): void {
|
|
58
|
+
ws.onmessage?.({ data: JSON.stringify(msg) } as MessageEvent)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ─── Tests ───────────────────────────────────────────────────────────────────
|
|
62
|
+
|
|
63
|
+
describe("Task 94 — Realtime multi-tenant isolation", () => {
|
|
64
|
+
let MockWS: ReturnType<typeof createMockWebSocketClass>
|
|
65
|
+
|
|
66
|
+
beforeEach(() => {
|
|
67
|
+
vi.restoreAllMocks()
|
|
68
|
+
MockWS = createMockWebSocketClass()
|
|
69
|
+
vi.stubGlobal("WebSocket", MockWS.MockWebSocket)
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
afterEach(() => {
|
|
73
|
+
vi.unstubAllGlobals()
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
describe("Single tenant subscription", () => {
|
|
77
|
+
it("receives INSERT events on the subscribed channel", async () => {
|
|
78
|
+
const client = new RealtimeClient("ws://localhost:4000/realtime", { apikey: "anon-key-A" })
|
|
79
|
+
const received: RealtimePayload<Record<string, unknown>>[] = []
|
|
80
|
+
|
|
81
|
+
client
|
|
82
|
+
.channel<Record<string, unknown>>("public:posts")
|
|
83
|
+
.on("postgres_changes", { event: "INSERT", schema: "public", table: "posts" }, (payload) => {
|
|
84
|
+
received.push(payload)
|
|
85
|
+
})
|
|
86
|
+
.subscribe()
|
|
87
|
+
|
|
88
|
+
// Wait for WebSocket to open
|
|
89
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
90
|
+
|
|
91
|
+
const ws = MockWS.instances[0]!
|
|
92
|
+
|
|
93
|
+
// Simulate server confirming subscription
|
|
94
|
+
simulateServerMessage(ws, {
|
|
95
|
+
type: "system",
|
|
96
|
+
status: "ok",
|
|
97
|
+
message: "subscribed to public:posts",
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
// Simulate an INSERT event
|
|
101
|
+
simulateServerMessage(ws, {
|
|
102
|
+
type: "change",
|
|
103
|
+
channel: "public:posts",
|
|
104
|
+
event: "INSERT",
|
|
105
|
+
payload: {
|
|
106
|
+
new: { id: 1, title: "Hello from project A", author_id: "user-1" },
|
|
107
|
+
old: null,
|
|
108
|
+
},
|
|
109
|
+
timestamp: "2024-01-01T00:00:00Z",
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
expect(received).toHaveLength(1)
|
|
113
|
+
expect(received[0]!.eventType).toBe("INSERT")
|
|
114
|
+
expect(received[0]!.new).toEqual({ id: 1, title: "Hello from project A", author_id: "user-1" })
|
|
115
|
+
})
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
describe("Multi-tenant isolation", () => {
|
|
119
|
+
it("project A subscription does NOT receive project B events", async () => {
|
|
120
|
+
// Project A client
|
|
121
|
+
const clientA = new RealtimeClient("ws://localhost:4000/realtime", { apikey: "anon-key-project-A" })
|
|
122
|
+
const receivedA: RealtimePayload<Record<string, unknown>>[] = []
|
|
123
|
+
|
|
124
|
+
clientA
|
|
125
|
+
.channel<Record<string, unknown>>("projectA:posts")
|
|
126
|
+
.on("postgres_changes", { event: "*", schema: "projectA", table: "posts" }, (payload) => {
|
|
127
|
+
receivedA.push(payload)
|
|
128
|
+
})
|
|
129
|
+
.subscribe()
|
|
130
|
+
|
|
131
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
132
|
+
const wsA = MockWS.instances[0]!
|
|
133
|
+
|
|
134
|
+
// Confirm subscription for project A
|
|
135
|
+
simulateServerMessage(wsA, {
|
|
136
|
+
type: "system",
|
|
137
|
+
status: "ok",
|
|
138
|
+
message: "subscribed to projectA:posts",
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
// Simulate INSERT in project A's channel
|
|
142
|
+
simulateServerMessage(wsA, {
|
|
143
|
+
type: "change",
|
|
144
|
+
channel: "projectA:posts",
|
|
145
|
+
event: "INSERT",
|
|
146
|
+
payload: {
|
|
147
|
+
new: { id: 1, title: "Project A post" },
|
|
148
|
+
old: null,
|
|
149
|
+
},
|
|
150
|
+
timestamp: "2024-01-01T00:00:01Z",
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
// Now simulate a message from project B arriving on the same WebSocket
|
|
154
|
+
// (this would be the server-side routing — in a real system, the server
|
|
155
|
+
// would NOT route project B events to project A's connection)
|
|
156
|
+
simulateServerMessage(wsA, {
|
|
157
|
+
type: "change",
|
|
158
|
+
channel: "projectB:posts", // Different channel
|
|
159
|
+
event: "INSERT",
|
|
160
|
+
payload: {
|
|
161
|
+
new: { id: 99, title: "Project B post — should not be received" },
|
|
162
|
+
old: null,
|
|
163
|
+
},
|
|
164
|
+
timestamp: "2024-01-01T00:00:02Z",
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
// Only project A's event should be received
|
|
168
|
+
expect(receivedA).toHaveLength(1)
|
|
169
|
+
expect(receivedA[0]!.new).toEqual({ id: 1, title: "Project A post" })
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
it("two independent clients receive only their own events", async () => {
|
|
173
|
+
// Project A
|
|
174
|
+
const clientA = new RealtimeClient("ws://a.realtime.test", { apikey: "key-A" })
|
|
175
|
+
const eventsA: RealtimePayload<Record<string, unknown>>[] = []
|
|
176
|
+
clientA
|
|
177
|
+
.channel<Record<string, unknown>>("public:todos")
|
|
178
|
+
.on("postgres_changes", { event: "INSERT" }, (p) => eventsA.push(p))
|
|
179
|
+
.subscribe()
|
|
180
|
+
|
|
181
|
+
// Project B
|
|
182
|
+
const clientB = new RealtimeClient("ws://b.realtime.test", { apikey: "key-B" })
|
|
183
|
+
const eventsB: RealtimePayload<Record<string, unknown>>[] = []
|
|
184
|
+
clientB
|
|
185
|
+
.channel<Record<string, unknown>>("public:todos")
|
|
186
|
+
.on("postgres_changes", { event: "INSERT" }, (p) => eventsB.push(p))
|
|
187
|
+
.subscribe()
|
|
188
|
+
|
|
189
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
190
|
+
|
|
191
|
+
const wsA = MockWS.instances[0]!
|
|
192
|
+
const wsB = MockWS.instances[1]!
|
|
193
|
+
|
|
194
|
+
// Confirm subscriptions
|
|
195
|
+
simulateServerMessage(wsA, { type: "system", status: "ok", message: "subscribed to public:todos" })
|
|
196
|
+
simulateServerMessage(wsB, { type: "system", status: "ok", message: "subscribed to public:todos" })
|
|
197
|
+
|
|
198
|
+
// Insert in A
|
|
199
|
+
simulateServerMessage(wsA, {
|
|
200
|
+
type: "change",
|
|
201
|
+
channel: "public:todos",
|
|
202
|
+
event: "INSERT",
|
|
203
|
+
payload: { new: { id: 1, text: "A's todo" }, old: null },
|
|
204
|
+
timestamp: "t1",
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
// Insert in B
|
|
208
|
+
simulateServerMessage(wsB, {
|
|
209
|
+
type: "change",
|
|
210
|
+
channel: "public:todos",
|
|
211
|
+
event: "INSERT",
|
|
212
|
+
payload: { new: { id: 2, text: "B's todo" }, old: null },
|
|
213
|
+
timestamp: "t2",
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
// A only sees A's event, B only sees B's event
|
|
217
|
+
expect(eventsA).toHaveLength(1)
|
|
218
|
+
expect(eventsA[0]!.new).toEqual({ id: 1, text: "A's todo" })
|
|
219
|
+
|
|
220
|
+
expect(eventsB).toHaveLength(1)
|
|
221
|
+
expect(eventsB[0]!.new).toEqual({ id: 2, text: "B's todo" })
|
|
222
|
+
})
|
|
223
|
+
})
|
|
224
|
+
|
|
225
|
+
describe("Channel matching", () => {
|
|
226
|
+
it("events are dispatched to the correct channel only", async () => {
|
|
227
|
+
const client = new RealtimeClient("ws://localhost:4000/realtime", { apikey: "key" })
|
|
228
|
+
const postsEvents: RealtimePayload<Record<string, unknown>>[] = []
|
|
229
|
+
const commentsEvents: RealtimePayload<Record<string, unknown>>[] = []
|
|
230
|
+
|
|
231
|
+
client
|
|
232
|
+
.channel<Record<string, unknown>>("public:posts")
|
|
233
|
+
.on("postgres_changes", { event: "*" }, (p) => postsEvents.push(p))
|
|
234
|
+
.subscribe()
|
|
235
|
+
|
|
236
|
+
client
|
|
237
|
+
.channel<Record<string, unknown>>("public:comments")
|
|
238
|
+
.on("postgres_changes", { event: "*" }, (p) => commentsEvents.push(p))
|
|
239
|
+
.subscribe()
|
|
240
|
+
|
|
241
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
242
|
+
const ws = MockWS.instances[0]!
|
|
243
|
+
|
|
244
|
+
// Confirm both
|
|
245
|
+
simulateServerMessage(ws, { type: "system", status: "ok", message: "subscribed to public:posts" })
|
|
246
|
+
simulateServerMessage(ws, { type: "system", status: "ok", message: "subscribed to public:comments" })
|
|
247
|
+
|
|
248
|
+
// Insert into posts
|
|
249
|
+
simulateServerMessage(ws, {
|
|
250
|
+
type: "change",
|
|
251
|
+
channel: "public:posts",
|
|
252
|
+
event: "INSERT",
|
|
253
|
+
payload: { new: { id: 1 }, old: null },
|
|
254
|
+
timestamp: "t1",
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
// Insert into comments
|
|
258
|
+
simulateServerMessage(ws, {
|
|
259
|
+
type: "change",
|
|
260
|
+
channel: "public:comments",
|
|
261
|
+
event: "INSERT",
|
|
262
|
+
payload: { new: { id: 100, post_id: 1 }, old: null },
|
|
263
|
+
timestamp: "t2",
|
|
264
|
+
})
|
|
265
|
+
|
|
266
|
+
expect(postsEvents).toHaveLength(1)
|
|
267
|
+
expect(postsEvents[0]!.new).toEqual({ id: 1 })
|
|
268
|
+
|
|
269
|
+
expect(commentsEvents).toHaveLength(1)
|
|
270
|
+
expect(commentsEvents[0]!.new).toEqual({ id: 100, post_id: 1 })
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
it("event type filtering: INSERT listener ignores UPDATE events", async () => {
|
|
274
|
+
const client = new RealtimeClient("ws://localhost:4000/realtime", { apikey: "key" })
|
|
275
|
+
const inserts: RealtimePayload<Record<string, unknown>>[] = []
|
|
276
|
+
|
|
277
|
+
client
|
|
278
|
+
.channel<Record<string, unknown>>("public:posts")
|
|
279
|
+
.on("postgres_changes", { event: "INSERT" }, (p) => inserts.push(p))
|
|
280
|
+
.subscribe()
|
|
281
|
+
|
|
282
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
283
|
+
const ws = MockWS.instances[0]!
|
|
284
|
+
simulateServerMessage(ws, { type: "system", status: "ok", message: "subscribed to public:posts" })
|
|
285
|
+
|
|
286
|
+
// Send UPDATE
|
|
287
|
+
simulateServerMessage(ws, {
|
|
288
|
+
type: "change",
|
|
289
|
+
channel: "public:posts",
|
|
290
|
+
event: "UPDATE",
|
|
291
|
+
payload: { new: { id: 1, title: "updated" }, old: { id: 1, title: "original" } },
|
|
292
|
+
timestamp: "t1",
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
// Send INSERT
|
|
296
|
+
simulateServerMessage(ws, {
|
|
297
|
+
type: "change",
|
|
298
|
+
channel: "public:posts",
|
|
299
|
+
event: "INSERT",
|
|
300
|
+
payload: { new: { id: 2, title: "new post" }, old: null },
|
|
301
|
+
timestamp: "t2",
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
expect(inserts).toHaveLength(1)
|
|
305
|
+
expect(inserts[0]!.eventType).toBe("INSERT")
|
|
306
|
+
})
|
|
307
|
+
|
|
308
|
+
it("wildcard (*) listener receives all event types", async () => {
|
|
309
|
+
const client = new RealtimeClient("ws://localhost:4000/realtime", { apikey: "key" })
|
|
310
|
+
const allEvents: RealtimePayload<Record<string, unknown>>[] = []
|
|
311
|
+
|
|
312
|
+
client
|
|
313
|
+
.channel<Record<string, unknown>>("public:posts")
|
|
314
|
+
.on("postgres_changes", { event: "*" }, (p) => allEvents.push(p))
|
|
315
|
+
.subscribe()
|
|
316
|
+
|
|
317
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
318
|
+
const ws = MockWS.instances[0]!
|
|
319
|
+
simulateServerMessage(ws, { type: "system", status: "ok", message: "subscribed to public:posts" })
|
|
320
|
+
|
|
321
|
+
simulateServerMessage(ws, {
|
|
322
|
+
type: "change", channel: "public:posts", event: "INSERT",
|
|
323
|
+
payload: { new: { id: 1 }, old: null }, timestamp: "t1",
|
|
324
|
+
})
|
|
325
|
+
simulateServerMessage(ws, {
|
|
326
|
+
type: "change", channel: "public:posts", event: "UPDATE",
|
|
327
|
+
payload: { new: { id: 1 }, old: { id: 1 } }, timestamp: "t2",
|
|
328
|
+
})
|
|
329
|
+
simulateServerMessage(ws, {
|
|
330
|
+
type: "change", channel: "public:posts", event: "DELETE",
|
|
331
|
+
payload: { new: null, old: { id: 1 } }, timestamp: "t3",
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
expect(allEvents).toHaveLength(3)
|
|
335
|
+
expect(allEvents.map((e) => e.eventType)).toEqual(["INSERT", "UPDATE", "DELETE"])
|
|
336
|
+
})
|
|
337
|
+
})
|
|
338
|
+
|
|
339
|
+
describe("Unsubscribe stops event delivery", () => {
|
|
340
|
+
it("no events received after unsubscribe", async () => {
|
|
341
|
+
const client = new RealtimeClient("ws://localhost:4000/realtime", { apikey: "key" })
|
|
342
|
+
const events: RealtimePayload<Record<string, unknown>>[] = []
|
|
343
|
+
|
|
344
|
+
const sub = client
|
|
345
|
+
.channel<Record<string, unknown>>("public:posts")
|
|
346
|
+
.on("postgres_changes", { event: "*" }, (p) => events.push(p))
|
|
347
|
+
.subscribe()
|
|
348
|
+
|
|
349
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
350
|
+
const ws = MockWS.instances[0]!
|
|
351
|
+
simulateServerMessage(ws, { type: "system", status: "ok", message: "subscribed to public:posts" })
|
|
352
|
+
|
|
353
|
+
// Receive one event
|
|
354
|
+
simulateServerMessage(ws, {
|
|
355
|
+
type: "change", channel: "public:posts", event: "INSERT",
|
|
356
|
+
payload: { new: { id: 1 }, old: null }, timestamp: "t1",
|
|
357
|
+
})
|
|
358
|
+
expect(events).toHaveLength(1)
|
|
359
|
+
|
|
360
|
+
// Unsubscribe
|
|
361
|
+
sub.unsubscribe()
|
|
362
|
+
|
|
363
|
+
// This event should NOT be delivered
|
|
364
|
+
simulateServerMessage(ws, {
|
|
365
|
+
type: "change", channel: "public:posts", event: "INSERT",
|
|
366
|
+
payload: { new: { id: 2 }, old: null }, timestamp: "t2",
|
|
367
|
+
})
|
|
368
|
+
|
|
369
|
+
expect(events).toHaveLength(1)
|
|
370
|
+
})
|
|
371
|
+
})
|
|
372
|
+
})
|