-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
439 lines (396 loc) · 11.3 KB
/
index.ts
File metadata and controls
439 lines (396 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/**
* Idempotency Module
*
* This module implements idempotency for POST/PUT/PATCH operations.
* Idempotency ensures that making the same request multiple times
* has the same effect as making it once.
*
* Why Idempotency Matters:
* - Network failures can cause duplicate requests
* - Client retries can create duplicate resources
* - Payment systems require idempotency to avoid double-charging
* - Improves reliability and user experience
*
* How It Works:
* 1. Client provides an "Idempotency-Key" header with unique value
* 2. Server checks if key has been used before
* 3. If new: Process request, store response with key
* 4. If exists: Return stored response without reprocessing
*
* Best Practices Implemented:
* - Key uniqueness per user + route
* - Time-based expiration (24 hours)
* - Atomic check-and-set operations
* - Full response replay (status, body, headers)
*/
import { db } from '../database/index.js';
import { logger } from '../observability/index.js';
import type { Request, Response, NextFunction } from 'express';
import type { ApiResponse } from '../types/index.js';
/**
* ============================================
* Idempotency Key Storage
* ============================================
*/
/**
* Stored response object
* Contains everything needed to replay a response
*/
export interface StoredResponse {
/** HTTP status code */
status: number;
/** Response body */
body: ApiResponse<unknown>;
/** When this response was stored */
createdAt: number;
/** How long this key should be valid (ms) */
ttl: number;
}
/**
* Extract idempotency key from request headers
*
* @param req - Express request object
* @returns The idempotency key or null if not present
*
* @example
* ```ts
* const key = getIdempotencyKey(req);
* if (!key) {
* return fail(res, req, 'IDEMPOTENCY_KEY_REQUIRED', 'Missing Idempotency-Key header');
* }
* ```
*/
export function getIdempotencyKey(req: Request): string | null {
const key = req.headers['idempotency-key'];
// Key must be a non-empty string
if (typeof key !== 'string' || key.trim().length === 0) {
return null;
}
return key.trim();
}
/**
* Validate idempotency key format
* Keys should be sufficiently random and unique
*
* Recommended formats:
* - UUID v4: "550e8400-e29b-41d4-a716-446655440000"
* - ULID: "01ARZ3NDEKTSV4RRFFQ69G5FAV"
* - Custom: "user_123-reserve-20240131-abc123"
*/
export function isValidIdempotencyKey(key: string): boolean {
// Minimum length to ensure uniqueness
if (key.length < 8) {
return false;
}
// Max length to prevent abuse
if (key.length > 255) {
return false;
}
// Should be URL-safe
const urlSafeRegex = /^[a-zA-Z0-9\-_]+$/;
return urlSafeRegex.test(key);
}
/**
* ============================================
* Idempotency Key Lookup
* ============================================
*/
/**
* Find a previously stored response for an idempotency key
*
* @param key - Idempotency key
* @param route - Route/method (e.g., "/reserve", "/confirm")
* @param userId - User who made the request
* @returns Stored response or null if not found
*
* @example
* ```ts
* const previous = findStoredResponse('key-123', '/reserve', 'user_1');
* if (previous) {
* return res.status(previous.status).json(previous.body);
* }
* ```
*/
export function findStoredResponse(
key: string,
route: string,
userId: string
): StoredResponse | null {
try {
const row = db
.prepare(
`
SELECT responseJson
FROM idempotency_keys
WHERE key = ? AND route = ? AND userId = ?
LIMIT 1
`
)
.get(key, route, userId) as { responseJson: string } | undefined;
if (!row) {
return null;
}
const stored = JSON.parse(row.responseJson) as StoredResponse;
// Check if expired (24 hour default)
const age = Date.now() - stored.createdAt;
if (age > stored.ttl) {
// Delete expired key
deleteIdempotencyKey(key, route, userId);
return null;
}
logger.debug('Idempotency hit', { key, route, userId });
return stored;
} catch (error) {
logger.error('Failed to retrieve idempotency key', error);
return null;
}
}
/**
* ============================================
* Idempotency Key Storage
* ============================================
*/
/**
* Store a response for an idempotency key
*
* @param key - Idempotency key
* @param route - Route/method
* @param userId - User who made the request
* @param status - HTTP status code
* @param body - Response body
* @param ttl - Time to live in milliseconds (default: 24 hours)
*
* @example
* ```ts
* await storeResponse(
* 'key-123',
* '/reserve',
* 'user_1',
* 201,
* { ok: true, data: { id: 'res_123', ... } }
* );
* ```
*/
export function storeResponse(
key: string,
route: string,
userId: string,
status: number,
body: ApiResponse<unknown>,
ttl: number = 24 * 60 * 60 * 1000 // 24 hours
): void {
try {
const stored: StoredResponse = {
status,
body,
createdAt: Date.now(),
ttl,
};
db.prepare(
`
INSERT OR REPLACE INTO idempotency_keys (key, route, userId, responseJson, createdAt)
VALUES (?, ?, ?, ?, ?)
`
).run(key, route, userId, JSON.stringify(stored), Date.now());
logger.debug('Stored idempotency response', { key, route, userId, status });
} catch (error) {
logger.error('Failed to store idempotency key', error);
// Don't throw - idempotency failures shouldn't break the request
}
}
/**
* ============================================
* Idempotency Key Deletion
* ============================================
*/
/**
* Delete an idempotency key
* Useful for cleanup or manual invalidation
*
* @param key - Idempotency key
* @param route - Route/method
* @param userId - User who made the request
*/
export function deleteIdempotencyKey(key: string, route: string, userId: string): void {
try {
db.prepare('DELETE FROM idempotency_keys WHERE key = ? AND route = ? AND userId = ?').run(
key,
route,
userId
);
logger.debug('Deleted idempotency key', { key, route, userId });
} catch (error) {
logger.error('Failed to delete idempotency key', error);
}
}
/**
* ============================================
* Cleanup Operations
* ============================================
*/
/**
* Delete expired idempotency keys
* Run this periodically to clean up old keys
*
* @param olderThanMs - Delete keys older than this (default: 24 hours)
* @returns Number of keys deleted
*
* @example
* ```ts
* // Run daily cleanup
* const deleted = cleanExpiredKeys();
* logger.info(`Cleaned ${deleted} expired idempotency keys`);
* ```
*/
export function cleanExpiredKeys(olderThanMs: number = 24 * 60 * 60 * 1000): number {
try {
const cutoffTime = Date.now() - olderThanMs;
const result = db
.prepare('DELETE FROM idempotency_keys WHERE createdAt < ?')
.run(cutoffTime);
logger.debug('Cleaned expired idempotency keys', { count: result.changes });
return result.changes;
} catch (error) {
logger.error('Failed to clean expired keys', error);
return 0;
}
}
/**
* ============================================
* Idempotency Middleware
* ============================================
*/
/**
* Idempotency check middleware factory
*
* Creates middleware that:
* 1. Checks for idempotency key
* 2. Returns cached response if exists
* 3. Continues to route handler if new
*
* After the route handler executes, the response is automatically stored
* if the operation was successful.
*
* @param route - Route identifier (e.g., "/reserve", "/confirm")
* @returns Express middleware function
*
* @example
* ```ts
* app.post('/reserve',
* idempotencyMiddleware('/reserve'),
* validateBody(reserveRequestSchema),
* async (req, res) => {
* // ... handle reservation ...
* // Response is automatically stored if successful
* }
* );
* ```
*/
export function idempotencyMiddleware(route: string) {
return (req: Request, res: any, next: NextFunction): void => {
// Extract userId from request body (for POST requests)
const userId = (req.body as { userId?: string })?.userId;
if (!userId) {
// Can't use idempotency without userId
return next();
}
const key = getIdempotencyKey(req);
// If no key provided, proceed normally
if (!key) {
return next();
}
// Validate key format
if (!isValidIdempotencyKey(key)) {
return res.status(400).json({
ok: false,
error: {
code: 'INVALID_IDEMPOTENCY_KEY',
message: 'Idempotency-Key must be at least 8 characters and contain only URL-safe characters',
},
});
}
// Check for existing response
const previous = findStoredResponse(key, route, userId);
if (previous) {
// Return cached response
return res.status(previous.status).json(previous.body);
}
// Store key and original json method for later use
res.locals.idempotencyKey = key;
res.locals.idempotencyRoute = route;
res.locals.idempotencyUserId = userId;
// Hook into response to store successful responses
const originalJson = res.json.bind(res);
res.json = function (body: unknown) {
// Store response if status code is 2xx
if (res.statusCode >= 200 && res.statusCode < 300) {
storeResponse(key, route, userId, res.statusCode, body as ApiResponse<unknown>);
}
return originalJson(body);
};
next();
};
}
/**
* ============================================
* Utilities
* ============================================;
/**
* Generate a unique idempotency key
* Use this if you want to generate keys on the server side
* (not recommended - clients should provide keys)
*
* @returns A unique idempotency key (ULID format)
*/
export function generateIdempotencyKey(): string {
// Simple ULID-like generator
// In production, use a proper ULID library
const timestamp = Date.now().toString(36);
const random = crypto.randomUUID().replace(/-/g, '').substring(0, 16);
return `${timestamp}-${random}`;
}
/**
* Get statistics about idempotency key usage
* Useful for monitoring and debugging
*
* @returns Statistics object
*/
export function getIdempotencyStats(): {
totalKeys: number;
keysByRoute: Record<string, number>;
oldestKey: number | null;
newestKey: number | null;
} {
try {
// Total keys
const totalKeys =
(db.prepare('SELECT COUNT(*) as count FROM idempotency_keys').get() as { count: number })
.count || 0;
// Keys by route
const byRoute = db
.prepare('SELECT route, COUNT(*) as count FROM idempotency_keys GROUP BY route')
.all() as Array<{ route: string; count: number }>;
const keysByRoute: Record<string, number> = {};
for (const row of byRoute) {
keysByRoute[row.route] = row.count;
}
// Oldest and newest keys
const timeRange = db
.prepare('SELECT MIN(createdAt) as min, MAX(createdAt) as max FROM idempotency_keys')
.get() as { min: number | null; max: number | null };
return {
totalKeys,
keysByRoute,
oldestKey: timeRange.min,
newestKey: timeRange.max,
};
} catch (error) {
logger.error('Failed to get idempotency stats', error);
return {
totalKeys: 0,
keysByRoute: {},
oldestKey: null,
newestKey: null,
};
}
}