@thebookingkit/server 0.1.2 → 0.1.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.
Files changed (95) hide show
  1. package/README.md +2 -2
  2. package/dist/adapters/calendar-adapter.d.ts +47 -0
  3. package/dist/adapters/calendar-adapter.d.ts.map +1 -0
  4. package/dist/adapters/calendar-adapter.js +2 -0
  5. package/dist/adapters/calendar-adapter.js.map +1 -0
  6. package/dist/adapters/email-adapter.d.ts +65 -0
  7. package/dist/adapters/email-adapter.d.ts.map +1 -0
  8. package/dist/adapters/email-adapter.js +41 -0
  9. package/dist/adapters/email-adapter.js.map +1 -0
  10. package/dist/adapters/index.d.ts +9 -0
  11. package/dist/adapters/index.d.ts.map +1 -0
  12. package/dist/adapters/index.js +3 -0
  13. package/dist/adapters/index.js.map +1 -0
  14. package/dist/adapters/job-adapter.d.ts +26 -0
  15. package/dist/adapters/job-adapter.d.ts.map +1 -0
  16. package/dist/adapters/job-adapter.js +13 -0
  17. package/dist/adapters/job-adapter.js.map +1 -0
  18. package/dist/adapters/payment-adapter.d.ts +106 -0
  19. package/dist/adapters/payment-adapter.d.ts.map +1 -0
  20. package/dist/adapters/payment-adapter.js +8 -0
  21. package/dist/adapters/payment-adapter.js.map +1 -0
  22. package/dist/adapters/sms-adapter.d.ts +33 -0
  23. package/dist/adapters/sms-adapter.d.ts.map +1 -0
  24. package/dist/adapters/sms-adapter.js +8 -0
  25. package/dist/adapters/sms-adapter.js.map +1 -0
  26. package/{src/adapters/storage-adapter.ts → dist/adapters/storage-adapter.d.ts} +5 -4
  27. package/dist/adapters/storage-adapter.d.ts.map +1 -0
  28. package/dist/adapters/storage-adapter.js +2 -0
  29. package/dist/adapters/storage-adapter.js.map +1 -0
  30. package/dist/api.d.ts +223 -0
  31. package/dist/api.d.ts.map +1 -0
  32. package/dist/api.js +286 -0
  33. package/dist/api.js.map +1 -0
  34. package/dist/auth.d.ts +71 -0
  35. package/dist/auth.d.ts.map +1 -0
  36. package/dist/auth.js +90 -0
  37. package/dist/auth.js.map +1 -0
  38. package/dist/booking-tokens.d.ts +23 -0
  39. package/dist/booking-tokens.d.ts.map +1 -0
  40. package/dist/booking-tokens.js +52 -0
  41. package/dist/booking-tokens.js.map +1 -0
  42. package/dist/email-templates.d.ts +32 -0
  43. package/dist/email-templates.d.ts.map +1 -0
  44. package/{src/email-templates.ts → dist/email-templates.js} +14 -34
  45. package/dist/email-templates.js.map +1 -0
  46. package/dist/index.d.ts +13 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +22 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/multi-tenancy.d.ts +123 -0
  51. package/dist/multi-tenancy.d.ts.map +1 -0
  52. package/dist/multi-tenancy.js +197 -0
  53. package/dist/multi-tenancy.js.map +1 -0
  54. package/dist/notification-jobs.d.ts +143 -0
  55. package/dist/notification-jobs.d.ts.map +1 -0
  56. package/dist/notification-jobs.js +278 -0
  57. package/dist/notification-jobs.js.map +1 -0
  58. package/dist/serialization-retry.d.ts +28 -0
  59. package/dist/serialization-retry.d.ts.map +1 -0
  60. package/dist/serialization-retry.js +71 -0
  61. package/dist/serialization-retry.js.map +1 -0
  62. package/dist/webhooks.d.ts +164 -0
  63. package/dist/webhooks.d.ts.map +1 -0
  64. package/dist/webhooks.js +239 -0
  65. package/dist/webhooks.js.map +1 -0
  66. package/dist/workflows.d.ts +169 -0
  67. package/dist/workflows.d.ts.map +1 -0
  68. package/dist/workflows.js +271 -0
  69. package/dist/workflows.js.map +1 -0
  70. package/package.json +21 -2
  71. package/CHANGELOG.md +0 -9
  72. package/src/__tests__/api.test.ts +0 -354
  73. package/src/__tests__/auth.test.ts +0 -111
  74. package/src/__tests__/concurrent-booking.test.ts +0 -170
  75. package/src/__tests__/multi-tenancy.test.ts +0 -267
  76. package/src/__tests__/serialization-retry.test.ts +0 -76
  77. package/src/__tests__/webhooks.test.ts +0 -412
  78. package/src/__tests__/workflows.test.ts +0 -422
  79. package/src/adapters/calendar-adapter.ts +0 -49
  80. package/src/adapters/email-adapter.ts +0 -108
  81. package/src/adapters/index.ts +0 -36
  82. package/src/adapters/job-adapter.ts +0 -26
  83. package/src/adapters/payment-adapter.ts +0 -118
  84. package/src/adapters/sms-adapter.ts +0 -35
  85. package/src/api.ts +0 -446
  86. package/src/auth.ts +0 -146
  87. package/src/booking-tokens.ts +0 -61
  88. package/src/index.ts +0 -192
  89. package/src/multi-tenancy.ts +0 -301
  90. package/src/notification-jobs.ts +0 -428
  91. package/src/serialization-retry.ts +0 -94
  92. package/src/webhooks.ts +0 -378
  93. package/src/workflows.ts +0 -441
  94. package/tsconfig.json +0 -9
  95. package/vitest.config.ts +0 -7
@@ -1,354 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
- import {
3
- createErrorResponse,
4
- createSuccessResponse,
5
- createPaginatedResponse,
6
- generateApiKey,
7
- hashApiKey,
8
- verifyApiKey,
9
- hasScope,
10
- isKeyExpired,
11
- checkRateLimit,
12
- encodeCursor,
13
- decodeCursor,
14
- validateSlotQueryParams,
15
- parseSortParam,
16
- API_ERROR_CODES,
17
- type ApiKeyScope,
18
- } from "../api.js";
19
-
20
- // Set the required env var for API key hashing in tests
21
- process.env.THEBOOKINGKIT_API_KEY_SECRET = "test-secret-for-unit-tests-only";
22
-
23
- // ---------------------------------------------------------------------------
24
- // Response Helpers
25
- // ---------------------------------------------------------------------------
26
-
27
- describe("createErrorResponse", () => {
28
- it("creates a standard error envelope", () => {
29
- const response = createErrorResponse("NOT_FOUND", "Booking not found");
30
- expect(response).toEqual({
31
- error: { code: "NOT_FOUND", message: "Booking not found" },
32
- });
33
- });
34
-
35
- it("includes details when provided", () => {
36
- const response = createErrorResponse(
37
- "VALIDATION_ERROR",
38
- "Invalid input",
39
- { field: "email" },
40
- );
41
- expect(response.error.details).toEqual({ field: "email" });
42
- });
43
-
44
- it("omits details when not provided", () => {
45
- const response = createErrorResponse("UNAUTHORIZED", "Invalid key");
46
- expect(response.error.details).toBeUndefined();
47
- });
48
- });
49
-
50
- describe("createSuccessResponse", () => {
51
- it("wraps data in a success envelope", () => {
52
- const response = createSuccessResponse({ id: "bk-1" });
53
- expect(response).toEqual({ data: { id: "bk-1" } });
54
- });
55
-
56
- it("includes meta when provided", () => {
57
- const response = createSuccessResponse([], {
58
- nextCursor: "abc",
59
- hasMore: true,
60
- });
61
- expect(response.meta?.nextCursor).toBe("abc");
62
- });
63
- });
64
-
65
- describe("createPaginatedResponse", () => {
66
- it("creates paginated response with cursor", () => {
67
- const response = createPaginatedResponse(["a", "b"], "cursor123", 10);
68
- expect(response.data).toEqual(["a", "b"]);
69
- expect(response.meta.nextCursor).toBe("cursor123");
70
- expect(response.meta.hasMore).toBe(true);
71
- expect(response.meta.total).toBe(10);
72
- });
73
-
74
- it("marks hasMore false when nextCursor is null", () => {
75
- const response = createPaginatedResponse(["a"], null);
76
- expect(response.meta.hasMore).toBe(false);
77
- expect(response.meta.nextCursor).toBeNull();
78
- });
79
- });
80
-
81
- // ---------------------------------------------------------------------------
82
- // API Key Management
83
- // ---------------------------------------------------------------------------
84
-
85
- describe("generateApiKey", () => {
86
- it("generates a key with the given prefix", () => {
87
- const { key } = generateApiKey("sk_live_");
88
- expect(key).toMatch(/^sk_live_[0-9a-f]{64}$/);
89
- });
90
-
91
- it("generates a display prefix", () => {
92
- const { prefix } = generateApiKey("sk_live_");
93
- expect(prefix).toContain("...");
94
- });
95
-
96
- it("generates a 64-char hex hash", () => {
97
- const { hash } = generateApiKey();
98
- expect(hash).toMatch(/^[0-9a-f]{64}$/);
99
- });
100
-
101
- it("generates unique keys each time", () => {
102
- const { key: k1 } = generateApiKey();
103
- const { key: k2 } = generateApiKey();
104
- expect(k1).not.toBe(k2);
105
- });
106
- });
107
-
108
- describe("hashApiKey", () => {
109
- it("throws when THEBOOKINGKIT_API_KEY_SECRET is missing", () => {
110
- const original = process.env.THEBOOKINGKIT_API_KEY_SECRET;
111
- delete process.env.THEBOOKINGKIT_API_KEY_SECRET;
112
- try {
113
- expect(() => hashApiKey("sk_live_test")).toThrow(
114
- "THEBOOKINGKIT_API_KEY_SECRET environment variable is required",
115
- );
116
- } finally {
117
- process.env.THEBOOKINGKIT_API_KEY_SECRET = original;
118
- }
119
- });
120
-
121
- it("accepts an explicit secret parameter", () => {
122
- const hash = hashApiKey("sk_live_test", "my-explicit-secret");
123
- expect(hash).toMatch(/^[0-9a-f]{64}$/);
124
- });
125
- });
126
-
127
- describe("verifyApiKey", () => {
128
- it("returns true for correct key", () => {
129
- const { key, hash } = generateApiKey();
130
- expect(verifyApiKey(key, hash)).toBe(true);
131
- });
132
-
133
- it("returns false for tampered key", () => {
134
- const { hash } = generateApiKey();
135
- expect(verifyApiKey("sk_live_wrong", hash)).toBe(false);
136
- });
137
-
138
- it("returns false for wrong hash", () => {
139
- const { key } = generateApiKey();
140
- const { hash: otherHash } = generateApiKey();
141
- expect(verifyApiKey(key, otherHash)).toBe(false);
142
- });
143
- });
144
-
145
- describe("hasScope", () => {
146
- it("returns true when scope is present", () => {
147
- const scopes: ApiKeyScope[] = ["read:bookings", "write:bookings"];
148
- expect(hasScope(scopes, "read:bookings")).toBe(true);
149
- });
150
-
151
- it("returns false when scope is absent", () => {
152
- const scopes: ApiKeyScope[] = ["read:bookings"];
153
- expect(hasScope(scopes, "write:bookings")).toBe(false);
154
- });
155
-
156
- it("admin scope grants all permissions", () => {
157
- const scopes: ApiKeyScope[] = ["admin"];
158
- expect(hasScope(scopes, "read:bookings")).toBe(true);
159
- expect(hasScope(scopes, "write:event-types")).toBe(true);
160
- expect(hasScope(scopes, "write:webhooks")).toBe(true);
161
- });
162
- });
163
-
164
- describe("isKeyExpired", () => {
165
- it("returns false for no expiry", () => {
166
- expect(isKeyExpired(undefined)).toBe(false);
167
- expect(isKeyExpired(null)).toBe(false);
168
- });
169
-
170
- it("returns true for past expiry", () => {
171
- expect(isKeyExpired(new Date(Date.now() - 1000))).toBe(true);
172
- });
173
-
174
- it("returns false for future expiry", () => {
175
- expect(isKeyExpired(new Date(Date.now() + 86400000))).toBe(false);
176
- });
177
- });
178
-
179
- // ---------------------------------------------------------------------------
180
- // Rate Limiting
181
- // ---------------------------------------------------------------------------
182
-
183
- describe("checkRateLimit", () => {
184
- beforeEach(() => {
185
- vi.useFakeTimers();
186
- vi.setSystemTime(new Date("2026-03-15T14:00:00.000Z"));
187
- });
188
-
189
- afterEach(() => {
190
- vi.useRealTimers();
191
- });
192
-
193
- it("allows first request", () => {
194
- const { result } = checkRateLimit(null, 120);
195
- expect(result.allowed).toBe(true);
196
- expect(result.remaining).toBe(119);
197
- expect(result.limit).toBe(120);
198
- });
199
-
200
- it("tracks requests within a window", () => {
201
- const { newState } = checkRateLimit(null, 120);
202
- const { result } = checkRateLimit(newState, 120);
203
- expect(result.allowed).toBe(true);
204
- expect(result.remaining).toBe(118);
205
- });
206
-
207
- it("blocks requests when limit exceeded", () => {
208
- let state = checkRateLimit(null, 2).newState;
209
- state = checkRateLimit(state, 2).newState;
210
- const { result } = checkRateLimit(state, 2);
211
- expect(result.allowed).toBe(false);
212
- expect(result.remaining).toBe(0);
213
- });
214
-
215
- it("resets counter in new window", () => {
216
- let state = checkRateLimit(null, 2).newState;
217
- state = checkRateLimit(state, 2).newState;
218
- // Advance to next minute
219
- vi.advanceTimersByTime(60 * 1000);
220
- const { result } = checkRateLimit(state, 2);
221
- expect(result.allowed).toBe(true);
222
- expect(result.remaining).toBe(1);
223
- });
224
- });
225
-
226
- // ---------------------------------------------------------------------------
227
- // Cursor Pagination
228
- // ---------------------------------------------------------------------------
229
-
230
- describe("encodeCursor / decodeCursor", () => {
231
- it("round-trips cursor data", () => {
232
- const data = { id: "bk-1", createdAt: "2026-03-15T14:00:00Z" };
233
- const cursor = encodeCursor(data);
234
- const decoded = decodeCursor(cursor);
235
- expect(decoded).toEqual(data);
236
- });
237
-
238
- it("returns null for invalid cursor", () => {
239
- expect(decodeCursor("not-valid-base64!!!")).toBeNull();
240
- });
241
-
242
- it("returns null for non-JSON cursor", () => {
243
- const cursor = Buffer.from("not json").toString("base64url");
244
- expect(decodeCursor(cursor)).toBeNull();
245
- });
246
- });
247
-
248
- // ---------------------------------------------------------------------------
249
- // validateSlotQueryParams
250
- // ---------------------------------------------------------------------------
251
-
252
- describe("validateSlotQueryParams", () => {
253
- const validParams = {
254
- providerId: "prov-1",
255
- start: "2026-03-15",
256
- end: "2026-04-15",
257
- timezone: "America/New_York",
258
- };
259
-
260
- it("accepts valid params", () => {
261
- const result = validateSlotQueryParams(validParams);
262
- expect(result.valid).toBe(true);
263
- expect(result.errors).toHaveLength(0);
264
- });
265
-
266
- it("accepts teamId instead of providerId", () => {
267
- const result = validateSlotQueryParams({
268
- teamId: "team-1",
269
- start: "2026-03-15",
270
- end: "2026-04-15",
271
- });
272
- expect(result.valid).toBe(true);
273
- });
274
-
275
- it("rejects missing providerId and teamId", () => {
276
- const result = validateSlotQueryParams({
277
- start: "2026-03-15",
278
- end: "2026-04-15",
279
- });
280
- expect(result.valid).toBe(false);
281
- expect(result.errors[0].field).toBe("providerId");
282
- });
283
-
284
- it("rejects missing start date", () => {
285
- const result = validateSlotQueryParams({
286
- providerId: "p1",
287
- end: "2026-04-15",
288
- });
289
- expect(result.valid).toBe(false);
290
- expect(result.errors.some((e) => e.field === "start")).toBe(true);
291
- });
292
-
293
- it("rejects invalid start date", () => {
294
- const result = validateSlotQueryParams({
295
- providerId: "p1",
296
- start: "not-a-date",
297
- end: "2026-04-15",
298
- });
299
- expect(result.valid).toBe(false);
300
- });
301
-
302
- it("rejects end before start", () => {
303
- const result = validateSlotQueryParams({
304
- providerId: "p1",
305
- start: "2026-04-15",
306
- end: "2026-03-15",
307
- });
308
- expect(result.valid).toBe(false);
309
- expect(result.errors.some((e) => e.message.includes("after start"))).toBe(
310
- true,
311
- );
312
- });
313
- });
314
-
315
- // ---------------------------------------------------------------------------
316
- // parseSortParam
317
- // ---------------------------------------------------------------------------
318
-
319
- describe("parseSortParam", () => {
320
- const allowedFields = ["createdAt", "startsAt", "status"];
321
-
322
- it("parses ascending sort", () => {
323
- const result = parseSortParam("startsAt", allowedFields);
324
- expect(result).toEqual({ field: "startsAt", direction: "asc" });
325
- });
326
-
327
- it("parses descending sort with leading minus", () => {
328
- const result = parseSortParam("-createdAt", allowedFields);
329
- expect(result).toEqual({ field: "createdAt", direction: "desc" });
330
- });
331
-
332
- it("returns null for invalid field", () => {
333
- expect(parseSortParam("unknownField", allowedFields)).toBeNull();
334
- });
335
-
336
- it("returns null for undefined input", () => {
337
- expect(parseSortParam(undefined, allowedFields)).toBeNull();
338
- });
339
- });
340
-
341
- // ---------------------------------------------------------------------------
342
- // API_ERROR_CODES
343
- // ---------------------------------------------------------------------------
344
-
345
- describe("API_ERROR_CODES", () => {
346
- it("exports all standard error codes", () => {
347
- expect(API_ERROR_CODES.NOT_FOUND).toBe("NOT_FOUND");
348
- expect(API_ERROR_CODES.UNAUTHORIZED).toBe("UNAUTHORIZED");
349
- expect(API_ERROR_CODES.FORBIDDEN).toBe("FORBIDDEN");
350
- expect(API_ERROR_CODES.VALIDATION_ERROR).toBe("VALIDATION_ERROR");
351
- expect(API_ERROR_CODES.RATE_LIMITED).toBe("RATE_LIMITED");
352
- expect(API_ERROR_CODES.CONFLICT).toBe("CONFLICT");
353
- });
354
- });
@@ -1,111 +0,0 @@
1
- import { describe, it, expect, vi } from "vitest";
2
- import {
3
- withAuth,
4
- assertProviderOwnership,
5
- assertCustomerAccess,
6
- UnauthorizedError,
7
- ForbiddenError,
8
- type AuthAdapter,
9
- type AuthUser,
10
- } from "../index.js";
11
-
12
- function mockAdapter(user: AuthUser | null): AuthAdapter {
13
- return {
14
- getCurrentUser: vi.fn().mockResolvedValue(user),
15
- getSession: vi.fn().mockResolvedValue(user ? { user, expires: new Date() } : null),
16
- verifyToken: vi.fn().mockResolvedValue(user),
17
- };
18
- }
19
-
20
- function mockRequest(headers: Record<string, string> = {}): Request {
21
- return new Request("http://localhost/api/test", {
22
- headers: new Headers(headers),
23
- });
24
- }
25
-
26
- describe("withAuth", () => {
27
- it("injects user and calls handler on valid session", async () => {
28
- const user: AuthUser = { id: "user1", email: "test@test.com" };
29
- const adapter = mockAdapter(user);
30
- const handler = vi.fn().mockResolvedValue(Response.json({ ok: true }));
31
-
32
- const wrapped = withAuth(adapter, handler);
33
- const response = await wrapped(mockRequest());
34
-
35
- expect(response.status).toBe(200);
36
- expect(handler).toHaveBeenCalledTimes(1);
37
- const calledReq = handler.mock.calls[0][0];
38
- expect(calledReq.user).toEqual(user);
39
- });
40
-
41
- it("returns 401 when no user is authenticated", async () => {
42
- const adapter = mockAdapter(null);
43
- // verifyToken also returns null
44
- adapter.verifyToken = vi.fn().mockResolvedValue(null);
45
- const handler = vi.fn();
46
-
47
- const wrapped = withAuth(adapter, handler);
48
- const response = await wrapped(mockRequest());
49
-
50
- expect(response.status).toBe(401);
51
- expect(handler).not.toHaveBeenCalled();
52
- });
53
-
54
- it("falls back to Bearer token when session returns null", async () => {
55
- const user: AuthUser = { id: "user2", email: "api@test.com" };
56
- const adapter = mockAdapter(null);
57
- adapter.getCurrentUser = vi.fn().mockResolvedValue(null);
58
- adapter.verifyToken = vi.fn().mockResolvedValue(user);
59
-
60
- const handler = vi.fn().mockResolvedValue(Response.json({ ok: true }));
61
- const wrapped = withAuth(adapter, handler);
62
- const response = await wrapped(
63
- mockRequest({ Authorization: "Bearer test-token-123" }),
64
- );
65
-
66
- expect(response.status).toBe(200);
67
- expect(adapter.verifyToken).toHaveBeenCalledWith("test-token-123");
68
- });
69
-
70
- it("returns 403 when role does not match", async () => {
71
- const user: AuthUser = {
72
- id: "user3",
73
- email: "member@test.com",
74
- role: "customer",
75
- };
76
- const adapter = mockAdapter(user);
77
- const handler = vi.fn();
78
-
79
- const wrapped = withAuth(adapter, handler, { requiredRole: "admin" });
80
- const response = await wrapped(mockRequest());
81
-
82
- expect(response.status).toBe(403);
83
- expect(handler).not.toHaveBeenCalled();
84
- });
85
- });
86
-
87
- describe("assertProviderOwnership", () => {
88
- it("does not throw when user IDs match", () => {
89
- expect(() => assertProviderOwnership("user1", "user1")).not.toThrow();
90
- });
91
-
92
- it("throws ForbiddenError when user IDs do not match", () => {
93
- expect(() => assertProviderOwnership("user1", "user2")).toThrow(
94
- ForbiddenError,
95
- );
96
- });
97
- });
98
-
99
- describe("assertCustomerAccess", () => {
100
- it("does not throw when emails match", () => {
101
- expect(() =>
102
- assertCustomerAccess("a@test.com", "a@test.com"),
103
- ).not.toThrow();
104
- });
105
-
106
- it("throws ForbiddenError when emails do not match", () => {
107
- expect(() =>
108
- assertCustomerAccess("a@test.com", "b@test.com"),
109
- ).toThrow(ForbiddenError);
110
- });
111
- });
@@ -1,170 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import {
3
- withSerializableRetry,
4
- BookingConflictError,
5
- SerializationRetryExhaustedError,
6
- } from "../index.js";
7
-
8
- /**
9
- * Concurrent booking simulation tests.
10
- *
11
- * These tests simulate the load test from E01-S04:
12
- * "50 concurrent booking attempts for the same slot yields exactly 1 confirmed
13
- * booking, 0 unhandled serialization errors, and all other callers receive
14
- * a clear conflict response within 2 seconds."
15
- *
16
- * Since we can't connect to a real Postgres in unit tests, we simulate the
17
- * database behavior with an in-memory "slot lock" that mimics the EXCLUDE
18
- * constraint (SQLSTATE 23P01) and serialization failures (SQLSTATE 40001).
19
- */
20
-
21
- /** Simulates a Postgres error with a SQLSTATE code */
22
- class PgError extends Error {
23
- code: string;
24
- constructor(message: string, code: string) {
25
- super(message);
26
- this.name = "PgError";
27
- this.code = code;
28
- }
29
- }
30
-
31
- describe("Concurrent Booking Simulation (E01-S04 Load Test)", () => {
32
- it("50 concurrent attempts for the same slot: exactly 1 success, rest get conflict", async () => {
33
- // Simulate a database slot that can only be booked once.
34
- // The first successful INSERT wins; subsequent attempts get exclusion_violation.
35
- let slotBooked = false;
36
- let serializationFailureCount = 0;
37
- const maxSimulatedSerializationFailures = 5; // simulate some contention
38
-
39
- const attemptBooking = async (attemptId: number): Promise<string> => {
40
- return withSerializableRetry(
41
- async () => {
42
- // Simulate random serialization failures under contention
43
- if (
44
- !slotBooked &&
45
- serializationFailureCount < maxSimulatedSerializationFailures &&
46
- Math.random() < 0.3
47
- ) {
48
- serializationFailureCount++;
49
- throw new PgError("serialization failure", "40001");
50
- }
51
-
52
- // Simulate the EXCLUDE constraint check
53
- if (slotBooked) {
54
- throw new PgError(
55
- "conflicting key value violates exclusion constraint",
56
- "23P01",
57
- );
58
- }
59
-
60
- // Race: first writer wins
61
- slotBooked = true;
62
- return `booking-${attemptId}`;
63
- },
64
- { maxRetries: 3, baseDelayMs: 10 },
65
- );
66
- };
67
-
68
- const CONCURRENCY = 50;
69
- const results = await Promise.allSettled(
70
- Array.from({ length: CONCURRENCY }, (_, i) => attemptBooking(i)),
71
- );
72
-
73
- const successes = results.filter((r) => r.status === "fulfilled");
74
- const failures = results.filter((r) => r.status === "rejected");
75
-
76
- // Exactly 1 booking should succeed
77
- expect(successes.length).toBe(1);
78
-
79
- // All failures should be BookingConflictError (not unhandled errors)
80
- for (const failure of failures) {
81
- if (failure.status === "rejected") {
82
- expect(failure.reason).toBeInstanceOf(BookingConflictError);
83
- }
84
- }
85
-
86
- // Zero unhandled serialization errors
87
- const serializationErrors = failures.filter(
88
- (f) =>
89
- f.status === "rejected" &&
90
- f.reason instanceof SerializationRetryExhaustedError,
91
- );
92
- expect(serializationErrors.length).toBe(0);
93
- });
94
-
95
- it("completes all 50 attempts within 2 seconds", async () => {
96
- let slotBooked = false;
97
-
98
- const attemptBooking = async (attemptId: number): Promise<string> => {
99
- return withSerializableRetry(
100
- async () => {
101
- if (slotBooked) {
102
- throw new PgError(
103
- "conflicting key value violates exclusion constraint",
104
- "23P01",
105
- );
106
- }
107
- slotBooked = true;
108
- return `booking-${attemptId}`;
109
- },
110
- { maxRetries: 3, baseDelayMs: 10 },
111
- );
112
- };
113
-
114
- const start = Date.now();
115
-
116
- await Promise.allSettled(
117
- Array.from({ length: 50 }, (_, i) => attemptBooking(i)),
118
- );
119
-
120
- const elapsed = Date.now() - start;
121
- expect(elapsed).toBeLessThan(2000);
122
- });
123
-
124
- it("serialization failures are retried and can succeed on a different slot", async () => {
125
- let attempt = 0;
126
-
127
- const result = await withSerializableRetry(
128
- async () => {
129
- attempt++;
130
- if (attempt <= 2) {
131
- throw new PgError("serialization failure", "40001");
132
- }
133
- return "booking-success";
134
- },
135
- { maxRetries: 3, baseDelayMs: 10 },
136
- );
137
-
138
- expect(result).toBe("booking-success");
139
- expect(attempt).toBe(3);
140
- });
141
-
142
- it("retries are exhausted after maxRetries serialization failures", async () => {
143
- const fn = () =>
144
- withSerializableRetry(
145
- async () => {
146
- throw new PgError("serialization failure", "40001");
147
- },
148
- { maxRetries: 3, baseDelayMs: 10 },
149
- );
150
-
151
- await expect(fn()).rejects.toThrow(SerializationRetryExhaustedError);
152
- });
153
-
154
- it("exclusion violation (slot taken) is never retried", async () => {
155
- let callCount = 0;
156
-
157
- const fn = () =>
158
- withSerializableRetry(
159
- async () => {
160
- callCount++;
161
- throw new PgError("exclusion constraint", "23P01");
162
- },
163
- { maxRetries: 3, baseDelayMs: 10 },
164
- );
165
-
166
- await expect(fn()).rejects.toThrow(BookingConflictError);
167
- // Should NOT have retried — only 1 call
168
- expect(callCount).toBe(1);
169
- });
170
- });