@supatype/client 0.1.0-alpha.6
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 +7 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/dist/auth.d.ts +243 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +560 -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 +137 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +225 -0
- package/dist/index.js.map +1 -0
- package/dist/query.d.ts +53 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +216 -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 +79 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +130 -0
- package/dist/storage.js.map +1 -0
- package/dist/types.d.ts +141 -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 +713 -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 +418 -0
- package/src/query.ts +280 -0
- package/src/realtime.ts +418 -0
- package/src/retry.ts +35 -0
- package/src/serverless-docs.ts +107 -0
- package/src/storage.ts +182 -0
- package/src/types.ts +184 -0
- package/tests/auth.test.ts +282 -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 +123 -0
- package/tsconfig.json +11 -0
- package/tsconfig.tsbuildinfo +1 -0
|
@@ -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
|
+
})
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration test — Task 90: SDK retry behaviour
|
|
3
|
+
*
|
|
4
|
+
* Simulates 503 -> SDK retries 3x with backoff -> succeeds or throws after max retries.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
8
|
+
import { fetchWithRetry } from "../src/fetch-with-retry.js"
|
|
9
|
+
import { NetworkError } from "../src/errors.js"
|
|
10
|
+
|
|
11
|
+
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
12
|
+
|
|
13
|
+
function mockResponse(status: number, body: unknown = {}): Response {
|
|
14
|
+
return {
|
|
15
|
+
ok: status >= 200 && status < 300,
|
|
16
|
+
status,
|
|
17
|
+
json: vi.fn().mockResolvedValue(body),
|
|
18
|
+
headers: new Headers(),
|
|
19
|
+
statusText: status === 503 ? "Service Unavailable" : "OK",
|
|
20
|
+
} as unknown as Response
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// ─── Tests ───────────────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
describe("Task 90 — SDK retry integration", () => {
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
vi.restoreAllMocks()
|
|
28
|
+
vi.useFakeTimers()
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
afterEach(() => {
|
|
32
|
+
vi.useRealTimers()
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it("succeeds immediately on 200 with no retries", async () => {
|
|
36
|
+
const fetchSpy = vi.fn().mockResolvedValue(mockResponse(200, { data: "ok" }))
|
|
37
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
38
|
+
|
|
39
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 5000 })
|
|
40
|
+
const res = await promise
|
|
41
|
+
|
|
42
|
+
expect(res.ok).toBe(true)
|
|
43
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it("retries on 503 and succeeds on second attempt", async () => {
|
|
47
|
+
const fetchSpy = vi.fn()
|
|
48
|
+
.mockResolvedValueOnce(mockResponse(503))
|
|
49
|
+
.mockResolvedValueOnce(mockResponse(200, { data: "recovered" }))
|
|
50
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
51
|
+
|
|
52
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 5000 })
|
|
53
|
+
|
|
54
|
+
// Advance past first retry delay (200ms)
|
|
55
|
+
await vi.advanceTimersByTimeAsync(250)
|
|
56
|
+
|
|
57
|
+
const res = await promise
|
|
58
|
+
expect(res.ok).toBe(true)
|
|
59
|
+
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it("retries on 500 server errors", async () => {
|
|
63
|
+
const fetchSpy = vi.fn()
|
|
64
|
+
.mockResolvedValueOnce(mockResponse(500))
|
|
65
|
+
.mockResolvedValueOnce(mockResponse(502))
|
|
66
|
+
.mockResolvedValueOnce(mockResponse(200, { data: "ok" }))
|
|
67
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
68
|
+
|
|
69
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 5000 })
|
|
70
|
+
|
|
71
|
+
// Advance through retry delays
|
|
72
|
+
await vi.advanceTimersByTimeAsync(250) // First retry (200ms delay)
|
|
73
|
+
await vi.advanceTimersByTimeAsync(1100) // Second retry (1000ms delay)
|
|
74
|
+
|
|
75
|
+
const res = await promise
|
|
76
|
+
expect(res.ok).toBe(true)
|
|
77
|
+
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it("retries up to maxRetries then returns the 503 response", async () => {
|
|
81
|
+
const fetchSpy = vi.fn().mockResolvedValue(mockResponse(503))
|
|
82
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
83
|
+
|
|
84
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 5000 })
|
|
85
|
+
|
|
86
|
+
// Advance through all retry delays
|
|
87
|
+
await vi.advanceTimersByTimeAsync(250) // retry 1 (200ms)
|
|
88
|
+
await vi.advanceTimersByTimeAsync(1100) // retry 2 (1000ms)
|
|
89
|
+
await vi.advanceTimersByTimeAsync(3100) // retry 3 (3000ms)
|
|
90
|
+
|
|
91
|
+
const res = await promise
|
|
92
|
+
// After all retries exhausted, the last 503 response is returned
|
|
93
|
+
expect(res.status).toBe(503)
|
|
94
|
+
expect(fetchSpy).toHaveBeenCalledTimes(4) // initial + 3 retries
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it("does not retry on 4xx client errors (except 429)", async () => {
|
|
98
|
+
const fetchSpy = vi.fn().mockResolvedValue(mockResponse(404, { error: "Not found" }))
|
|
99
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
100
|
+
|
|
101
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 5000 })
|
|
102
|
+
const res = await promise
|
|
103
|
+
|
|
104
|
+
expect(res.status).toBe(404)
|
|
105
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1) // No retries for 4xx
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it("does not retry on 401", async () => {
|
|
109
|
+
const fetchSpy = vi.fn().mockResolvedValue(mockResponse(401, { error: "Unauthorized" }))
|
|
110
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
111
|
+
|
|
112
|
+
const res = await fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 5000 })
|
|
113
|
+
|
|
114
|
+
expect(res.status).toBe(401)
|
|
115
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it("retries on network errors (fetch throws)", async () => {
|
|
119
|
+
const fetchSpy = vi.fn()
|
|
120
|
+
.mockRejectedValueOnce(new Error("ECONNREFUSED"))
|
|
121
|
+
.mockRejectedValueOnce(new Error("ECONNREFUSED"))
|
|
122
|
+
.mockResolvedValueOnce(mockResponse(200, { data: "ok" }))
|
|
123
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
124
|
+
|
|
125
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 5000 })
|
|
126
|
+
|
|
127
|
+
await vi.advanceTimersByTimeAsync(250)
|
|
128
|
+
await vi.advanceTimersByTimeAsync(1100)
|
|
129
|
+
|
|
130
|
+
const res = await promise
|
|
131
|
+
expect(res.ok).toBe(true)
|
|
132
|
+
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it("throws NetworkError after exhausting retries on network failures", async () => {
|
|
136
|
+
vi.useRealTimers()
|
|
137
|
+
const fetchSpy = vi.fn().mockRejectedValue(new Error("ECONNREFUSED"))
|
|
138
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
139
|
+
|
|
140
|
+
await expect(
|
|
141
|
+
fetchWithRetry("http://api.test/data", { maxRetries: 0, timeout: 5000 }),
|
|
142
|
+
).rejects.toThrow(NetworkError)
|
|
143
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
144
|
+
vi.useFakeTimers()
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
it("throws NetworkError with CONNECTION_REFUSED code", async () => {
|
|
148
|
+
vi.useRealTimers()
|
|
149
|
+
const fetchSpy = vi.fn().mockRejectedValue(new Error("ECONNREFUSED"))
|
|
150
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
151
|
+
|
|
152
|
+
try {
|
|
153
|
+
await fetchWithRetry("http://api.test/data", { maxRetries: 0, timeout: 5000 })
|
|
154
|
+
expect.fail("Should have thrown")
|
|
155
|
+
} catch (err) {
|
|
156
|
+
expect(err).toBeInstanceOf(NetworkError)
|
|
157
|
+
expect((err as NetworkError).code).toBe("NETWORK_CONNECTION_REFUSED")
|
|
158
|
+
}
|
|
159
|
+
vi.useFakeTimers()
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
it("respects retry: false option — no retries attempted", async () => {
|
|
163
|
+
const fetchSpy = vi.fn().mockResolvedValue(mockResponse(503))
|
|
164
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
165
|
+
|
|
166
|
+
const res = await fetchWithRetry("http://api.test/data", { retry: false, timeout: 5000 })
|
|
167
|
+
|
|
168
|
+
expect(res.status).toBe(503)
|
|
169
|
+
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
it("uses exponential backoff delays: 200ms, 1000ms, 3000ms", async () => {
|
|
173
|
+
const timestamps: number[] = []
|
|
174
|
+
const fetchSpy = vi.fn().mockImplementation(async () => {
|
|
175
|
+
timestamps.push(Date.now())
|
|
176
|
+
return mockResponse(503)
|
|
177
|
+
})
|
|
178
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
179
|
+
|
|
180
|
+
const promise = fetchWithRetry("http://api.test/data", { maxRetries: 3, timeout: 30000 })
|
|
181
|
+
|
|
182
|
+
// Initial call happens immediately
|
|
183
|
+
await vi.advanceTimersByTimeAsync(0)
|
|
184
|
+
expect(timestamps).toHaveLength(1)
|
|
185
|
+
|
|
186
|
+
// First retry after ~200ms
|
|
187
|
+
await vi.advanceTimersByTimeAsync(200)
|
|
188
|
+
expect(timestamps).toHaveLength(2)
|
|
189
|
+
|
|
190
|
+
// Second retry after ~1000ms
|
|
191
|
+
await vi.advanceTimersByTimeAsync(1000)
|
|
192
|
+
expect(timestamps).toHaveLength(3)
|
|
193
|
+
|
|
194
|
+
// Third retry after ~3000ms
|
|
195
|
+
await vi.advanceTimersByTimeAsync(3000)
|
|
196
|
+
expect(timestamps).toHaveLength(4)
|
|
197
|
+
|
|
198
|
+
await promise
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
it("AbortError from timeout throws NetworkError with TIMEOUT code", async () => {
|
|
202
|
+
const abortError = new Error("The operation was aborted")
|
|
203
|
+
abortError.name = "AbortError"
|
|
204
|
+
const fetchSpy = vi.fn().mockRejectedValue(abortError)
|
|
205
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
206
|
+
|
|
207
|
+
// Timeout is handled by the AbortController in fetchWithRetry
|
|
208
|
+
await expect(
|
|
209
|
+
fetchWithRetry("http://api.test/data", { maxRetries: 0, timeout: 100 }),
|
|
210
|
+
).rejects.toThrow("timed out")
|
|
211
|
+
})
|
|
212
|
+
})
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
2
|
+
import { detectServerlessEnvironment, warnIfServerlessDirectConnection } from "../src/fetch-with-retry.js"
|
|
3
|
+
|
|
4
|
+
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Set an environment variable for the duration of a test, restoring it
|
|
8
|
+
* (or deleting it) afterwards.
|
|
9
|
+
*/
|
|
10
|
+
function withEnv(key: string, value: string): () => void {
|
|
11
|
+
const prev = process.env[key]
|
|
12
|
+
process.env[key] = value
|
|
13
|
+
return () => {
|
|
14
|
+
if (prev === undefined) {
|
|
15
|
+
delete process.env[key]
|
|
16
|
+
} else {
|
|
17
|
+
process.env[key] = prev
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ─── detectServerlessEnvironment ─────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
describe("detectServerlessEnvironment", () => {
|
|
25
|
+
let restoreEnv: (() => void) | undefined
|
|
26
|
+
|
|
27
|
+
afterEach(() => {
|
|
28
|
+
restoreEnv?.()
|
|
29
|
+
restoreEnv = undefined
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it("returns detected=false when no serverless env vars are set", () => {
|
|
33
|
+
const result = detectServerlessEnvironment()
|
|
34
|
+
expect(result.detected).toBe(false)
|
|
35
|
+
expect(result.platform).toBeNull()
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it("detects Vercel when VERCEL=1", () => {
|
|
39
|
+
restoreEnv = withEnv("VERCEL", "1")
|
|
40
|
+
const result = detectServerlessEnvironment()
|
|
41
|
+
expect(result.detected).toBe(true)
|
|
42
|
+
expect(result.platform).toBe("Vercel")
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it("does not detect Vercel when VERCEL has wrong value", () => {
|
|
46
|
+
restoreEnv = withEnv("VERCEL", "0")
|
|
47
|
+
const result = detectServerlessEnvironment()
|
|
48
|
+
// VERCEL must be exactly "1"
|
|
49
|
+
expect(result.detected).toBe(false)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it("detects AWS Lambda when AWS_LAMBDA_FUNCTION_NAME is set", () => {
|
|
53
|
+
restoreEnv = withEnv("AWS_LAMBDA_FUNCTION_NAME", "my-function")
|
|
54
|
+
const result = detectServerlessEnvironment()
|
|
55
|
+
expect(result.detected).toBe(true)
|
|
56
|
+
expect(result.platform).toBe("AWS Lambda")
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it("detects Netlify when NETLIFY=true", () => {
|
|
60
|
+
restoreEnv = withEnv("NETLIFY", "true")
|
|
61
|
+
const result = detectServerlessEnvironment()
|
|
62
|
+
expect(result.detected).toBe(true)
|
|
63
|
+
expect(result.platform).toBe("Netlify")
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it("detects Cloudflare Workers when CF_PAGES is set", () => {
|
|
67
|
+
restoreEnv = withEnv("CF_PAGES", "1")
|
|
68
|
+
const result = detectServerlessEnvironment()
|
|
69
|
+
expect(result.detected).toBe(true)
|
|
70
|
+
expect(result.platform).toBe("Cloudflare Workers")
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
// ─── warnIfServerlessDirectConnection ────────────────────────────────────────
|
|
75
|
+
|
|
76
|
+
describe("warnIfServerlessDirectConnection", () => {
|
|
77
|
+
let restoreEnv: (() => void) | undefined
|
|
78
|
+
let warnSpy: ReturnType<typeof vi.spyOn>
|
|
79
|
+
|
|
80
|
+
beforeEach(() => {
|
|
81
|
+
warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
|
|
82
|
+
// Reset the one-time guard between tests by re-importing.
|
|
83
|
+
// Since the guard is module-level state, we need to reset it.
|
|
84
|
+
// We do this by directly resetting via a dynamic import trick — but
|
|
85
|
+
// the simplest approach is to just accept the guard fires once per
|
|
86
|
+
// describe block. Instead, let's reset it manually.
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
afterEach(() => {
|
|
90
|
+
restoreEnv?.()
|
|
91
|
+
restoreEnv = undefined
|
|
92
|
+
warnSpy.mockRestore()
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it("does not warn when not in a serverless environment", () => {
|
|
96
|
+
warnIfServerlessDirectConnection("postgres://localhost:5432/mydb")
|
|
97
|
+
expect(warnSpy).not.toHaveBeenCalled()
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
it("warns when a direct postgres:// URL is used in a serverless env", () => {
|
|
101
|
+
restoreEnv = withEnv("AWS_LAMBDA_FUNCTION_NAME", "handler")
|
|
102
|
+
warnIfServerlessDirectConnection("postgres://db.example.com:5432/mydb")
|
|
103
|
+
expect(warnSpy).toHaveBeenCalledOnce()
|
|
104
|
+
expect(warnSpy.mock.calls[0]?.[0]).toContain(
|
|
105
|
+
"Direct database connections are not recommended in serverless environments"
|
|
106
|
+
)
|
|
107
|
+
expect(warnSpy.mock.calls[0]?.[0]).toContain("AWS Lambda")
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it("does not warn for HTTP gateway URLs in a serverless env", () => {
|
|
111
|
+
restoreEnv = withEnv("VERCEL", "1")
|
|
112
|
+
warnIfServerlessDirectConnection("https://my-project.supatype.co")
|
|
113
|
+
expect(warnSpy).not.toHaveBeenCalled()
|
|
114
|
+
})
|
|
115
|
+
})
|