@signaltree/events 7.3.1
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/angular.d.ts +1 -0
- package/angular.esm.js +547 -0
- package/factory.esm.js +178 -0
- package/idempotency.esm.js +701 -0
- package/index.d.ts +1 -0
- package/index.esm.js +167 -0
- package/nestjs.d.ts +1 -0
- package/nestjs.esm.js +944 -0
- package/package.json +110 -0
- package/src/angular/handlers.d.ts +132 -0
- package/src/angular/index.d.ts +12 -0
- package/src/angular/optimistic-updates.d.ts +117 -0
- package/src/angular/websocket.service.d.ts +158 -0
- package/src/angular.d.ts +7 -0
- package/src/core/error-classification.d.ts +100 -0
- package/src/core/factory.d.ts +114 -0
- package/src/core/idempotency.d.ts +209 -0
- package/src/core/registry.d.ts +147 -0
- package/src/core/types.d.ts +127 -0
- package/src/core/validation.d.ts +619 -0
- package/src/index.d.ts +56 -0
- package/src/nestjs/base.subscriber.d.ts +169 -0
- package/src/nestjs/decorators.d.ts +37 -0
- package/src/nestjs/dlq.service.d.ts +117 -0
- package/src/nestjs/event-bus.module.d.ts +117 -0
- package/src/nestjs/event-bus.service.d.ts +114 -0
- package/src/nestjs/index.d.ts +16 -0
- package/src/nestjs/tokens.d.ts +8 -0
- package/src/nestjs.d.ts +7 -0
- package/src/testing/assertions.d.ts +113 -0
- package/src/testing/factories.d.ts +106 -0
- package/src/testing/helpers.d.ts +104 -0
- package/src/testing/index.d.ts +13 -0
- package/src/testing/mock-event-bus.d.ts +144 -0
- package/src/testing.d.ts +7 -0
- package/testing.d.ts +1 -0
- package/testing.esm.js +743 -0
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Event Registry class - manages all registered event types
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```typescript
|
|
6
|
+
* const registry = createEventRegistry();
|
|
7
|
+
*
|
|
8
|
+
* // Register events
|
|
9
|
+
* registry.register({
|
|
10
|
+
* type: 'TradeProposalCreated',
|
|
11
|
+
* schema: TradeProposalCreatedSchema,
|
|
12
|
+
* priority: 'high',
|
|
13
|
+
* description: 'Emitted when a user proposes a trade',
|
|
14
|
+
* category: 'trade',
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* // Validate events
|
|
18
|
+
* const validated = registry.validate(rawEvent);
|
|
19
|
+
*
|
|
20
|
+
* // Get schema for event type
|
|
21
|
+
* const schema = registry.getSchema('TradeProposalCreated');
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
class EventRegistry {
|
|
25
|
+
events = new Map();
|
|
26
|
+
config;
|
|
27
|
+
constructor(config = {}) {
|
|
28
|
+
this.config = {
|
|
29
|
+
strict: config.strict ?? false,
|
|
30
|
+
warnOnDeprecated: config.warnOnDeprecated ?? true
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Register an event type with its schema
|
|
35
|
+
*/
|
|
36
|
+
register(event) {
|
|
37
|
+
if (this.events.has(event.type)) {
|
|
38
|
+
throw new Error(`Event type '${event.type}' is already registered`);
|
|
39
|
+
}
|
|
40
|
+
this.events.set(event.type, event);
|
|
41
|
+
return this;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Register multiple events at once
|
|
45
|
+
*/
|
|
46
|
+
registerMany(events) {
|
|
47
|
+
for (const event of events) {
|
|
48
|
+
this.register(event);
|
|
49
|
+
}
|
|
50
|
+
return this;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Get schema for an event type
|
|
54
|
+
*/
|
|
55
|
+
getSchema(type) {
|
|
56
|
+
return this.events.get(type)?.schema;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Get registered event info
|
|
60
|
+
*/
|
|
61
|
+
getEvent(type) {
|
|
62
|
+
return this.events.get(type);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Check if event type is registered
|
|
66
|
+
*/
|
|
67
|
+
has(type) {
|
|
68
|
+
return this.events.has(type);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Get default priority for event type
|
|
72
|
+
*/
|
|
73
|
+
getPriority(type) {
|
|
74
|
+
return this.events.get(type)?.priority ?? 'normal';
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Validate an event against its registered schema
|
|
78
|
+
*
|
|
79
|
+
* @throws Error if event type is unknown (in strict mode) or validation fails
|
|
80
|
+
*/
|
|
81
|
+
validate(event) {
|
|
82
|
+
if (typeof event !== 'object' || event === null) {
|
|
83
|
+
throw new Error('Event must be an object');
|
|
84
|
+
}
|
|
85
|
+
const eventObj = event;
|
|
86
|
+
const type = eventObj['type'];
|
|
87
|
+
if (!type) {
|
|
88
|
+
throw new Error('Event must have a type field');
|
|
89
|
+
}
|
|
90
|
+
const registered = this.events.get(type);
|
|
91
|
+
if (!registered) {
|
|
92
|
+
if (this.config.strict) {
|
|
93
|
+
throw new Error(`Unknown event type: ${type}`);
|
|
94
|
+
}
|
|
95
|
+
// In non-strict mode, return as-is (no validation)
|
|
96
|
+
return event;
|
|
97
|
+
}
|
|
98
|
+
// Warn about deprecated events
|
|
99
|
+
if (registered.deprecated && this.config.warnOnDeprecated) {
|
|
100
|
+
console.warn(`[EventRegistry] Event '${type}' is deprecated. ${registered.deprecationMessage ?? ''}`);
|
|
101
|
+
}
|
|
102
|
+
const result = registered.schema.safeParse(event);
|
|
103
|
+
if (!result.success) {
|
|
104
|
+
const errors = result.error.issues.map(i => `${i.path.join('.')}: ${i.message}`);
|
|
105
|
+
throw new Error(`Event validation failed for '${type}': ${errors.join(', ')}`);
|
|
106
|
+
}
|
|
107
|
+
return result.data;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Check if event is valid without throwing
|
|
111
|
+
*/
|
|
112
|
+
isValid(event) {
|
|
113
|
+
try {
|
|
114
|
+
this.validate(event);
|
|
115
|
+
return true;
|
|
116
|
+
} catch {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Get all registered event types
|
|
122
|
+
*/
|
|
123
|
+
getAllTypes() {
|
|
124
|
+
return Array.from(this.events.keys());
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Get all registered events
|
|
128
|
+
*/
|
|
129
|
+
getAll() {
|
|
130
|
+
return Array.from(this.events.values());
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Get events by category
|
|
134
|
+
*/
|
|
135
|
+
getByCategory(category) {
|
|
136
|
+
return this.getAll().filter(e => e.category === category);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Get event catalog for documentation
|
|
140
|
+
*/
|
|
141
|
+
getCatalog() {
|
|
142
|
+
return this.getAll().map(e => ({
|
|
143
|
+
type: e.type,
|
|
144
|
+
category: e.category,
|
|
145
|
+
priority: e.priority,
|
|
146
|
+
description: e.description,
|
|
147
|
+
deprecated: e.deprecated ?? false
|
|
148
|
+
}));
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Export registry as JSON schema (for external tools)
|
|
152
|
+
*/
|
|
153
|
+
toJSONSchema() {
|
|
154
|
+
const schemas = {};
|
|
155
|
+
for (const [type, event] of Array.from(this.events.entries())) {
|
|
156
|
+
// Note: This is a simplified JSON schema export
|
|
157
|
+
// For full compatibility, use zod-to-json-schema package
|
|
158
|
+
schemas[type] = {
|
|
159
|
+
type: 'object',
|
|
160
|
+
description: event.description,
|
|
161
|
+
deprecated: event.deprecated,
|
|
162
|
+
priority: event.priority,
|
|
163
|
+
category: event.category
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
$schema: 'http://json-schema.org/draft-07/schema#',
|
|
168
|
+
title: 'Event Registry',
|
|
169
|
+
definitions: schemas
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Create a new event registry
|
|
175
|
+
*/
|
|
176
|
+
function createEventRegistry(config) {
|
|
177
|
+
return new EventRegistry(config);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Error Classification - Determine retry behavior for errors
|
|
182
|
+
*
|
|
183
|
+
* Provides:
|
|
184
|
+
* - Retryable vs non-retryable error classification
|
|
185
|
+
* - Error categories (transient, permanent, poison)
|
|
186
|
+
* - Retry configuration per error type
|
|
187
|
+
* - Custom error classifiers
|
|
188
|
+
*/
|
|
189
|
+
/**
|
|
190
|
+
* Default retry configurations by classification
|
|
191
|
+
*/
|
|
192
|
+
const DEFAULT_RETRY_CONFIGS = {
|
|
193
|
+
transient: {
|
|
194
|
+
maxAttempts: 5,
|
|
195
|
+
initialDelayMs: 1000,
|
|
196
|
+
maxDelayMs: 60000,
|
|
197
|
+
backoffMultiplier: 2,
|
|
198
|
+
jitter: 0.1
|
|
199
|
+
},
|
|
200
|
+
permanent: {
|
|
201
|
+
maxAttempts: 0,
|
|
202
|
+
initialDelayMs: 0,
|
|
203
|
+
maxDelayMs: 0,
|
|
204
|
+
backoffMultiplier: 1,
|
|
205
|
+
jitter: 0
|
|
206
|
+
},
|
|
207
|
+
poison: {
|
|
208
|
+
maxAttempts: 0,
|
|
209
|
+
initialDelayMs: 0,
|
|
210
|
+
maxDelayMs: 0,
|
|
211
|
+
backoffMultiplier: 1,
|
|
212
|
+
jitter: 0
|
|
213
|
+
},
|
|
214
|
+
unknown: {
|
|
215
|
+
maxAttempts: 3,
|
|
216
|
+
initialDelayMs: 2000,
|
|
217
|
+
maxDelayMs: 30000,
|
|
218
|
+
backoffMultiplier: 2,
|
|
219
|
+
jitter: 0.2
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
/**
|
|
223
|
+
* Known transient error patterns
|
|
224
|
+
*/
|
|
225
|
+
const TRANSIENT_ERROR_PATTERNS = [
|
|
226
|
+
// Network errors
|
|
227
|
+
/ECONNREFUSED/i, /ECONNRESET/i, /ETIMEDOUT/i, /ENETUNREACH/i, /EHOSTUNREACH/i, /ENOTFOUND/i, /socket hang up/i, /network error/i, /connection.*timeout/i, /request.*timeout/i,
|
|
228
|
+
// Database transient
|
|
229
|
+
/deadlock/i, /lock wait timeout/i, /too many connections/i, /connection pool exhausted/i, /temporarily unavailable/i,
|
|
230
|
+
// HTTP transient
|
|
231
|
+
/502 bad gateway/i, /503 service unavailable/i, /504 gateway timeout/i, /429 too many requests/i,
|
|
232
|
+
// Redis/Queue transient
|
|
233
|
+
/BUSY/i, /LOADING/i, /CLUSTERDOWN/i, /READONLY/i,
|
|
234
|
+
// Generic transient
|
|
235
|
+
/temporary failure/i, /try again/i, /retry/i, /throttl/i, /rate limit/i, /circuit breaker/i];
|
|
236
|
+
/**
|
|
237
|
+
* Known permanent error patterns
|
|
238
|
+
*/
|
|
239
|
+
const PERMANENT_ERROR_PATTERNS = [
|
|
240
|
+
// Auth errors
|
|
241
|
+
/unauthorized/i, /forbidden/i, /access denied/i, /permission denied/i, /invalid token/i, /token expired/i,
|
|
242
|
+
// Business logic
|
|
243
|
+
/not found/i, /already exists/i, /duplicate/i, /conflict/i, /invalid state/i, /precondition failed/i,
|
|
244
|
+
// HTTP permanent
|
|
245
|
+
/400 bad request/i, /401 unauthorized/i, /403 forbidden/i, /404 not found/i, /409 conflict/i, /422 unprocessable/i];
|
|
246
|
+
/**
|
|
247
|
+
* Known poison error patterns (send to DLQ immediately)
|
|
248
|
+
*/
|
|
249
|
+
const POISON_ERROR_PATTERNS = [
|
|
250
|
+
// Schema/Serialization
|
|
251
|
+
/invalid json/i, /json parse error/i, /unexpected token/i, /schema validation/i, /invalid event schema/i, /deserialization/i, /malformed/i,
|
|
252
|
+
// Data corruption
|
|
253
|
+
/data corruption/i, /checksum mismatch/i, /integrity error/i];
|
|
254
|
+
/**
|
|
255
|
+
* Error codes that indicate transient failures
|
|
256
|
+
*/
|
|
257
|
+
const TRANSIENT_ERROR_CODES = new Set(['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ENOTFOUND', 'EPIPE', 'EAI_AGAIN']);
|
|
258
|
+
/**
|
|
259
|
+
* HTTP status codes that indicate transient failures
|
|
260
|
+
*/
|
|
261
|
+
const TRANSIENT_HTTP_STATUS = new Set([408, 429, 500, 502, 503, 504]);
|
|
262
|
+
/**
|
|
263
|
+
* HTTP status codes that indicate permanent failures
|
|
264
|
+
*/
|
|
265
|
+
const PERMANENT_HTTP_STATUS = new Set([400, 401, 403, 404, 405, 409, 410, 422]);
|
|
266
|
+
/**
|
|
267
|
+
* Create an error classifier
|
|
268
|
+
*
|
|
269
|
+
* @example
|
|
270
|
+
* ```typescript
|
|
271
|
+
* const classifier = createErrorClassifier({
|
|
272
|
+
* customClassifiers: [
|
|
273
|
+
* (error) => {
|
|
274
|
+
* if (error instanceof MyCustomTransientError) return 'transient';
|
|
275
|
+
* return null; // Let default classification handle it
|
|
276
|
+
* }
|
|
277
|
+
* ],
|
|
278
|
+
* retryConfigs: {
|
|
279
|
+
* transient: { maxAttempts: 10 }, // Override max attempts
|
|
280
|
+
* },
|
|
281
|
+
* });
|
|
282
|
+
*
|
|
283
|
+
* const result = classifier.classify(error);
|
|
284
|
+
* if (result.sendToDlq) {
|
|
285
|
+
* await dlqService.send(event, error, result.reason);
|
|
286
|
+
* }
|
|
287
|
+
* ```
|
|
288
|
+
*/
|
|
289
|
+
function createErrorClassifier(config = {}) {
|
|
290
|
+
const customClassifiers = config.customClassifiers ?? [];
|
|
291
|
+
const defaultClassification = config.defaultClassification ?? 'unknown';
|
|
292
|
+
// Merge retry configs
|
|
293
|
+
const retryConfigs = {
|
|
294
|
+
transient: {
|
|
295
|
+
...DEFAULT_RETRY_CONFIGS.transient,
|
|
296
|
+
...config.retryConfigs?.transient
|
|
297
|
+
},
|
|
298
|
+
permanent: {
|
|
299
|
+
...DEFAULT_RETRY_CONFIGS.permanent,
|
|
300
|
+
...config.retryConfigs?.permanent
|
|
301
|
+
},
|
|
302
|
+
poison: {
|
|
303
|
+
...DEFAULT_RETRY_CONFIGS.poison,
|
|
304
|
+
...config.retryConfigs?.poison
|
|
305
|
+
},
|
|
306
|
+
unknown: {
|
|
307
|
+
...DEFAULT_RETRY_CONFIGS.unknown,
|
|
308
|
+
...config.retryConfigs?.unknown
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
function extractErrorInfo(error) {
|
|
312
|
+
if (error instanceof Error) {
|
|
313
|
+
const errWithCode = error;
|
|
314
|
+
return {
|
|
315
|
+
message: error.message,
|
|
316
|
+
name: error.name,
|
|
317
|
+
code: errWithCode.code,
|
|
318
|
+
status: errWithCode.status ?? errWithCode.statusCode ?? errWithCode.response?.status
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
if (typeof error === 'object' && error !== null) {
|
|
322
|
+
const obj = error;
|
|
323
|
+
return {
|
|
324
|
+
message: String(obj['message'] ?? obj['error'] ?? ''),
|
|
325
|
+
code: obj['code'],
|
|
326
|
+
status: obj['status'] ?? obj['statusCode']
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
message: String(error)
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
function classifyByPatterns(message) {
|
|
334
|
+
// Check poison patterns first (most specific)
|
|
335
|
+
for (const pattern of POISON_ERROR_PATTERNS) {
|
|
336
|
+
if (pattern.test(message)) {
|
|
337
|
+
return 'poison';
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
// Check permanent patterns
|
|
341
|
+
for (const pattern of PERMANENT_ERROR_PATTERNS) {
|
|
342
|
+
if (pattern.test(message)) {
|
|
343
|
+
return 'permanent';
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// Check transient patterns
|
|
347
|
+
for (const pattern of TRANSIENT_ERROR_PATTERNS) {
|
|
348
|
+
if (pattern.test(message)) {
|
|
349
|
+
return 'transient';
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return null;
|
|
353
|
+
}
|
|
354
|
+
function classify(error) {
|
|
355
|
+
// 1. Try custom classifiers first
|
|
356
|
+
for (const classifier of customClassifiers) {
|
|
357
|
+
const result = classifier(error);
|
|
358
|
+
if (result !== null) {
|
|
359
|
+
return {
|
|
360
|
+
classification: result,
|
|
361
|
+
retryConfig: retryConfigs[result],
|
|
362
|
+
sendToDlq: result === 'poison' || result === 'permanent',
|
|
363
|
+
reason: `Custom classifier: ${result}`
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const {
|
|
368
|
+
message,
|
|
369
|
+
code,
|
|
370
|
+
status,
|
|
371
|
+
name
|
|
372
|
+
} = extractErrorInfo(error);
|
|
373
|
+
// 2. Check error code
|
|
374
|
+
if (code && TRANSIENT_ERROR_CODES.has(code)) {
|
|
375
|
+
return {
|
|
376
|
+
classification: 'transient',
|
|
377
|
+
retryConfig: retryConfigs.transient,
|
|
378
|
+
sendToDlq: false,
|
|
379
|
+
reason: `Error code: ${code}`
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
// 3. Check HTTP status
|
|
383
|
+
if (status !== undefined) {
|
|
384
|
+
if (TRANSIENT_HTTP_STATUS.has(status)) {
|
|
385
|
+
return {
|
|
386
|
+
classification: 'transient',
|
|
387
|
+
retryConfig: retryConfigs.transient,
|
|
388
|
+
sendToDlq: false,
|
|
389
|
+
reason: `HTTP status: ${status}`
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
if (PERMANENT_HTTP_STATUS.has(status)) {
|
|
393
|
+
return {
|
|
394
|
+
classification: 'permanent',
|
|
395
|
+
retryConfig: retryConfigs.permanent,
|
|
396
|
+
sendToDlq: true,
|
|
397
|
+
reason: `HTTP status: ${status}`
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
// 4. Check error patterns
|
|
402
|
+
const patternResult = classifyByPatterns(message) ?? classifyByPatterns(name ?? '');
|
|
403
|
+
if (patternResult) {
|
|
404
|
+
return {
|
|
405
|
+
classification: patternResult,
|
|
406
|
+
retryConfig: retryConfigs[patternResult],
|
|
407
|
+
sendToDlq: patternResult === 'poison' || patternResult === 'permanent',
|
|
408
|
+
reason: `Pattern match: ${message.slice(0, 50)}`
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
// 5. Use default classification
|
|
412
|
+
return {
|
|
413
|
+
classification: defaultClassification,
|
|
414
|
+
retryConfig: retryConfigs[defaultClassification],
|
|
415
|
+
sendToDlq: defaultClassification === 'poison' || defaultClassification === 'permanent',
|
|
416
|
+
reason: 'No matching pattern, using default'
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
function isRetryable(error) {
|
|
420
|
+
const result = classify(error);
|
|
421
|
+
return result.classification === 'transient' || result.classification === 'unknown';
|
|
422
|
+
}
|
|
423
|
+
function calculateDelay(attempt, retryConfig) {
|
|
424
|
+
// Exponential backoff: initialDelay * multiplier^attempt
|
|
425
|
+
const baseDelay = retryConfig.initialDelayMs * Math.pow(retryConfig.backoffMultiplier, attempt);
|
|
426
|
+
// Cap at maxDelay
|
|
427
|
+
const cappedDelay = Math.min(baseDelay, retryConfig.maxDelayMs);
|
|
428
|
+
// Add jitter to prevent thundering herd
|
|
429
|
+
const jitter = cappedDelay * retryConfig.jitter * Math.random();
|
|
430
|
+
return Math.round(cappedDelay + jitter);
|
|
431
|
+
}
|
|
432
|
+
return {
|
|
433
|
+
classify,
|
|
434
|
+
isRetryable,
|
|
435
|
+
calculateDelay
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Pre-configured error classifier instance
|
|
440
|
+
*/
|
|
441
|
+
const defaultErrorClassifier = createErrorClassifier();
|
|
442
|
+
/**
|
|
443
|
+
* Quick helper to check if error is retryable
|
|
444
|
+
*/
|
|
445
|
+
function isRetryableError(error) {
|
|
446
|
+
return defaultErrorClassifier.isRetryable(error);
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Quick helper to classify error
|
|
450
|
+
*/
|
|
451
|
+
function classifyError(error) {
|
|
452
|
+
return defaultErrorClassifier.classify(error);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* In-memory idempotency store
|
|
457
|
+
*
|
|
458
|
+
* Best for:
|
|
459
|
+
* - Development and testing
|
|
460
|
+
* - Single-instance deployments
|
|
461
|
+
* - Short-lived processes
|
|
462
|
+
*
|
|
463
|
+
* NOT recommended for:
|
|
464
|
+
* - Production multi-instance deployments
|
|
465
|
+
* - Long-running processes with many events
|
|
466
|
+
*/
|
|
467
|
+
class InMemoryIdempotencyStore {
|
|
468
|
+
records = new Map();
|
|
469
|
+
cleanupTimer;
|
|
470
|
+
defaultTtlMs;
|
|
471
|
+
defaultLockTtlMs;
|
|
472
|
+
maxRecords;
|
|
473
|
+
constructor(config = {}) {
|
|
474
|
+
this.defaultTtlMs = config.defaultTtlMs ?? 24 * 60 * 60 * 1000; // 24 hours
|
|
475
|
+
this.defaultLockTtlMs = config.defaultLockTtlMs ?? 30 * 1000; // 30 seconds
|
|
476
|
+
this.maxRecords = config.maxRecords ?? 100000;
|
|
477
|
+
if (config.cleanupIntervalMs !== 0) {
|
|
478
|
+
const interval = config.cleanupIntervalMs ?? 60 * 1000;
|
|
479
|
+
this.cleanupTimer = setInterval(() => this.cleanup(), interval);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
makeKey(eventId, consumer) {
|
|
483
|
+
return `${consumer}:${eventId}`;
|
|
484
|
+
}
|
|
485
|
+
async check(event, consumer, options = {}) {
|
|
486
|
+
const key = this.makeKey(event.id, consumer);
|
|
487
|
+
const record = this.records.get(key);
|
|
488
|
+
const now = Date.now();
|
|
489
|
+
// Check for existing record
|
|
490
|
+
if (record && record.expiresAt > now) {
|
|
491
|
+
// If processing and lock expired, treat as stale and allow reprocessing
|
|
492
|
+
if (record.status === 'processing') {
|
|
493
|
+
const lockExpired = record.startedAt.getTime() + this.defaultLockTtlMs < now;
|
|
494
|
+
if (lockExpired) {
|
|
495
|
+
// Lock expired, allow new processing attempt
|
|
496
|
+
if (options.acquireLock) {
|
|
497
|
+
const updated = {
|
|
498
|
+
...record,
|
|
499
|
+
startedAt: new Date(),
|
|
500
|
+
attempts: record.attempts + 1
|
|
501
|
+
};
|
|
502
|
+
this.records.set(key, updated);
|
|
503
|
+
return {
|
|
504
|
+
isDuplicate: false,
|
|
505
|
+
lockAcquired: true
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
return {
|
|
509
|
+
isDuplicate: false
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
// Still processing within lock period - treat as duplicate
|
|
513
|
+
return {
|
|
514
|
+
isDuplicate: true,
|
|
515
|
+
processedAt: record.startedAt
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
// Completed or failed record exists
|
|
519
|
+
return {
|
|
520
|
+
isDuplicate: true,
|
|
521
|
+
processedAt: record.completedAt ?? record.startedAt,
|
|
522
|
+
result: record.result
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
// No existing record or expired
|
|
526
|
+
if (options.acquireLock !== false) {
|
|
527
|
+
const ttlMs = options.lockTtlMs ?? this.defaultTtlMs;
|
|
528
|
+
const newRecord = {
|
|
529
|
+
eventId: event.id,
|
|
530
|
+
eventType: event.type,
|
|
531
|
+
startedAt: new Date(),
|
|
532
|
+
status: 'processing',
|
|
533
|
+
consumer,
|
|
534
|
+
attempts: 1,
|
|
535
|
+
expiresAt: now + ttlMs
|
|
536
|
+
};
|
|
537
|
+
this.records.set(key, newRecord);
|
|
538
|
+
this.enforceMaxRecords();
|
|
539
|
+
return {
|
|
540
|
+
isDuplicate: false,
|
|
541
|
+
lockAcquired: true
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
return {
|
|
545
|
+
isDuplicate: false
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
async markProcessing(event, consumer, ttlMs) {
|
|
549
|
+
const result = await this.check(event, consumer, {
|
|
550
|
+
acquireLock: true,
|
|
551
|
+
lockTtlMs: ttlMs ?? this.defaultLockTtlMs
|
|
552
|
+
});
|
|
553
|
+
return result.lockAcquired ?? false;
|
|
554
|
+
}
|
|
555
|
+
async markCompleted(event, consumer, result, ttlMs) {
|
|
556
|
+
const key = this.makeKey(event.id, consumer);
|
|
557
|
+
const record = this.records.get(key);
|
|
558
|
+
const now = Date.now();
|
|
559
|
+
const updated = {
|
|
560
|
+
eventId: event.id,
|
|
561
|
+
eventType: event.type,
|
|
562
|
+
startedAt: record?.startedAt ?? new Date(),
|
|
563
|
+
completedAt: new Date(),
|
|
564
|
+
status: 'completed',
|
|
565
|
+
result,
|
|
566
|
+
consumer,
|
|
567
|
+
attempts: record?.attempts ?? 1,
|
|
568
|
+
expiresAt: now + (ttlMs ?? this.defaultTtlMs)
|
|
569
|
+
};
|
|
570
|
+
this.records.set(key, updated);
|
|
571
|
+
}
|
|
572
|
+
async markFailed(event, consumer, error) {
|
|
573
|
+
const key = this.makeKey(event.id, consumer);
|
|
574
|
+
const record = this.records.get(key);
|
|
575
|
+
const now = Date.now();
|
|
576
|
+
const errorStr = error instanceof Error ? error.message : String(error);
|
|
577
|
+
const updated = {
|
|
578
|
+
eventId: event.id,
|
|
579
|
+
eventType: event.type,
|
|
580
|
+
startedAt: record?.startedAt ?? new Date(),
|
|
581
|
+
completedAt: new Date(),
|
|
582
|
+
status: 'failed',
|
|
583
|
+
error: errorStr,
|
|
584
|
+
consumer,
|
|
585
|
+
attempts: record?.attempts ?? 1,
|
|
586
|
+
expiresAt: now + this.defaultTtlMs
|
|
587
|
+
};
|
|
588
|
+
this.records.set(key, updated);
|
|
589
|
+
}
|
|
590
|
+
async releaseLock(event, consumer) {
|
|
591
|
+
const key = this.makeKey(event.id, consumer);
|
|
592
|
+
this.records.delete(key);
|
|
593
|
+
}
|
|
594
|
+
async getRecord(eventId, consumer) {
|
|
595
|
+
const key = this.makeKey(eventId, consumer);
|
|
596
|
+
const record = this.records.get(key);
|
|
597
|
+
if (!record || record.expiresAt < Date.now()) {
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
// Return without internal expiresAt field
|
|
601
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
602
|
+
const {
|
|
603
|
+
expiresAt: _,
|
|
604
|
+
...publicRecord
|
|
605
|
+
} = record;
|
|
606
|
+
return publicRecord;
|
|
607
|
+
}
|
|
608
|
+
async cleanup() {
|
|
609
|
+
const now = Date.now();
|
|
610
|
+
let cleaned = 0;
|
|
611
|
+
for (const [key, record] of Array.from(this.records.entries())) {
|
|
612
|
+
if (record.expiresAt < now) {
|
|
613
|
+
this.records.delete(key);
|
|
614
|
+
cleaned++;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return cleaned;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Enforce max records limit using LRU-like eviction
|
|
621
|
+
*/
|
|
622
|
+
enforceMaxRecords() {
|
|
623
|
+
if (this.records.size <= this.maxRecords) return;
|
|
624
|
+
// Sort by expires time (oldest first)
|
|
625
|
+
const entries = Array.from(this.records.entries()).sort((a, b) => a[1].expiresAt - b[1].expiresAt);
|
|
626
|
+
// Remove oldest 10%
|
|
627
|
+
const toRemove = Math.ceil(this.maxRecords * 0.1);
|
|
628
|
+
for (let i = 0; i < toRemove && i < entries.length; i++) {
|
|
629
|
+
this.records.delete(entries[i][0]);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Stop cleanup timer (for graceful shutdown)
|
|
634
|
+
*/
|
|
635
|
+
dispose() {
|
|
636
|
+
if (this.cleanupTimer) {
|
|
637
|
+
clearInterval(this.cleanupTimer);
|
|
638
|
+
this.cleanupTimer = undefined;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Clear all records (for testing)
|
|
643
|
+
*/
|
|
644
|
+
clear() {
|
|
645
|
+
this.records.clear();
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Get stats (for monitoring)
|
|
649
|
+
*/
|
|
650
|
+
getStats() {
|
|
651
|
+
return {
|
|
652
|
+
size: this.records.size,
|
|
653
|
+
maxRecords: this.maxRecords
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Create an in-memory idempotency store
|
|
659
|
+
*
|
|
660
|
+
* @example
|
|
661
|
+
* ```typescript
|
|
662
|
+
* const store = createInMemoryIdempotencyStore({
|
|
663
|
+
* defaultTtlMs: 60 * 60 * 1000, // 1 hour
|
|
664
|
+
* maxRecords: 50000,
|
|
665
|
+
* });
|
|
666
|
+
*
|
|
667
|
+
* // In your subscriber
|
|
668
|
+
* const result = await store.check(event, 'my-subscriber');
|
|
669
|
+
* if (result.isDuplicate) {
|
|
670
|
+
* return result.result; // Return cached result
|
|
671
|
+
* }
|
|
672
|
+
*
|
|
673
|
+
* try {
|
|
674
|
+
* const processResult = await processEvent(event);
|
|
675
|
+
* await store.markCompleted(event, 'my-subscriber', processResult);
|
|
676
|
+
* return processResult;
|
|
677
|
+
* } catch (error) {
|
|
678
|
+
* await store.markFailed(event, 'my-subscriber', error);
|
|
679
|
+
* throw error;
|
|
680
|
+
* }
|
|
681
|
+
* ```
|
|
682
|
+
*/
|
|
683
|
+
function createInMemoryIdempotencyStore(config) {
|
|
684
|
+
return new InMemoryIdempotencyStore(config);
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Generate an idempotency key from event
|
|
688
|
+
* Useful for custom implementations
|
|
689
|
+
*/
|
|
690
|
+
function generateIdempotencyKey(event, consumer) {
|
|
691
|
+
return `idempotency:${consumer}:${event.id}`;
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Generate an idempotency key from correlation ID
|
|
695
|
+
* Useful for request-level idempotency
|
|
696
|
+
*/
|
|
697
|
+
function generateCorrelationKey(correlationId, operation) {
|
|
698
|
+
return `idempotency:correlation:${operation}:${correlationId}`;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
export { DEFAULT_RETRY_CONFIGS as D, EventRegistry as E, InMemoryIdempotencyStore as I, classifyError as a, createErrorClassifier as b, createEventRegistry as c, defaultErrorClassifier as d, createInMemoryIdempotencyStore as e, generateCorrelationKey as f, generateIdempotencyKey as g, isRetryableError as i };
|
package/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/index";
|