@amqp-contract/worker 0.6.0 → 0.8.0
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/README.md +39 -10
- package/dist/index.cjs +432 -102
- package/dist/index.d.cts +354 -98
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +354 -98
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +428 -102
- package/dist/index.mjs.map +1 -1
- package/docs/index.md +994 -213
- package/package.json +19 -12
package/dist/index.d.cts
CHANGED
|
@@ -27,6 +27,33 @@ declare class MessageValidationError extends WorkerError {
|
|
|
27
27
|
readonly issues: unknown;
|
|
28
28
|
constructor(consumerName: string, issues: unknown);
|
|
29
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Retryable errors - transient failures that may succeed on retry
|
|
32
|
+
* Examples: network timeouts, rate limiting, temporary service unavailability
|
|
33
|
+
*
|
|
34
|
+
* Use this error type when the operation might succeed if retried.
|
|
35
|
+
* The worker will apply exponential backoff and retry the message.
|
|
36
|
+
*/
|
|
37
|
+
declare class RetryableError extends WorkerError {
|
|
38
|
+
readonly cause?: unknown | undefined;
|
|
39
|
+
constructor(message: string, cause?: unknown | undefined);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Non-retryable errors - permanent failures that should not be retried
|
|
43
|
+
* Examples: invalid data, business rule violations, permanent external failures
|
|
44
|
+
*
|
|
45
|
+
* Use this error type when retrying would not help - the message will be
|
|
46
|
+
* immediately sent to the dead letter queue (DLQ) if configured.
|
|
47
|
+
*/
|
|
48
|
+
declare class NonRetryableError extends WorkerError {
|
|
49
|
+
readonly cause?: unknown | undefined;
|
|
50
|
+
constructor(message: string, cause?: unknown | undefined);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Union type representing all handler errors.
|
|
54
|
+
* Use this type when defining handlers that explicitly signal error outcomes.
|
|
55
|
+
*/
|
|
56
|
+
type HandlerError = RetryableError | NonRetryableError;
|
|
30
57
|
//#endregion
|
|
31
58
|
//#region src/types.d.ts
|
|
32
59
|
/**
|
|
@@ -50,40 +77,129 @@ type InferConsumer<TContract extends ContractDefinition, TName extends InferCons
|
|
|
50
77
|
*/
|
|
51
78
|
type WorkerInferConsumerInput<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = ConsumerInferInput<InferConsumer<TContract, TName>>;
|
|
52
79
|
/**
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
80
|
+
* Safe consumer handler type for a specific consumer.
|
|
81
|
+
* Returns a `Future<Result<void, HandlerError>>` for explicit error handling.
|
|
82
|
+
*
|
|
83
|
+
* **Recommended over unsafe handlers** for better error control:
|
|
84
|
+
* - RetryableError: Message will be retried with exponential backoff
|
|
85
|
+
* - NonRetryableError: Message will be immediately sent to DLQ
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* const handler: WorkerInferSafeConsumerHandler<typeof contract, 'processOrder'> =
|
|
90
|
+
* (message) => Future.value(Result.Ok(undefined));
|
|
91
|
+
* ```
|
|
56
92
|
*/
|
|
57
|
-
type
|
|
93
|
+
type WorkerInferSafeConsumerHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = (message: WorkerInferConsumerInput<TContract, TName>) => Future<Result<void, HandlerError>>;
|
|
58
94
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
95
|
+
* Safe consumer handler type for batch processing.
|
|
96
|
+
* Returns a `Future<Result<void, HandlerError>>` for explicit error handling.
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```typescript
|
|
100
|
+
* const handler: WorkerInferSafeConsumerBatchHandler<typeof contract, 'processOrders'> =
|
|
101
|
+
* (messages) => Future.value(Result.Ok(undefined));
|
|
102
|
+
* ```
|
|
61
103
|
*/
|
|
62
|
-
type
|
|
104
|
+
type WorkerInferSafeConsumerBatchHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = (messages: Array<WorkerInferConsumerInput<TContract, TName>>) => Future<Result<void, HandlerError>>;
|
|
63
105
|
/**
|
|
64
|
-
*
|
|
106
|
+
* Safe handler entry for a consumer - either a function or a tuple of [handler, options].
|
|
65
107
|
*
|
|
66
108
|
* Three patterns are supported:
|
|
67
|
-
* 1. Simple handler: `
|
|
68
|
-
* 2. Handler with prefetch: `[
|
|
69
|
-
* 3. Batch handler: `[
|
|
109
|
+
* 1. Simple handler: `(message) => Future.value(Result.Ok(undefined))`
|
|
110
|
+
* 2. Handler with prefetch: `[(message) => ..., { prefetch: 10 }]`
|
|
111
|
+
* 3. Batch handler: `[(messages) => ..., { batchSize: 5, batchTimeout: 1000 }]`
|
|
70
112
|
*/
|
|
71
|
-
type
|
|
113
|
+
type WorkerInferSafeConsumerHandlerEntry<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = WorkerInferSafeConsumerHandler<TContract, TName> | readonly [WorkerInferSafeConsumerHandler<TContract, TName>, {
|
|
72
114
|
prefetch?: number;
|
|
73
115
|
batchSize?: never;
|
|
74
116
|
batchTimeout?: never;
|
|
75
|
-
}] | readonly [
|
|
117
|
+
}] | readonly [WorkerInferSafeConsumerBatchHandler<TContract, TName>, {
|
|
76
118
|
prefetch?: number;
|
|
77
119
|
batchSize: number;
|
|
78
120
|
batchTimeout?: number;
|
|
79
121
|
}];
|
|
80
122
|
/**
|
|
81
|
-
*
|
|
82
|
-
*
|
|
123
|
+
* Safe consumer handlers for a contract.
|
|
124
|
+
* All handlers return `Future<Result<void, HandlerError>>` for explicit error control.
|
|
125
|
+
*/
|
|
126
|
+
type WorkerInferSafeConsumerHandlers<TContract extends ContractDefinition> = { [K in InferConsumerNames<TContract>]: WorkerInferSafeConsumerHandlerEntry<TContract, K> };
|
|
127
|
+
/**
|
|
128
|
+
* Unsafe consumer handler type for a specific consumer.
|
|
129
|
+
* Returns a `Promise<void>` - throws exceptions on error.
|
|
130
|
+
*
|
|
131
|
+
* @deprecated Prefer using safe handlers (WorkerInferSafeConsumerHandler) that return
|
|
132
|
+
* `Future<Result<void, HandlerError>>` for better error handling.
|
|
133
|
+
*
|
|
134
|
+
* **Note:** When using unsafe handlers:
|
|
135
|
+
* - All thrown errors are treated as retryable by default (when retry is configured)
|
|
136
|
+
* - Use RetryableError or NonRetryableError to control retry behavior explicitly
|
|
137
|
+
*/
|
|
138
|
+
type WorkerInferUnsafeConsumerHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = (message: WorkerInferConsumerInput<TContract, TName>) => Promise<void>;
|
|
139
|
+
/**
|
|
140
|
+
* Unsafe consumer handler type for batch processing.
|
|
141
|
+
* Returns a `Promise<void>` - throws exceptions on error.
|
|
142
|
+
*
|
|
143
|
+
* @deprecated Prefer using safe handlers (WorkerInferSafeConsumerBatchHandler) that return
|
|
144
|
+
* `Future<Result<void, HandlerError>>` for better error handling.
|
|
145
|
+
*/
|
|
146
|
+
type WorkerInferUnsafeConsumerBatchHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = (messages: Array<WorkerInferConsumerInput<TContract, TName>>) => Promise<void>;
|
|
147
|
+
/**
|
|
148
|
+
* Unsafe handler entry for a consumer - either a function or a tuple of [handler, options].
|
|
149
|
+
*
|
|
150
|
+
* @deprecated Prefer using safe handler entries (WorkerInferSafeConsumerHandlerEntry).
|
|
83
151
|
*/
|
|
84
|
-
type
|
|
152
|
+
type WorkerInferUnsafeConsumerHandlerEntry<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = WorkerInferUnsafeConsumerHandler<TContract, TName> | readonly [WorkerInferUnsafeConsumerHandler<TContract, TName>, {
|
|
153
|
+
prefetch?: number;
|
|
154
|
+
batchSize?: never;
|
|
155
|
+
batchTimeout?: never;
|
|
156
|
+
}] | readonly [WorkerInferUnsafeConsumerBatchHandler<TContract, TName>, {
|
|
157
|
+
prefetch?: number;
|
|
158
|
+
batchSize: number;
|
|
159
|
+
batchTimeout?: number;
|
|
160
|
+
}];
|
|
161
|
+
/**
|
|
162
|
+
* Unsafe consumer handlers for a contract.
|
|
163
|
+
*
|
|
164
|
+
* @deprecated Prefer using safe handlers (WorkerInferSafeConsumerHandlers).
|
|
165
|
+
*/
|
|
166
|
+
type WorkerInferUnsafeConsumerHandlers<TContract extends ContractDefinition> = { [K in InferConsumerNames<TContract>]: WorkerInferUnsafeConsumerHandlerEntry<TContract, K> };
|
|
167
|
+
/**
|
|
168
|
+
* @deprecated Use WorkerInferUnsafeConsumerHandler instead
|
|
169
|
+
*/
|
|
170
|
+
type WorkerInferConsumerHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = WorkerInferUnsafeConsumerHandler<TContract, TName>;
|
|
171
|
+
/**
|
|
172
|
+
* @deprecated Use WorkerInferUnsafeConsumerBatchHandler instead
|
|
173
|
+
*/
|
|
174
|
+
type WorkerInferConsumerBatchHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = WorkerInferUnsafeConsumerBatchHandler<TContract, TName>;
|
|
175
|
+
/**
|
|
176
|
+
* @deprecated Use WorkerInferUnsafeConsumerHandlerEntry instead
|
|
177
|
+
*/
|
|
178
|
+
type WorkerInferConsumerHandlerEntry<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = WorkerInferUnsafeConsumerHandlerEntry<TContract, TName>;
|
|
179
|
+
/**
|
|
180
|
+
* @deprecated Use WorkerInferUnsafeConsumerHandlers instead
|
|
181
|
+
*/
|
|
182
|
+
type WorkerInferConsumerHandlers<TContract extends ContractDefinition> = WorkerInferUnsafeConsumerHandlers<TContract>;
|
|
85
183
|
//#endregion
|
|
86
184
|
//#region src/worker.d.ts
|
|
185
|
+
/**
|
|
186
|
+
* Retry configuration options for handling failed message processing.
|
|
187
|
+
*
|
|
188
|
+
* When enabled, the worker will automatically retry failed messages using
|
|
189
|
+
* RabbitMQ's native TTL + Dead Letter Exchange (DLX) pattern.
|
|
190
|
+
*/
|
|
191
|
+
type RetryOptions = {
|
|
192
|
+
/** Maximum retry attempts before sending to DLQ (default: 3) */
|
|
193
|
+
maxRetries?: number;
|
|
194
|
+
/** Initial delay in ms before first retry (default: 1000) */
|
|
195
|
+
initialDelayMs?: number;
|
|
196
|
+
/** Maximum delay in ms between retries (default: 30000) */
|
|
197
|
+
maxDelayMs?: number;
|
|
198
|
+
/** Exponential backoff multiplier (default: 2) */
|
|
199
|
+
backoffMultiplier?: number;
|
|
200
|
+
/** Add jitter to prevent thundering herd (default: true) */
|
|
201
|
+
jitter?: boolean;
|
|
202
|
+
};
|
|
87
203
|
/**
|
|
88
204
|
* Options for creating a type-safe AMQP worker.
|
|
89
205
|
*
|
|
@@ -117,21 +233,35 @@ type WorkerInferConsumerHandlers<TContract extends ContractDefinition> = { [K in
|
|
|
117
233
|
* connectionOptions: {
|
|
118
234
|
* heartbeatIntervalInSeconds: 30
|
|
119
235
|
* },
|
|
120
|
-
* logger: myLogger
|
|
236
|
+
* logger: myLogger,
|
|
237
|
+
* retry: {
|
|
238
|
+
* maxRetries: 3,
|
|
239
|
+
* initialDelayMs: 1000,
|
|
240
|
+
* maxDelayMs: 30000,
|
|
241
|
+
* backoffMultiplier: 2,
|
|
242
|
+
* jitter: true
|
|
243
|
+
* }
|
|
121
244
|
* };
|
|
122
245
|
* ```
|
|
123
246
|
*/
|
|
124
247
|
type CreateWorkerOptions<TContract extends ContractDefinition> = {
|
|
125
248
|
/** The AMQP contract definition specifying consumers and their message schemas */
|
|
126
249
|
contract: TContract;
|
|
127
|
-
/**
|
|
128
|
-
|
|
250
|
+
/**
|
|
251
|
+
* Handlers for each consumer defined in the contract.
|
|
252
|
+
* Handlers must return `Future<Result<void, HandlerError>>` for explicit error handling.
|
|
253
|
+
* Use defineHandler() to create safe handlers, or defineUnsafeHandler() which wraps
|
|
254
|
+
* Promise-based handlers into safe handlers internally.
|
|
255
|
+
*/
|
|
256
|
+
handlers: WorkerInferSafeConsumerHandlers<TContract>;
|
|
129
257
|
/** AMQP broker URL(s). Multiple URLs provide failover support */
|
|
130
258
|
urls: ConnectionUrl[];
|
|
131
259
|
/** Optional connection configuration (heartbeat, reconnect settings, etc.) */
|
|
132
260
|
connectionOptions?: AmqpConnectionManagerOptions | undefined;
|
|
133
261
|
/** Optional logger for logging message consumption and errors */
|
|
134
262
|
logger?: Logger | undefined;
|
|
263
|
+
/** Retry configuration - when undefined, uses legacy behavior (immediate requeue) */
|
|
264
|
+
retry?: RetryOptions | undefined;
|
|
135
265
|
};
|
|
136
266
|
/**
|
|
137
267
|
* Type-safe AMQP worker for consuming messages from RabbitMQ.
|
|
@@ -177,9 +307,15 @@ declare class TypedAmqpWorker<TContract extends ContractDefinition> {
|
|
|
177
307
|
private readonly contract;
|
|
178
308
|
private readonly amqpClient;
|
|
179
309
|
private readonly logger?;
|
|
310
|
+
/**
|
|
311
|
+
* Internal handler type - always safe handlers (`Future<Result>`).
|
|
312
|
+
* Unsafe handlers are wrapped into safe handlers by defineUnsafeHandler/defineUnsafeHandlers.
|
|
313
|
+
*/
|
|
180
314
|
private readonly actualHandlers;
|
|
181
315
|
private readonly consumerOptions;
|
|
182
316
|
private readonly batchTimers;
|
|
317
|
+
private readonly consumerTags;
|
|
318
|
+
private readonly retryConfig;
|
|
183
319
|
private constructor();
|
|
184
320
|
/**
|
|
185
321
|
* Create a type-safe AMQP worker from a contract.
|
|
@@ -197,17 +333,13 @@ declare class TypedAmqpWorker<TContract extends ContractDefinition> {
|
|
|
197
333
|
*
|
|
198
334
|
* @example
|
|
199
335
|
* ```typescript
|
|
200
|
-
* const
|
|
336
|
+
* const worker = await TypedAmqpWorker.create({
|
|
201
337
|
* contract: myContract,
|
|
202
338
|
* handlers: {
|
|
203
339
|
* processOrder: async (msg) => console.log('Order:', msg.orderId)
|
|
204
340
|
* },
|
|
205
341
|
* urls: ['amqp://localhost']
|
|
206
342
|
* }).resultToPromise();
|
|
207
|
-
*
|
|
208
|
-
* if (workerResult.isError()) {
|
|
209
|
-
* console.error('Failed to create worker:', workerResult.error);
|
|
210
|
-
* }
|
|
211
343
|
* ```
|
|
212
344
|
*/
|
|
213
345
|
static create<TContract extends ContractDefinition>({
|
|
@@ -215,7 +347,8 @@ declare class TypedAmqpWorker<TContract extends ContractDefinition> {
|
|
|
215
347
|
handlers,
|
|
216
348
|
urls,
|
|
217
349
|
connectionOptions,
|
|
218
|
-
logger
|
|
350
|
+
logger,
|
|
351
|
+
retry
|
|
219
352
|
}: CreateWorkerOptions<TContract>): Future<Result<TypedAmqpWorker<TContract>, TechnicalError>>;
|
|
220
353
|
/**
|
|
221
354
|
* Close the AMQP channel and connection.
|
|
@@ -234,6 +367,11 @@ declare class TypedAmqpWorker<TContract extends ContractDefinition> {
|
|
|
234
367
|
* ```
|
|
235
368
|
*/
|
|
236
369
|
close(): Future<Result<void, TechnicalError>>;
|
|
370
|
+
/**
|
|
371
|
+
* Set up wait queues for retry mechanism.
|
|
372
|
+
* Creates and binds wait queues for each consumer queue that has DLX configuration.
|
|
373
|
+
*/
|
|
374
|
+
private setupWaitQueues;
|
|
237
375
|
/**
|
|
238
376
|
* Start consuming messages for all consumers
|
|
239
377
|
*/
|
|
@@ -245,149 +383,267 @@ declare class TypedAmqpWorker<TContract extends ContractDefinition> {
|
|
|
245
383
|
private consume;
|
|
246
384
|
/**
|
|
247
385
|
* Parse and validate a message from AMQP
|
|
248
|
-
* @returns Future<Result<validated message, void
|
|
386
|
+
* @returns `Future<Result<validated message, void>>` - Ok with validated message, or Error (already handled with nack)
|
|
249
387
|
*/
|
|
250
388
|
private parseAndValidateMessage;
|
|
251
389
|
/**
|
|
252
390
|
* Consume messages one at a time
|
|
253
391
|
*/
|
|
254
392
|
private consumeSingle;
|
|
393
|
+
/**
|
|
394
|
+
* Handle batch processing error by applying error handling to all messages.
|
|
395
|
+
*/
|
|
396
|
+
private handleBatchError;
|
|
255
397
|
/**
|
|
256
398
|
* Consume messages in batches
|
|
257
399
|
*/
|
|
258
400
|
private consumeBatch;
|
|
401
|
+
/**
|
|
402
|
+
* Handle error in message processing with retry logic.
|
|
403
|
+
*
|
|
404
|
+
* Flow:
|
|
405
|
+
* 1. If NonRetryableError -> send directly to DLQ (no retry)
|
|
406
|
+
* 2. If no retry config -> legacy behavior (immediate requeue)
|
|
407
|
+
* 3. If max retries exceeded -> send to DLQ
|
|
408
|
+
* 4. Otherwise -> publish to wait queue with TTL for retry
|
|
409
|
+
*/
|
|
410
|
+
private handleError;
|
|
411
|
+
/**
|
|
412
|
+
* Calculate retry delay with exponential backoff and optional jitter.
|
|
413
|
+
*/
|
|
414
|
+
private calculateRetryDelay;
|
|
415
|
+
/**
|
|
416
|
+
* Parse message content for republishing.
|
|
417
|
+
* Prevents double JSON serialization by converting Buffer to object when possible.
|
|
418
|
+
*/
|
|
419
|
+
private parseMessageContentForRetry;
|
|
420
|
+
/**
|
|
421
|
+
* Publish message to wait queue for retry after TTL expires.
|
|
422
|
+
*
|
|
423
|
+
* ┌─────────────────────────────────────────────────────────────────┐
|
|
424
|
+
* │ Retry Flow (Native RabbitMQ TTL + DLX Pattern) │
|
|
425
|
+
* ├─────────────────────────────────────────────────────────────────┤
|
|
426
|
+
* │ │
|
|
427
|
+
* │ 1. Handler throws any Error │
|
|
428
|
+
* │ ↓ │
|
|
429
|
+
* │ 2. Worker publishes to DLX with routing key: {queue}-wait │
|
|
430
|
+
* │ ↓ │
|
|
431
|
+
* │ 3. DLX routes to wait queue: {queue}-wait │
|
|
432
|
+
* │ (with expiration: calculated backoff delay) │
|
|
433
|
+
* │ ↓ │
|
|
434
|
+
* │ 4. Message waits in queue until TTL expires │
|
|
435
|
+
* │ ↓ │
|
|
436
|
+
* │ 5. Expired message dead-lettered to DLX │
|
|
437
|
+
* │ (with routing key: {queue}) │
|
|
438
|
+
* │ ↓ │
|
|
439
|
+
* │ 6. DLX routes back to main queue → RETRY │
|
|
440
|
+
* │ ↓ │
|
|
441
|
+
* │ 7. If retries exhausted: nack without requeue → DLQ │
|
|
442
|
+
* │ │
|
|
443
|
+
* └─────────────────────────────────────────────────────────────────┘
|
|
444
|
+
*/
|
|
445
|
+
private publishForRetry;
|
|
446
|
+
/**
|
|
447
|
+
* Send message to dead letter queue.
|
|
448
|
+
* Nacks the message without requeue, relying on DLX configuration.
|
|
449
|
+
*/
|
|
450
|
+
private sendToDLQ;
|
|
259
451
|
}
|
|
260
452
|
//#endregion
|
|
261
453
|
//#region src/handlers.d.ts
|
|
262
454
|
/**
|
|
263
455
|
* Define a type-safe handler for a specific consumer in a contract.
|
|
264
456
|
*
|
|
265
|
-
* This
|
|
266
|
-
* providing
|
|
457
|
+
* **Recommended:** This function creates handlers that return `Future<Result<void, HandlerError>>`,
|
|
458
|
+
* providing explicit error handling and better control over retry behavior.
|
|
267
459
|
*
|
|
268
460
|
* Supports three patterns:
|
|
269
461
|
* 1. Simple handler: just the function (single message handler)
|
|
270
462
|
* 2. Handler with prefetch: [handler, { prefetch: 10 }] (single message handler with config)
|
|
271
463
|
* 3. Batch handler: [batchHandler, { batchSize: 5, batchTimeout: 1000 }] (REQUIRES batchSize config)
|
|
272
464
|
*
|
|
273
|
-
* **Important**: Batch handlers (handlers that accept an array of messages) MUST include
|
|
274
|
-
* batchSize configuration. You cannot create a batch handler without specifying batchSize.
|
|
275
|
-
*
|
|
276
465
|
* @template TContract - The contract definition type
|
|
277
466
|
* @template TName - The consumer name from the contract
|
|
278
467
|
* @param contract - The contract definition containing the consumer
|
|
279
468
|
* @param consumerName - The name of the consumer from the contract
|
|
280
|
-
* @param handler - The
|
|
469
|
+
* @param handler - The handler function that returns `Future<Result<void, HandlerError>>`
|
|
281
470
|
* @param options - Optional consumer options (prefetch, batchSize, batchTimeout)
|
|
282
|
-
* - For single-message handlers: { prefetch?: number } is optional
|
|
283
|
-
* - For batch handlers: { batchSize: number, batchTimeout?: number } is REQUIRED
|
|
284
471
|
* @returns A type-safe handler that can be used with TypedAmqpWorker
|
|
285
472
|
*
|
|
286
473
|
* @example
|
|
287
474
|
* ```typescript
|
|
288
|
-
* import { defineHandler } from '@amqp-contract/worker';
|
|
475
|
+
* import { defineHandler, RetryableError, NonRetryableError } from '@amqp-contract/worker';
|
|
476
|
+
* import { Future, Result } from '@swan-io/boxed';
|
|
289
477
|
* import { orderContract } from './contract';
|
|
290
478
|
*
|
|
291
|
-
* // Simple
|
|
479
|
+
* // Simple handler with explicit error handling using mapError
|
|
292
480
|
* const processOrderHandler = defineHandler(
|
|
293
481
|
* orderContract,
|
|
294
482
|
* 'processOrder',
|
|
295
|
-
*
|
|
296
|
-
*
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
* );
|
|
300
|
-
*
|
|
301
|
-
* // Single-message handler with prefetch
|
|
302
|
-
* const processOrderWithPrefetch = defineHandler(
|
|
303
|
-
* orderContract,
|
|
304
|
-
* 'processOrder',
|
|
305
|
-
* async (message) => {
|
|
306
|
-
* await processOrder(message);
|
|
307
|
-
* },
|
|
308
|
-
* { prefetch: 10 }
|
|
483
|
+
* (message) =>
|
|
484
|
+
* Future.fromPromise(processPayment(message))
|
|
485
|
+
* .mapOk(() => undefined)
|
|
486
|
+
* .mapError((error) => new RetryableError('Payment failed', error))
|
|
309
487
|
* );
|
|
310
488
|
*
|
|
311
|
-
* //
|
|
312
|
-
* const
|
|
489
|
+
* // Handler with validation (non-retryable error)
|
|
490
|
+
* const validateOrderHandler = defineHandler(
|
|
313
491
|
* orderContract,
|
|
314
|
-
* '
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
*
|
|
319
|
-
*
|
|
492
|
+
* 'validateOrder',
|
|
493
|
+
* (message) => {
|
|
494
|
+
* if (message.amount < 1) {
|
|
495
|
+
* // Won't be retried - goes directly to DLQ
|
|
496
|
+
* return Future.value(Result.Error(new NonRetryableError('Invalid order amount')));
|
|
497
|
+
* }
|
|
498
|
+
* return Future.value(Result.Ok(undefined));
|
|
499
|
+
* }
|
|
320
500
|
* );
|
|
321
501
|
* ```
|
|
322
502
|
*/
|
|
323
|
-
declare function defineHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler:
|
|
324
|
-
declare function defineHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler:
|
|
503
|
+
declare function defineHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler: WorkerInferSafeConsumerHandler<TContract, TName>): WorkerInferSafeConsumerHandlerEntry<TContract, TName>;
|
|
504
|
+
declare function defineHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler: WorkerInferSafeConsumerHandler<TContract, TName>, options: {
|
|
325
505
|
prefetch?: number;
|
|
326
506
|
batchSize?: never;
|
|
327
507
|
batchTimeout?: never;
|
|
328
|
-
}):
|
|
329
|
-
declare function defineHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler:
|
|
508
|
+
}): WorkerInferSafeConsumerHandlerEntry<TContract, TName>;
|
|
509
|
+
declare function defineHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler: WorkerInferSafeConsumerBatchHandler<TContract, TName>, options: {
|
|
330
510
|
prefetch?: number;
|
|
331
511
|
batchSize: number;
|
|
332
512
|
batchTimeout?: number;
|
|
333
|
-
}):
|
|
513
|
+
}): WorkerInferSafeConsumerHandlerEntry<TContract, TName>;
|
|
334
514
|
/**
|
|
335
515
|
* Define multiple type-safe handlers for consumers in a contract.
|
|
336
516
|
*
|
|
337
|
-
* This
|
|
338
|
-
*
|
|
517
|
+
* **Recommended:** This function creates handlers that return `Future<Result<void, HandlerError>>`,
|
|
518
|
+
* providing explicit error handling and better control over retry behavior.
|
|
339
519
|
*
|
|
340
520
|
* @template TContract - The contract definition type
|
|
341
521
|
* @param contract - The contract definition containing the consumers
|
|
342
|
-
* @param handlers - An object with
|
|
522
|
+
* @param handlers - An object with handler functions for each consumer
|
|
343
523
|
* @returns A type-safe handlers object that can be used with TypedAmqpWorker
|
|
344
524
|
*
|
|
345
525
|
* @example
|
|
346
526
|
* ```typescript
|
|
347
|
-
* import { defineHandlers } from '@amqp-contract/worker';
|
|
527
|
+
* import { defineHandlers, RetryableError } from '@amqp-contract/worker';
|
|
528
|
+
* import { Future } from '@swan-io/boxed';
|
|
348
529
|
* import { orderContract } from './contract';
|
|
349
530
|
*
|
|
350
|
-
* // Define all handlers at once
|
|
351
531
|
* const handlers = defineHandlers(orderContract, {
|
|
352
|
-
* processOrder:
|
|
353
|
-
*
|
|
354
|
-
*
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
*
|
|
359
|
-
*
|
|
360
|
-
* shipOrder: async (message) => {
|
|
361
|
-
* await prepareShipment(message);
|
|
362
|
-
* },
|
|
363
|
-
* });
|
|
364
|
-
*
|
|
365
|
-
* // Use the handlers in worker
|
|
366
|
-
* const worker = await TypedAmqpWorker.create({
|
|
367
|
-
* contract: orderContract,
|
|
368
|
-
* handlers,
|
|
369
|
-
* connection: 'amqp://localhost',
|
|
532
|
+
* processOrder: (message) =>
|
|
533
|
+
* Future.fromPromise(processPayment(message))
|
|
534
|
+
* .mapOk(() => undefined)
|
|
535
|
+
* .mapError((error) => new RetryableError('Payment failed', error)),
|
|
536
|
+
* notifyOrder: (message) =>
|
|
537
|
+
* Future.fromPromise(sendNotification(message))
|
|
538
|
+
* .mapOk(() => undefined)
|
|
539
|
+
* .mapError((error) => new RetryableError('Notification failed', error)),
|
|
370
540
|
* });
|
|
371
541
|
* ```
|
|
542
|
+
*/
|
|
543
|
+
declare function defineHandlers<TContract extends ContractDefinition>(contract: TContract, handlers: WorkerInferSafeConsumerHandlers<TContract>): WorkerInferSafeConsumerHandlers<TContract>;
|
|
544
|
+
/**
|
|
545
|
+
* Unsafe handler type for single messages (internal use).
|
|
546
|
+
*/
|
|
547
|
+
type UnsafeHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = (message: WorkerInferConsumerInput<TContract, TName>) => Promise<void>;
|
|
548
|
+
/**
|
|
549
|
+
* Unsafe handler type for batch messages (internal use).
|
|
550
|
+
*/
|
|
551
|
+
type UnsafeBatchHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = (messages: Array<WorkerInferConsumerInput<TContract, TName>>) => Promise<void>;
|
|
552
|
+
/**
|
|
553
|
+
* Define an unsafe handler for a specific consumer in a contract.
|
|
554
|
+
*
|
|
555
|
+
* @deprecated Use `defineHandler` instead for explicit error handling with `Future<Result>`.
|
|
556
|
+
*
|
|
557
|
+
* **Warning:** Unsafe handlers use exception-based error handling:
|
|
558
|
+
* - All thrown errors are treated as retryable by default
|
|
559
|
+
* - Harder to reason about which errors should be retried
|
|
560
|
+
* - May lead to unexpected retry behavior
|
|
561
|
+
*
|
|
562
|
+
* **Note:** Internally, this function wraps the Promise-based handler into a Future-based
|
|
563
|
+
* safe handler for consistent processing in the worker.
|
|
564
|
+
*
|
|
565
|
+
* @template TContract - The contract definition type
|
|
566
|
+
* @template TName - The consumer name from the contract
|
|
567
|
+
* @param contract - The contract definition containing the consumer
|
|
568
|
+
* @param consumerName - The name of the consumer from the contract
|
|
569
|
+
* @param handler - The async handler function that processes messages
|
|
570
|
+
* @param options - Optional consumer options (prefetch, batchSize, batchTimeout)
|
|
571
|
+
* @returns A type-safe handler that can be used with TypedAmqpWorker
|
|
372
572
|
*
|
|
373
573
|
* @example
|
|
374
574
|
* ```typescript
|
|
375
|
-
*
|
|
376
|
-
* async function handleProcessOrder(message: WorkerInferConsumerInput<typeof orderContract, 'processOrder'>) {
|
|
377
|
-
* await processOrder(message);
|
|
378
|
-
* }
|
|
575
|
+
* import { defineUnsafeHandler } from '@amqp-contract/worker';
|
|
379
576
|
*
|
|
380
|
-
*
|
|
381
|
-
*
|
|
382
|
-
*
|
|
577
|
+
* // ⚠️ Consider using defineHandler for better error handling
|
|
578
|
+
* const processOrderHandler = defineUnsafeHandler(
|
|
579
|
+
* orderContract,
|
|
580
|
+
* 'processOrder',
|
|
581
|
+
* async (message) => {
|
|
582
|
+
* // Throws on error - will be retried
|
|
583
|
+
* await processPayment(message);
|
|
584
|
+
* }
|
|
585
|
+
* );
|
|
586
|
+
* ```
|
|
587
|
+
*/
|
|
588
|
+
declare function defineUnsafeHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler: UnsafeHandler<TContract, TName>): WorkerInferSafeConsumerHandlerEntry<TContract, TName>;
|
|
589
|
+
declare function defineUnsafeHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler: UnsafeHandler<TContract, TName>, options: {
|
|
590
|
+
prefetch?: number;
|
|
591
|
+
batchSize?: never;
|
|
592
|
+
batchTimeout?: never;
|
|
593
|
+
}): WorkerInferSafeConsumerHandlerEntry<TContract, TName>;
|
|
594
|
+
declare function defineUnsafeHandler<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>>(contract: TContract, consumerName: TName, handler: UnsafeBatchHandler<TContract, TName>, options: {
|
|
595
|
+
prefetch?: number;
|
|
596
|
+
batchSize: number;
|
|
597
|
+
batchTimeout?: number;
|
|
598
|
+
}): WorkerInferSafeConsumerHandlerEntry<TContract, TName>;
|
|
599
|
+
/**
|
|
600
|
+
* Unsafe handler entry type for internal use.
|
|
601
|
+
*/
|
|
602
|
+
type UnsafeHandlerEntry<TContract extends ContractDefinition, TName extends InferConsumerNames<TContract>> = UnsafeHandler<TContract, TName> | readonly [UnsafeHandler<TContract, TName>, {
|
|
603
|
+
prefetch?: number;
|
|
604
|
+
batchSize?: never;
|
|
605
|
+
batchTimeout?: never;
|
|
606
|
+
}] | readonly [UnsafeBatchHandler<TContract, TName>, {
|
|
607
|
+
prefetch?: number;
|
|
608
|
+
batchSize: number;
|
|
609
|
+
batchTimeout?: number;
|
|
610
|
+
}];
|
|
611
|
+
/**
|
|
612
|
+
* Unsafe handlers object type for internal use.
|
|
613
|
+
*/
|
|
614
|
+
type UnsafeHandlers<TContract extends ContractDefinition> = { [K in InferConsumerNames<TContract>]: UnsafeHandlerEntry<TContract, K> };
|
|
615
|
+
/**
|
|
616
|
+
* Define multiple unsafe handlers for consumers in a contract.
|
|
383
617
|
*
|
|
384
|
-
*
|
|
385
|
-
*
|
|
386
|
-
*
|
|
618
|
+
* @deprecated Use `defineHandlers` instead for explicit error handling with `Future<Result>`.
|
|
619
|
+
*
|
|
620
|
+
* **Warning:** Unsafe handlers use exception-based error handling.
|
|
621
|
+
* Consider migrating to safe handlers for better error control.
|
|
622
|
+
*
|
|
623
|
+
* **Note:** Internally, this function wraps all Promise-based handlers into Future-based
|
|
624
|
+
* safe handlers for consistent processing in the worker.
|
|
625
|
+
*
|
|
626
|
+
* @template TContract - The contract definition type
|
|
627
|
+
* @param contract - The contract definition containing the consumers
|
|
628
|
+
* @param handlers - An object with async handler functions for each consumer
|
|
629
|
+
* @returns A type-safe handlers object that can be used with TypedAmqpWorker
|
|
630
|
+
*
|
|
631
|
+
* @example
|
|
632
|
+
* ```typescript
|
|
633
|
+
* import { defineUnsafeHandlers } from '@amqp-contract/worker';
|
|
634
|
+
*
|
|
635
|
+
* // ⚠️ Consider using defineHandlers for better error handling
|
|
636
|
+
* const handlers = defineUnsafeHandlers(orderContract, {
|
|
637
|
+
* processOrder: async (message) => {
|
|
638
|
+
* await processPayment(message);
|
|
639
|
+
* },
|
|
640
|
+
* notifyOrder: async (message) => {
|
|
641
|
+
* await sendNotification(message);
|
|
642
|
+
* },
|
|
387
643
|
* });
|
|
388
644
|
* ```
|
|
389
645
|
*/
|
|
390
|
-
declare function
|
|
646
|
+
declare function defineUnsafeHandlers<TContract extends ContractDefinition>(contract: TContract, handlers: UnsafeHandlers<TContract>): WorkerInferSafeConsumerHandlers<TContract>;
|
|
391
647
|
//#endregion
|
|
392
|
-
export { type CreateWorkerOptions, MessageValidationError, TechnicalError, TypedAmqpWorker, type WorkerInferConsumerBatchHandler, type WorkerInferConsumerHandler, type WorkerInferConsumerHandlerEntry, type WorkerInferConsumerHandlers, type WorkerInferConsumerInput, defineHandler, defineHandlers };
|
|
648
|
+
export { type CreateWorkerOptions, type HandlerError, MessageValidationError, NonRetryableError, type RetryOptions, RetryableError, TechnicalError, TypedAmqpWorker, type WorkerInferConsumerBatchHandler, type WorkerInferConsumerHandler, type WorkerInferConsumerHandlerEntry, type WorkerInferConsumerHandlers, type WorkerInferConsumerInput, type WorkerInferSafeConsumerBatchHandler, type WorkerInferSafeConsumerHandler, type WorkerInferSafeConsumerHandlerEntry, type WorkerInferSafeConsumerHandlers, type WorkerInferUnsafeConsumerBatchHandler, type WorkerInferUnsafeConsumerHandler, type WorkerInferUnsafeConsumerHandlerEntry, type WorkerInferUnsafeConsumerHandlers, defineHandler, defineHandlers, defineUnsafeHandler, defineUnsafeHandlers };
|
|
393
649
|
//# sourceMappingURL=index.d.cts.map
|