alepha 0.12.1 → 0.13.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.
Files changed (198) hide show
  1. package/dist/api-notifications/index.d.ts +111 -111
  2. package/dist/api-users/index.d.ts +1240 -1240
  3. package/dist/api-verifications/index.d.ts +94 -94
  4. package/dist/cli/{dist-Sz2EXvQX.cjs → dist-Dl9Vl7Ur.js} +17 -13
  5. package/dist/cli/{dist-BBPjuQ56.js.map → dist-Dl9Vl7Ur.js.map} +1 -1
  6. package/dist/cli/index.d.ts +3 -11
  7. package/dist/cli/index.js +106 -74
  8. package/dist/cli/index.js.map +1 -1
  9. package/dist/email/index.js +71 -73
  10. package/dist/email/index.js.map +1 -1
  11. package/dist/orm/index.d.ts +1 -1
  12. package/dist/orm/index.js.map +1 -1
  13. package/dist/queue/index.d.ts +4 -4
  14. package/dist/redis/index.d.ts +10 -10
  15. package/dist/retry/index.d.ts +1 -1
  16. package/dist/retry/index.js +2 -2
  17. package/dist/retry/index.js.map +1 -1
  18. package/dist/scheduler/index.d.ts +6 -6
  19. package/dist/server/index.js +1 -1
  20. package/dist/server/index.js.map +1 -1
  21. package/dist/server-auth/index.d.ts +193 -193
  22. package/dist/server-health/index.d.ts +17 -17
  23. package/dist/server-links/index.d.ts +34 -34
  24. package/dist/server-metrics/index.js +170 -174
  25. package/dist/server-metrics/index.js.map +1 -1
  26. package/dist/server-security/index.d.ts +9 -9
  27. package/dist/vite/index.js +4 -5
  28. package/dist/vite/index.js.map +1 -1
  29. package/dist/websocket/index.d.ts +7 -7
  30. package/package.json +52 -103
  31. package/src/cli/apps/AlephaPackageBuilderCli.ts +7 -2
  32. package/src/cli/assets/appRouterTs.ts +9 -0
  33. package/src/cli/assets/indexHtml.ts +2 -1
  34. package/src/cli/assets/mainBrowserTs.ts +10 -0
  35. package/src/cli/commands/CoreCommands.ts +6 -5
  36. package/src/cli/commands/DrizzleCommands.ts +65 -57
  37. package/src/cli/commands/VerifyCommands.ts +1 -1
  38. package/src/cli/services/ProjectUtils.ts +44 -38
  39. package/src/orm/providers/DrizzleKitProvider.ts +1 -1
  40. package/src/retry/descriptors/$retry.ts +5 -3
  41. package/src/server/providers/NodeHttpServerProvider.ts +1 -1
  42. package/src/vite/helpers/boot.ts +3 -3
  43. package/dist/api-files/index.cjs +0 -1293
  44. package/dist/api-files/index.cjs.map +0 -1
  45. package/dist/api-files/index.d.cts +0 -829
  46. package/dist/api-jobs/index.cjs +0 -274
  47. package/dist/api-jobs/index.cjs.map +0 -1
  48. package/dist/api-jobs/index.d.cts +0 -654
  49. package/dist/api-notifications/index.cjs +0 -380
  50. package/dist/api-notifications/index.cjs.map +0 -1
  51. package/dist/api-notifications/index.d.cts +0 -289
  52. package/dist/api-parameters/index.cjs +0 -66
  53. package/dist/api-parameters/index.cjs.map +0 -1
  54. package/dist/api-parameters/index.d.cts +0 -84
  55. package/dist/api-users/index.cjs +0 -6009
  56. package/dist/api-users/index.cjs.map +0 -1
  57. package/dist/api-users/index.d.cts +0 -4740
  58. package/dist/api-verifications/index.cjs +0 -407
  59. package/dist/api-verifications/index.cjs.map +0 -1
  60. package/dist/api-verifications/index.d.cts +0 -207
  61. package/dist/batch/index.cjs +0 -408
  62. package/dist/batch/index.cjs.map +0 -1
  63. package/dist/batch/index.d.cts +0 -330
  64. package/dist/bin/index.cjs +0 -17
  65. package/dist/bin/index.cjs.map +0 -1
  66. package/dist/bin/index.d.cts +0 -1
  67. package/dist/bucket/index.cjs +0 -303
  68. package/dist/bucket/index.cjs.map +0 -1
  69. package/dist/bucket/index.d.cts +0 -355
  70. package/dist/cache/index.cjs +0 -241
  71. package/dist/cache/index.cjs.map +0 -1
  72. package/dist/cache/index.d.cts +0 -202
  73. package/dist/cache-redis/index.cjs +0 -84
  74. package/dist/cache-redis/index.cjs.map +0 -1
  75. package/dist/cache-redis/index.d.cts +0 -40
  76. package/dist/cli/chunk-DSlc6foC.cjs +0 -43
  77. package/dist/cli/dist-BBPjuQ56.js +0 -2778
  78. package/dist/cli/dist-Sz2EXvQX.cjs.map +0 -1
  79. package/dist/cli/index.cjs +0 -1241
  80. package/dist/cli/index.cjs.map +0 -1
  81. package/dist/cli/index.d.cts +0 -422
  82. package/dist/command/index.cjs +0 -693
  83. package/dist/command/index.cjs.map +0 -1
  84. package/dist/command/index.d.cts +0 -340
  85. package/dist/core/index.cjs +0 -2264
  86. package/dist/core/index.cjs.map +0 -1
  87. package/dist/core/index.d.cts +0 -1927
  88. package/dist/datetime/index.cjs +0 -318
  89. package/dist/datetime/index.cjs.map +0 -1
  90. package/dist/datetime/index.d.cts +0 -145
  91. package/dist/email/index.cjs +0 -10874
  92. package/dist/email/index.cjs.map +0 -1
  93. package/dist/email/index.d.cts +0 -186
  94. package/dist/fake/index.cjs +0 -34641
  95. package/dist/fake/index.cjs.map +0 -1
  96. package/dist/fake/index.d.cts +0 -74
  97. package/dist/file/index.cjs +0 -1212
  98. package/dist/file/index.cjs.map +0 -1
  99. package/dist/file/index.d.cts +0 -698
  100. package/dist/lock/index.cjs +0 -226
  101. package/dist/lock/index.cjs.map +0 -1
  102. package/dist/lock/index.d.cts +0 -361
  103. package/dist/lock-redis/index.cjs +0 -113
  104. package/dist/lock-redis/index.cjs.map +0 -1
  105. package/dist/lock-redis/index.d.cts +0 -24
  106. package/dist/logger/index.cjs +0 -521
  107. package/dist/logger/index.cjs.map +0 -1
  108. package/dist/logger/index.d.cts +0 -281
  109. package/dist/orm/index.cjs +0 -2986
  110. package/dist/orm/index.cjs.map +0 -1
  111. package/dist/orm/index.d.cts +0 -2213
  112. package/dist/queue/index.cjs +0 -1044
  113. package/dist/queue/index.cjs.map +0 -1
  114. package/dist/queue/index.d.cts +0 -1265
  115. package/dist/queue-redis/index.cjs +0 -873
  116. package/dist/queue-redis/index.cjs.map +0 -1
  117. package/dist/queue-redis/index.d.cts +0 -82
  118. package/dist/redis/index.cjs +0 -153
  119. package/dist/redis/index.cjs.map +0 -1
  120. package/dist/redis/index.d.cts +0 -82
  121. package/dist/retry/index.cjs +0 -146
  122. package/dist/retry/index.cjs.map +0 -1
  123. package/dist/retry/index.d.cts +0 -172
  124. package/dist/router/index.cjs +0 -111
  125. package/dist/router/index.cjs.map +0 -1
  126. package/dist/router/index.d.cts +0 -46
  127. package/dist/scheduler/index.cjs +0 -576
  128. package/dist/scheduler/index.cjs.map +0 -1
  129. package/dist/scheduler/index.d.cts +0 -145
  130. package/dist/security/index.cjs +0 -2402
  131. package/dist/security/index.cjs.map +0 -1
  132. package/dist/security/index.d.cts +0 -598
  133. package/dist/server/index.cjs +0 -1680
  134. package/dist/server/index.cjs.map +0 -1
  135. package/dist/server/index.d.cts +0 -810
  136. package/dist/server-auth/index.cjs +0 -3146
  137. package/dist/server-auth/index.cjs.map +0 -1
  138. package/dist/server-auth/index.d.cts +0 -1164
  139. package/dist/server-cache/index.cjs +0 -252
  140. package/dist/server-cache/index.cjs.map +0 -1
  141. package/dist/server-cache/index.d.cts +0 -164
  142. package/dist/server-compress/index.cjs +0 -141
  143. package/dist/server-compress/index.cjs.map +0 -1
  144. package/dist/server-compress/index.d.cts +0 -38
  145. package/dist/server-cookies/index.cjs +0 -234
  146. package/dist/server-cookies/index.cjs.map +0 -1
  147. package/dist/server-cookies/index.d.cts +0 -144
  148. package/dist/server-cors/index.cjs +0 -201
  149. package/dist/server-cors/index.cjs.map +0 -1
  150. package/dist/server-cors/index.d.cts +0 -140
  151. package/dist/server-health/index.cjs +0 -62
  152. package/dist/server-health/index.cjs.map +0 -1
  153. package/dist/server-health/index.d.cts +0 -58
  154. package/dist/server-helmet/index.cjs +0 -131
  155. package/dist/server-helmet/index.cjs.map +0 -1
  156. package/dist/server-helmet/index.d.cts +0 -97
  157. package/dist/server-links/index.cjs +0 -992
  158. package/dist/server-links/index.cjs.map +0 -1
  159. package/dist/server-links/index.d.cts +0 -513
  160. package/dist/server-metrics/index.cjs +0 -4535
  161. package/dist/server-metrics/index.cjs.map +0 -1
  162. package/dist/server-metrics/index.d.cts +0 -35
  163. package/dist/server-multipart/index.cjs +0 -237
  164. package/dist/server-multipart/index.cjs.map +0 -1
  165. package/dist/server-multipart/index.d.cts +0 -50
  166. package/dist/server-proxy/index.cjs +0 -186
  167. package/dist/server-proxy/index.cjs.map +0 -1
  168. package/dist/server-proxy/index.d.cts +0 -234
  169. package/dist/server-rate-limit/index.cjs +0 -241
  170. package/dist/server-rate-limit/index.cjs.map +0 -1
  171. package/dist/server-rate-limit/index.d.cts +0 -183
  172. package/dist/server-security/index.cjs +0 -316
  173. package/dist/server-security/index.cjs.map +0 -1
  174. package/dist/server-security/index.d.cts +0 -173
  175. package/dist/server-static/index.cjs +0 -170
  176. package/dist/server-static/index.cjs.map +0 -1
  177. package/dist/server-static/index.d.cts +0 -121
  178. package/dist/server-swagger/index.cjs +0 -1021
  179. package/dist/server-swagger/index.cjs.map +0 -1
  180. package/dist/server-swagger/index.d.cts +0 -382
  181. package/dist/sms/index.cjs +0 -221
  182. package/dist/sms/index.cjs.map +0 -1
  183. package/dist/sms/index.d.cts +0 -130
  184. package/dist/thread/index.cjs +0 -350
  185. package/dist/thread/index.cjs.map +0 -1
  186. package/dist/thread/index.d.cts +0 -260
  187. package/dist/topic/index.cjs +0 -282
  188. package/dist/topic/index.cjs.map +0 -1
  189. package/dist/topic/index.d.cts +0 -523
  190. package/dist/topic-redis/index.cjs +0 -71
  191. package/dist/topic-redis/index.cjs.map +0 -1
  192. package/dist/topic-redis/index.d.cts +0 -42
  193. package/dist/vite/index.cjs +0 -1077
  194. package/dist/vite/index.cjs.map +0 -1
  195. package/dist/vite/index.d.cts +0 -542
  196. package/dist/websocket/index.cjs +0 -1117
  197. package/dist/websocket/index.cjs.map +0 -1
  198. package/dist/websocket/index.d.cts +0 -861
@@ -1,1265 +0,0 @@
1
- import * as alepha1 from "alepha";
2
- import { Alepha, Descriptor, KIND, Service, Static, TSchema } from "alepha";
3
- import * as alepha_logger1 from "alepha/logger";
4
- import { DateTimeProvider } from "alepha/datetime";
5
-
6
- //#region src/queue/interfaces/QueueJob.d.ts
7
- /**
8
- * Represents a job in the queue system.
9
- *
10
- * Jobs are the core unit of work in the queue. They contain the payload to be processed,
11
- * options for controlling behavior (priority, retries, delays), and state tracking.
12
- */
13
- interface QueueJob<T = unknown> {
14
- /**
15
- * Unique identifier for the job.
16
- */
17
- id: string;
18
- /**
19
- * The queue this job belongs to.
20
- */
21
- queue: string;
22
- /**
23
- * The actual data to be processed.
24
- */
25
- payload: T;
26
- /**
27
- * Job configuration options.
28
- */
29
- options: QueueJobOptions;
30
- /**
31
- * Current state of the job.
32
- */
33
- state: QueueJobState;
34
- }
35
- /**
36
- * Options for configuring job behavior.
37
- */
38
- interface QueueJobOptions {
39
- /**
40
- * Job priority. Lower values = higher priority.
41
- * Jobs with lower priority values are processed first.
42
- *
43
- * @default 0
44
- */
45
- priority?: number;
46
- /**
47
- * Delay in milliseconds before the job becomes available for processing.
48
- * The job will be in "delayed" status until the delay expires.
49
- *
50
- * @default 0 (no delay)
51
- */
52
- delay?: number;
53
- /**
54
- * Maximum number of processing attempts before the job is marked as failed.
55
- * Includes the initial attempt.
56
- *
57
- * @default 1 (no retries)
58
- */
59
- maxAttempts?: number;
60
- /**
61
- * Backoff configuration for retries.
62
- * Controls the delay between retry attempts.
63
- */
64
- backoff?: QueueJobBackoff;
65
- /**
66
- * Maximum time in milliseconds a job can be processed before it's considered stalled.
67
- * If the worker doesn't complete or extend the lock within this time, the job
68
- * can be picked up by another worker.
69
- *
70
- * @default 30000 (30 seconds)
71
- */
72
- lockDuration?: number;
73
- /**
74
- * Automatically remove jobs when they complete successfully.
75
- * - `true`: Remove immediately after completion
76
- * - `false`: Keep in completed list (default)
77
- * - `number`: Keep this many most recent completed jobs, remove older ones
78
- *
79
- * @default false
80
- */
81
- removeOnComplete?: boolean | number;
82
- /**
83
- * Automatically remove jobs when they fail permanently (after all retries exhausted).
84
- * - `true`: Remove immediately after failure
85
- * - `false`: Keep in failed list (default)
86
- * - `number`: Keep this many most recent failed jobs, remove older ones
87
- *
88
- * @default false
89
- */
90
- removeOnFail?: boolean | number;
91
- }
92
- /**
93
- * Backoff configuration for job retries.
94
- */
95
- interface QueueJobBackoff {
96
- /**
97
- * Type of backoff strategy.
98
- * - "fixed": Same delay between all retries
99
- * - "exponential": Delay doubles with each retry
100
- */
101
- type: "fixed" | "exponential";
102
- /**
103
- * Base delay in milliseconds.
104
- * - For "fixed": The delay between all retries
105
- * - For "exponential": Initial delay, then multiplied by 2^attempt
106
- *
107
- * @default 1000
108
- */
109
- delay?: number;
110
- /**
111
- * Maximum delay in milliseconds (for exponential backoff).
112
- *
113
- * @default 30000
114
- */
115
- maxDelay?: number;
116
- }
117
- /**
118
- * Current state of a job.
119
- */
120
- interface QueueJobState {
121
- /**
122
- * Current status of the job.
123
- */
124
- status: QueueJobStatus;
125
- /**
126
- * Number of processing attempts made (starts at 0, incremented before each attempt).
127
- */
128
- attempts: number;
129
- /**
130
- * Worker ID that currently holds the lock on this job.
131
- * Only set when status is "active".
132
- */
133
- lockedBy?: string;
134
- /**
135
- * Timestamp (ms) when the current lock expires.
136
- * If processing isn't completed by this time, the job is considered stalled.
137
- */
138
- lockedUntil?: number;
139
- /**
140
- * Error message from the last failed attempt.
141
- */
142
- error?: string;
143
- /**
144
- * Stack trace from the last failed attempt.
145
- */
146
- stackTrace?: string;
147
- /**
148
- * Result returned by the handler on successful completion.
149
- */
150
- result?: unknown;
151
- /**
152
- * Timestamp (ms) when the job was created.
153
- */
154
- createdAt: number;
155
- /**
156
- * Timestamp (ms) when the job should become available for processing.
157
- * Used for delayed jobs.
158
- */
159
- availableAt?: number;
160
- /**
161
- * Timestamp (ms) when the job started processing (last attempt).
162
- */
163
- processedAt?: number;
164
- /**
165
- * Timestamp (ms) when the job completed successfully.
166
- */
167
- completedAt?: number;
168
- /**
169
- * Timestamp (ms) when the job failed (after all retries exhausted).
170
- */
171
- failedAt?: number;
172
- }
173
- /**
174
- * Possible statuses for a job.
175
- */
176
- type QueueJobStatus = "waiting" | "delayed" | "active" | "completed" | "failed";
177
- /**
178
- * Job counts by status.
179
- */
180
- type QueueJobCounts = Record<QueueJobStatus, number>;
181
- /**
182
- * Options for adding a job to the queue.
183
- * Simplified version of QueueJobOptions for the public API.
184
- */
185
- interface QueueAddJobOptions {
186
- /**
187
- * Job priority. Lower values = higher priority.
188
- * @default 0
189
- */
190
- priority?: number;
191
- /**
192
- * Delay in milliseconds before processing.
193
- * @default 0
194
- */
195
- delay?: number;
196
- }
197
- /**
198
- * Result of acquiring a job for processing.
199
- */
200
- interface QueueAcquiredJob<T = unknown> {
201
- /**
202
- * The queue the job was acquired from.
203
- */
204
- queue: string;
205
- /**
206
- * The acquired job.
207
- */
208
- job: QueueJob<T>;
209
- }
210
- /**
211
- * Options for cleaning old jobs.
212
- */
213
- interface QueueCleanOptions {
214
- /**
215
- * Maximum age in milliseconds. Jobs older than this will be removed.
216
- */
217
- maxAge?: number;
218
- /**
219
- * Maximum number of jobs to keep. Oldest jobs beyond this count are removed.
220
- */
221
- maxCount?: number;
222
- }
223
- /**
224
- * Options for querying jobs.
225
- */
226
- interface QueueGetJobsOptions {
227
- /**
228
- * Maximum number of jobs to return.
229
- * @default 100
230
- */
231
- limit?: number;
232
- /**
233
- * Number of jobs to skip (for pagination).
234
- * @default 0
235
- */
236
- offset?: number;
237
- }
238
- /**
239
- * Event types emitted by the queue system.
240
- */
241
- type QueueEventType = "waiting" | "active" | "completed" | "failed" | "stalled" | "progress" | "retrying" | "removed";
242
- /**
243
- * Base interface for all queue events.
244
- */
245
- interface QueueEventBase {
246
- /**
247
- * The queue name where the event occurred.
248
- */
249
- queue: string;
250
- /**
251
- * The job ID associated with the event.
252
- */
253
- jobId: string;
254
- /**
255
- * Timestamp when the event occurred.
256
- */
257
- timestamp: number;
258
- }
259
- /**
260
- * Event emitted when a job is added to the waiting queue.
261
- */
262
- interface QueueEventWaiting extends QueueEventBase {
263
- type: "waiting";
264
- /**
265
- * The job that was added.
266
- */
267
- job: QueueJob;
268
- }
269
- /**
270
- * Event emitted when a job starts processing.
271
- */
272
- interface QueueEventActive extends QueueEventBase {
273
- type: "active";
274
- /**
275
- * The worker ID that acquired the job.
276
- */
277
- workerId: string;
278
- /**
279
- * Current attempt number.
280
- */
281
- attempt: number;
282
- }
283
- /**
284
- * Event emitted when a job completes successfully.
285
- */
286
- interface QueueEventCompleted extends QueueEventBase {
287
- type: "completed";
288
- /**
289
- * The result returned by the job handler.
290
- */
291
- result?: unknown;
292
- /**
293
- * Total processing time in milliseconds.
294
- */
295
- duration: number;
296
- }
297
- /**
298
- * Event emitted when a job fails permanently (all retries exhausted).
299
- */
300
- interface QueueEventFailed extends QueueEventBase {
301
- type: "failed";
302
- /**
303
- * The error message.
304
- */
305
- error: string;
306
- /**
307
- * The stack trace if available.
308
- */
309
- stackTrace?: string;
310
- /**
311
- * Number of attempts made.
312
- */
313
- attempts: number;
314
- }
315
- /**
316
- * Event emitted when a job is detected as stalled.
317
- */
318
- interface QueueEventStalled extends QueueEventBase {
319
- type: "stalled";
320
- /**
321
- * The worker ID that was processing the job.
322
- */
323
- workerId?: string;
324
- /**
325
- * Whether the job will be retried.
326
- */
327
- willRetry: boolean;
328
- }
329
- /**
330
- * Event emitted when a job reports progress.
331
- */
332
- interface QueueEventProgress extends QueueEventBase {
333
- type: "progress";
334
- /**
335
- * Progress data (0-100 or custom object).
336
- */
337
- progress: number | Record<string, unknown>;
338
- }
339
- /**
340
- * Event emitted when a job is being retried after a failure.
341
- */
342
- interface QueueEventRetrying extends QueueEventBase {
343
- type: "retrying";
344
- /**
345
- * The error from the previous attempt.
346
- */
347
- error: string;
348
- /**
349
- * The attempt number that will be made.
350
- */
351
- attempt: number;
352
- /**
353
- * Delay in milliseconds before retry.
354
- */
355
- delay: number;
356
- }
357
- /**
358
- * Event emitted when a job is removed from the queue.
359
- */
360
- interface QueueEventRemoved extends QueueEventBase {
361
- type: "removed";
362
- /**
363
- * The status the job was in when removed.
364
- */
365
- previousStatus: QueueJobStatus;
366
- }
367
- /**
368
- * Union type of all queue events.
369
- */
370
- type QueueEvent = QueueEventWaiting | QueueEventActive | QueueEventCompleted | QueueEventFailed | QueueEventStalled | QueueEventProgress | QueueEventRetrying | QueueEventRemoved;
371
- /**
372
- * Handler function for queue events.
373
- */
374
- type QueueEventHandler<T extends QueueEvent = QueueEvent> = (event: T) => void | Promise<void>;
375
- /**
376
- * Map of event types to their corresponding event interfaces.
377
- */
378
- interface QueueEventMap {
379
- waiting: QueueEventWaiting;
380
- active: QueueEventActive;
381
- completed: QueueEventCompleted;
382
- failed: QueueEventFailed;
383
- stalled: QueueEventStalled;
384
- progress: QueueEventProgress;
385
- retrying: QueueEventRetrying;
386
- removed: QueueEventRemoved;
387
- }
388
- //#endregion
389
- //#region src/queue/providers/QueueProvider.d.ts
390
- /**
391
- * Queue provider interface supporting both simple message-based and advanced job-based operations.
392
- *
393
- * The simple API (push/pop/popBlocking) is for basic fire-and-forget messaging.
394
- * The job API provides crash recovery, retries, delayed jobs, priorities, and job history.
395
- */
396
- declare abstract class QueueProvider {
397
- protected eventHandlers: Map<QueueEventType | "*", Set<QueueEventHandler<QueueEvent>>>;
398
- /**
399
- * Subscribe to queue events.
400
- *
401
- * @param event Event type to listen for, or "*" for all events.
402
- * @param handler Handler function to call when event occurs.
403
- * @returns Unsubscribe function.
404
- *
405
- * @example
406
- * ```ts
407
- * // Listen for completed events
408
- * const unsubscribe = provider.on("completed", (event) => {
409
- * console.log(`Job ${event.jobId} completed in ${event.duration}ms`);
410
- * });
411
- *
412
- * // Listen for all events
413
- * provider.on("*", (event) => {
414
- * console.log(`Event: ${event.type} for job ${event.jobId}`);
415
- * });
416
- *
417
- * // Unsubscribe later
418
- * unsubscribe();
419
- * ```
420
- */
421
- on<T extends QueueEventType>(event: T, handler: QueueEventHandler<QueueEventMap[T]>): () => void;
422
- on(event: "*", handler: QueueEventHandler<QueueEvent>): () => void;
423
- /**
424
- * Emit a queue event to all registered handlers.
425
- *
426
- * @param event The event to emit.
427
- */
428
- protected emit(event: QueueEvent): Promise<void>;
429
- /**
430
- * Push a message to the queue.
431
- *
432
- * @param queue Name of the queue to push the message to.
433
- * @param message String message to be pushed to the queue.
434
- */
435
- abstract push(queue: string, message: string): Promise<void>;
436
- /**
437
- * Pop a message from the queue.
438
- *
439
- * @param queue Name of the queue to pop the message from.
440
- * @returns The message popped or `undefined` if the queue is empty.
441
- */
442
- abstract pop(queue: string): Promise<string | undefined>;
443
- /**
444
- * Pop a message from one of the specified queues, blocking until available or timeout.
445
- *
446
- * @param queues Array of queue names to listen on.
447
- * @param timeoutSeconds Maximum time to wait in seconds.
448
- * @returns Object with queue name and message, or `undefined` if timeout expired.
449
- */
450
- abstract popBlocking(queues: string[], timeoutSeconds: number): Promise<{
451
- queue: string;
452
- message: string;
453
- } | undefined>;
454
- /**
455
- * Add a job to the queue.
456
- *
457
- * @param queue Queue name.
458
- * @param payload Job data to process.
459
- * @param options Job options (priority, delay, retries, etc.).
460
- * @returns The created job.
461
- */
462
- abstract addJob<T>(queue: string, payload: T, options?: QueueJobOptions): Promise<QueueJob<T>>;
463
- /**
464
- * Acquire the next available job for processing.
465
- *
466
- * This atomically:
467
- * 1. Finds the highest priority job that is ready for processing
468
- * 2. Moves it to "active" status
469
- * 3. Sets a lock with the worker ID
470
- *
471
- * @param queues Queue names to check (in order of preference).
472
- * @param workerId Unique identifier for the worker acquiring the job.
473
- * @param timeoutSeconds Maximum time to wait for a job.
474
- * @returns The acquired job or undefined if timeout.
475
- */
476
- abstract acquireJob(queues: string[], workerId: string, timeoutSeconds: number): Promise<QueueAcquiredJob | undefined>;
477
- /**
478
- * Mark a job as completed successfully.
479
- *
480
- * @param queue Queue name.
481
- * @param jobId Job ID.
482
- * @param result Optional result data from processing.
483
- */
484
- abstract completeJob(queue: string, jobId: string, result?: unknown): Promise<void>;
485
- /**
486
- * Mark a job as failed.
487
- *
488
- * If the job has remaining retry attempts, it will be moved to "delayed" status
489
- * (for backoff) or "waiting" status. Otherwise, it will be moved to "failed" status.
490
- *
491
- * @param queue Queue name.
492
- * @param jobId Job ID.
493
- * @param error Error message.
494
- * @param stackTrace Optional stack trace.
495
- */
496
- abstract failJob(queue: string, jobId: string, error: string, stackTrace?: string): Promise<void>;
497
- /**
498
- * Extend the lock on an active job.
499
- *
500
- * Workers should call this periodically while processing long-running jobs
501
- * to prevent them from being considered stalled.
502
- *
503
- * @param queue Queue name.
504
- * @param jobId Job ID.
505
- * @param workerId Worker ID (must match the lock holder).
506
- * @returns True if lock was extended, false if job is not locked by this worker.
507
- */
508
- abstract renewJobLock(queue: string, jobId: string, workerId: string): Promise<boolean>;
509
- /**
510
- * Get a job by ID.
511
- *
512
- * @param queue Queue name.
513
- * @param jobId Job ID.
514
- * @returns The job or undefined if not found.
515
- */
516
- abstract getJob(queue: string, jobId: string): Promise<QueueJob | undefined>;
517
- /**
518
- * Get jobs by status.
519
- *
520
- * @param queue Queue name.
521
- * @param status Job status to filter by.
522
- * @param options Pagination options.
523
- * @returns Array of jobs.
524
- */
525
- abstract getJobs(queue: string, status: QueueJobStatus, options?: QueueGetJobsOptions): Promise<QueueJob[]>;
526
- /**
527
- * Get job counts by status.
528
- *
529
- * @param queue Queue name.
530
- * @returns Object with counts for each status.
531
- */
532
- abstract getJobCounts(queue: string): Promise<QueueJobCounts>;
533
- /**
534
- * Promote delayed jobs that are ready for processing.
535
- *
536
- * Moves jobs from "delayed" to "waiting" status when their availableAt time has passed.
537
- *
538
- * @param queue Queue name.
539
- * @returns Number of jobs promoted.
540
- */
541
- abstract promoteDelayedJobs(queue: string): Promise<number>;
542
- /**
543
- * Recover stalled jobs.
544
- *
545
- * Finds jobs in "active" status whose locks have expired and either:
546
- * - Moves them back to "waiting" for retry (if attempts remaining)
547
- * - Moves them to "failed" (if no attempts remaining)
548
- *
549
- * @param queue Queue name.
550
- * @param stalledThresholdMs Jobs with expired locks older than this are considered stalled.
551
- * @returns Array of recovered job IDs.
552
- */
553
- abstract recoverStalledJobs(queue: string, stalledThresholdMs: number): Promise<string[]>;
554
- /**
555
- * Remove old completed or failed jobs.
556
- *
557
- * @param queue Queue name.
558
- * @param status Status to clean ("completed" or "failed").
559
- * @param options Cleaning options (maxAge, maxCount).
560
- * @returns Number of jobs removed.
561
- */
562
- abstract cleanJobs(queue: string, status: "completed" | "failed", options?: QueueCleanOptions): Promise<number>;
563
- /**
564
- * Remove a specific job.
565
- *
566
- * @param queue Queue name.
567
- * @param jobId Job ID.
568
- */
569
- abstract removeJob(queue: string, jobId: string): Promise<void>;
570
- /**
571
- * Cancel all pending waiters.
572
- *
573
- * This is called during shutdown to immediately release all blocking
574
- * acquireJob calls, preventing shutdown delays.
575
- */
576
- abstract cancelWaiters(): void;
577
- }
578
- //#endregion
579
- //#region src/queue/providers/MemoryQueueProvider.d.ts
580
- interface MessageWaiter {
581
- queues: Set<string>;
582
- resolve: (result: {
583
- queue: string;
584
- message: string;
585
- } | undefined) => void;
586
- timer: ReturnType<typeof setTimeout>;
587
- }
588
- interface JobWaiter {
589
- queues: Set<string>;
590
- workerId: string;
591
- resolve: (result: QueueAcquiredJob | undefined) => void;
592
- timer: ReturnType<typeof setTimeout>;
593
- }
594
- /**
595
- * In-memory queue provider with full job support.
596
- *
597
- * This provider stores all data in memory and is suitable for:
598
- * - Development and testing
599
- * - Single-instance applications
600
- * - Scenarios where job persistence across restarts is not required
601
- */
602
- declare class MemoryQueueProvider extends QueueProvider {
603
- protected readonly log: alepha_logger1.Logger;
604
- protected messageQueues: Record<string, string[]>;
605
- protected messageWaiters: Set<MessageWaiter>;
606
- protected jobs: Map<string, Map<string, QueueJob>>;
607
- protected waiting: Map<string, string[]>;
608
- protected delayed: Map<string, string[]>;
609
- protected active: Map<string, Set<string>>;
610
- protected completed: Map<string, string[]>;
611
- protected failed: Map<string, string[]>;
612
- protected jobWaiters: Set<JobWaiter>;
613
- protected jobIdCounter: number;
614
- push(queue: string, ...messages: string[]): Promise<void>;
615
- pop(queue: string): Promise<string | undefined>;
616
- popBlocking(queues: string[], timeoutSeconds: number): Promise<{
617
- queue: string;
618
- message: string;
619
- } | undefined>;
620
- protected findMessageWaiter(queue: string): MessageWaiter | undefined;
621
- protected removeMessageWaiter(waiter: MessageWaiter): void;
622
- protected generateJobId(): string;
623
- protected ensureQueueStructures(queue: string): void;
624
- addJob<T>(queue: string, payload: T, options?: QueueJobOptions): Promise<QueueJob<T>>;
625
- protected insertWaiting(queue: string, job: QueueJob): void;
626
- protected insertDelayed(queue: string, job: QueueJob): void;
627
- protected notifyJobWaiters(queue: string): void;
628
- protected removeJobWaiter(waiter: JobWaiter): void;
629
- protected tryAcquireJob(queues: string[], workerId: string): QueueAcquiredJob | undefined;
630
- acquireJob(queues: string[], workerId: string, timeoutSeconds: number): Promise<QueueAcquiredJob | undefined>;
631
- completeJob(queue: string, jobId: string, result?: unknown): Promise<void>;
632
- failJob(queue: string, jobId: string, error: string, stackTrace?: string): Promise<void>;
633
- protected calculateBackoff(job: QueueJob): number;
634
- renewJobLock(queue: string, jobId: string, workerId: string): Promise<boolean>;
635
- getJob(queue: string, jobId: string): Promise<QueueJob | undefined>;
636
- getJobs(queue: string, status: QueueJobStatus, options?: QueueGetJobsOptions): Promise<QueueJob[]>;
637
- getJobCounts(queue: string): Promise<QueueJobCounts>;
638
- promoteDelayedJobs(queue: string): Promise<number>;
639
- recoverStalledJobs(queue: string, stalledThresholdMs: number): Promise<string[]>;
640
- cleanJobs(queue: string, status: "completed" | "failed", options?: QueueCleanOptions): Promise<number>;
641
- removeJob(queue: string, jobId: string): Promise<void>;
642
- cancelWaiters(): void;
643
- }
644
- //#endregion
645
- //#region src/queue/descriptors/$queue.d.ts
646
- /**
647
- * Creates a queue descriptor for asynchronous message processing with background workers.
648
- *
649
- * The $queue descriptor enables powerful asynchronous communication patterns in your application.
650
- * It provides type-safe message queuing with automatic worker processing, making it perfect for
651
- * decoupling components and handling background tasks efficiently.
652
- *
653
- * **Background Processing**
654
- * - Automatic worker threads for non-blocking message processing
655
- * - Built-in retry mechanisms and error handling
656
- * - Dead letter queues for failed message handling
657
- * - Graceful shutdown and worker lifecycle management
658
- *
659
- * **Type Safety**
660
- * - Full TypeScript support with schema validation using TypeBox
661
- * - Type-safe message payloads with automatic inference
662
- * - Runtime validation of all queued messages
663
- * - Compile-time errors for invalid message structures
664
- *
665
- * **Storage Flexibility**
666
- * - Memory provider for development and testing
667
- * - Redis provider for production scalability and persistence
668
- * - Custom provider support for specialized backends
669
- * - Automatic failover and connection pooling
670
- *
671
- * **Performance & Scalability**
672
- * - Batch processing support for high-throughput scenarios
673
- * - Horizontal scaling with distributed queue backends
674
- * - Configurable concurrency and worker pools
675
- * - Efficient serialization and message routing
676
- *
677
- * **Reliability**
678
- * - Message persistence across application restarts
679
- * - Automatic retry with exponential backoff
680
- * - Dead letter handling for permanently failed messages
681
- * - Comprehensive logging and monitoring integration
682
- *
683
- * @example Basic notification queue
684
- * ```typescript
685
- * const emailQueue = $queue({
686
- * name: "email-notifications",
687
- * schema: t.object({
688
- * to: t.text(),
689
- * subject: t.text(),
690
- * body: t.text(),
691
- * priority: t.optional(t.enum(["high", "normal"]))
692
- * }),
693
- * handler: async (message) => {
694
- * await emailService.send(message.payload);
695
- * console.log(`Email sent to ${message.payload.to}`);
696
- * }
697
- * });
698
- *
699
- * // Push messages for background processing
700
- * await emailQueue.push({
701
- * to: "user@example.com",
702
- * subject: "Welcome!",
703
- * body: "Welcome to our platform",
704
- * priority: "high"
705
- * });
706
- * ```
707
- *
708
- * @example Batch processing with Redis
709
- * ```typescript
710
- * const imageQueue = $queue({
711
- * name: "image-processing",
712
- * provider: RedisQueueProvider,
713
- * schema: t.object({
714
- * imageId: t.text(),
715
- * operations: t.array(t.enum(["resize", "compress", "thumbnail"]))
716
- * }),
717
- * handler: async (message) => {
718
- * for (const op of message.payload.operations) {
719
- * await processImage(message.payload.imageId, op);
720
- * }
721
- * }
722
- * });
723
- *
724
- * // Batch processing multiple images
725
- * await imageQueue.push(
726
- * { imageId: "img1", operations: ["resize", "thumbnail"] },
727
- * { imageId: "img2", operations: ["compress"] },
728
- * { imageId: "img3", operations: ["resize", "compress", "thumbnail"] }
729
- * );
730
- * ```
731
- *
732
- * @example Development with memory provider
733
- * ```typescript
734
- * const taskQueue = $queue({
735
- * name: "dev-tasks",
736
- * provider: "memory",
737
- * schema: t.object({
738
- * taskType: t.enum(["cleanup", "backup", "report"]),
739
- * data: t.record(t.text(), t.any())
740
- * }),
741
- * handler: async (message) => {
742
- * switch (message.payload.taskType) {
743
- * case "cleanup":
744
- * await performCleanup(message.payload.data);
745
- * break;
746
- * case "backup":
747
- * await createBackup(message.payload.data);
748
- * break;
749
- * case "report":
750
- * await generateReport(message.payload.data);
751
- * break;
752
- * }
753
- * }
754
- * });
755
- * ```
756
- */
757
- declare const $queue: {
758
- <T extends TSchema>(options: QueueDescriptorOptions<T>): QueueDescriptor<T>;
759
- [KIND]: typeof QueueDescriptor;
760
- };
761
- interface QueueDescriptorOptions<T extends TSchema> {
762
- /**
763
- * Unique name for the queue.
764
- *
765
- * This name is used for:
766
- * - Queue identification across the system
767
- * - Storage backend key generation
768
- * - Logging and monitoring
769
- * - Worker assignment and routing
770
- *
771
- * If not provided, defaults to the property key where the queue is declared.
772
- *
773
- * @example "email-notifications"
774
- * @example "image-processing"
775
- * @example "order-fulfillment"
776
- */
777
- name?: string;
778
- /**
779
- * Human-readable description of the queue's purpose.
780
- *
781
- * Used for:
782
- * - Documentation generation
783
- * - Monitoring dashboards
784
- * - Development team communication
785
- * - Queue management interfaces
786
- *
787
- * @example "Process user registration emails and welcome sequences"
788
- * @example "Handle image uploads, resizing, and thumbnail generation"
789
- * @example "Manage order processing, payment, and shipping workflows"
790
- */
791
- description?: string;
792
- /**
793
- * Queue storage provider configuration.
794
- *
795
- * Options:
796
- * - **"memory"**: In-memory queue (default for development, lost on restart)
797
- * - **Service<QueueProvider>**: Custom provider class (e.g., RedisQueueProvider)
798
- * - **undefined**: Uses the default queue provider from dependency injection
799
- *
800
- * **Provider Selection Guidelines**:
801
- * - Development: Use "memory" for fast, simple testing
802
- * - Production: Use Redis or database-backed providers for persistence
803
- * - High-throughput: Use specialized providers with connection pooling
804
- * - Distributed systems: Use Redis or message brokers for scalability
805
- *
806
- * @default Uses injected QueueProvider
807
- * @example "memory"
808
- * @example RedisQueueProvider
809
- * @example DatabaseQueueProvider
810
- */
811
- provider?: "memory" | Service<QueueProvider>;
812
- /**
813
- * TypeBox schema defining the structure of messages in this queue.
814
- *
815
- * This schema:
816
- * - Validates all messages pushed to the queue
817
- * - Provides full TypeScript type inference
818
- * - Ensures type safety between producers and consumers
819
- * - Enables automatic serialization/deserialization
820
- *
821
- * **Schema Design Best Practices**:
822
- * - Keep schemas simple and focused on the specific task
823
- * - Use optional fields for data that might not always be available
824
- * - Include version fields for schema evolution
825
- * - Use union types for different message types in the same queue
826
- *
827
- * @example
828
- * ```ts
829
- * t.object({
830
- * userId: t.text(),
831
- * action: t.enum(["create", "update"]),
832
- * data: t.record(t.text(), t.any()),
833
- * timestamp: t.optional(t.number())
834
- * })
835
- * ```
836
- */
837
- schema: T;
838
- /**
839
- * Message handler function that processes queue messages.
840
- *
841
- * This function:
842
- * - Runs in background worker threads for non-blocking processing
843
- * - Receives type-safe message payloads based on the schema
844
- * - Should be idempotent to handle potential retries
845
- * - Can throw errors to trigger retry mechanisms
846
- * - Has access to the full Alepha dependency injection container
847
- *
848
- * **Handler Best Practices**:
849
- * - Keep handlers focused on a single responsibility
850
- * - Use proper error handling and logging
851
- * - Make operations idempotent when possible
852
- * - Validate critical business logic within handlers
853
- * - Consider using transactions for data consistency
854
- *
855
- * @param message - The queue message with validated payload
856
- * @returns Promise that resolves when processing is complete
857
- *
858
- * @example
859
- * ```ts
860
- * handler: async (message) => {
861
- * const { userId, email, template } = message.payload;
862
- *
863
- * try {
864
- * await this.emailService.send({
865
- * to: email,
866
- * template,
867
- * data: { userId }
868
- * });
869
- *
870
- * await this.userService.markEmailSent(userId, template);
871
- * } catch (error) {
872
- * // Log error and let the queue system handle retries
873
- * this.logger.error(`Failed to send email to ${email}`, error);
874
- * throw error;
875
- * }
876
- * }
877
- * ```
878
- */
879
- handler?: (message: QueueMessage<T>) => Promise<void>;
880
- /**
881
- * Maximum number of processing attempts before the job is marked as failed.
882
- * Includes the initial attempt.
883
- *
884
- * Set this to enable automatic retries on failure.
885
- *
886
- * @default 1 (no retries)
887
- * @example 3 // Allows 2 retries after initial failure
888
- */
889
- maxAttempts?: number;
890
- /**
891
- * Backoff configuration for retries.
892
- * Controls the delay between retry attempts.
893
- *
894
- * @example
895
- * ```ts
896
- * backoff: {
897
- * type: "exponential",
898
- * delay: 1000, // Initial delay: 1 second
899
- * maxDelay: 60000 // Maximum delay: 1 minute
900
- * }
901
- * ```
902
- */
903
- backoff?: QueueJobBackoff;
904
- /**
905
- * Maximum time in milliseconds a job can be processed before it's considered stalled.
906
- * If the worker doesn't complete or extend the lock within this time, the job
907
- * can be picked up by another worker.
908
- *
909
- * Increase this for long-running jobs.
910
- *
911
- * @default 30000 (30 seconds)
912
- */
913
- lockDuration?: number;
914
- /**
915
- * Automatically remove jobs when they complete successfully.
916
- * - `true`: Remove immediately after completion
917
- * - `false`: Keep in completed list (default)
918
- * - `number`: Keep this many most recent completed jobs, remove older ones
919
- *
920
- * @default false
921
- * @example
922
- * ```ts
923
- * // Remove immediately after completion
924
- * removeOnComplete: true
925
- *
926
- * // Keep only the last 100 completed jobs
927
- * removeOnComplete: 100
928
- * ```
929
- */
930
- removeOnComplete?: boolean | number;
931
- /**
932
- * Automatically remove jobs when they fail permanently (after all retries exhausted).
933
- * - `true`: Remove immediately after failure
934
- * - `false`: Keep in failed list (default)
935
- * - `number`: Keep this many most recent failed jobs, remove older ones
936
- *
937
- * @default false
938
- * @example
939
- * ```ts
940
- * // Remove immediately after failure
941
- * removeOnFail: true
942
- *
943
- * // Keep only the last 50 failed jobs for debugging
944
- * removeOnFail: 50
945
- * ```
946
- */
947
- removeOnFail?: boolean | number;
948
- }
949
- declare class QueueDescriptor<T extends TSchema> extends Descriptor<QueueDescriptorOptions<T>> {
950
- protected readonly log: alepha_logger1.Logger;
951
- readonly provider: QueueProvider | MemoryQueueProvider;
952
- /**
953
- * Push one or more payloads to the queue for background processing.
954
- *
955
- * Jobs will be processed with crash recovery, retries (if configured),
956
- * and proper lifecycle management.
957
- *
958
- * @param payloads - One or more payloads to queue
959
- */
960
- push(...payloads: Array<Static<T>>): Promise<void>;
961
- /**
962
- * Push a payload to the queue with specific options.
963
- *
964
- * @param payload - The payload to queue
965
- * @param options - Job options (priority, delay)
966
- */
967
- push(payload: Static<T>, options: QueueAddJobOptions): Promise<void>;
968
- /**
969
- * Get default job options from descriptor configuration.
970
- */
971
- protected getDefaultJobOptions(): {
972
- maxAttempts: number | undefined;
973
- backoff: QueueJobBackoff | undefined;
974
- lockDuration: number | undefined;
975
- removeOnComplete: number | boolean | undefined;
976
- removeOnFail: number | boolean | undefined;
977
- };
978
- get name(): string;
979
- protected $provider(): QueueProvider | MemoryQueueProvider;
980
- }
981
- interface QueueMessageSchema {
982
- payload: TSchema;
983
- }
984
- interface QueueMessage<T extends TSchema> {
985
- payload: Static<T>;
986
- }
987
- //#endregion
988
- //#region src/queue/descriptors/$consumer.d.ts
989
- /**
990
- * Creates a consumer descriptor to process messages from a specific queue.
991
- *
992
- * Provides a dedicated message consumer that connects to a queue and processes messages
993
- * with custom handler logic, enabling scalable architectures where multiple consumers
994
- * can process messages from the same queue.
995
- *
996
- * **Key Features**
997
- * - Seamless integration with any $queue descriptor
998
- * - Full type safety inherited from queue schema
999
- * - Automatic worker management for background processing
1000
- * - Built-in error handling and retry mechanisms
1001
- * - Support for multiple consumers per queue for horizontal scaling
1002
- *
1003
- * **Common Use Cases**
1004
- * - Email sending and notification services
1005
- * - Image and media processing workers
1006
- * - Data synchronization and background jobs
1007
- *
1008
- * @example
1009
- * ```ts
1010
- * class EmailService {
1011
- * emailQueue = $queue({
1012
- * name: "emails",
1013
- * schema: t.object({
1014
- * to: t.text(),
1015
- * subject: t.text(),
1016
- * body: t.text()
1017
- * })
1018
- * });
1019
- *
1020
- * emailConsumer = $consumer({
1021
- * queue: this.emailQueue,
1022
- * handler: async (message) => {
1023
- * const { to, subject, body } = message.payload;
1024
- * await this.sendEmail(to, subject, body);
1025
- * }
1026
- * });
1027
- *
1028
- * async sendWelcomeEmail(userEmail: string) {
1029
- * await this.emailQueue.push({
1030
- * to: userEmail,
1031
- * subject: "Welcome!",
1032
- * body: "Thanks for joining."
1033
- * });
1034
- * }
1035
- * }
1036
- * ```
1037
- */
1038
- declare const $consumer: {
1039
- <T extends TSchema>(options: ConsumerDescriptorOptions<T>): ConsumerDescriptor<T>;
1040
- [KIND]: typeof ConsumerDescriptor;
1041
- };
1042
- interface ConsumerDescriptorOptions<T extends TSchema> {
1043
- /**
1044
- * The queue descriptor that this consumer will process messages from.
1045
- *
1046
- * This establishes the connection between the consumer and its source queue:
1047
- * - The consumer inherits the queue's message schema for type safety
1048
- * - Messages pushed to the queue will be automatically routed to this consumer
1049
- * - Multiple consumers can be attached to the same queue for parallel processing
1050
- * - The consumer will use the queue's provider and configuration settings
1051
- *
1052
- * **Queue Integration Benefits**:
1053
- * - Type safety: Consumer handler gets fully typed message payloads
1054
- * - Schema validation: Messages are validated before reaching the consumer
1055
- * - Error handling: Failed messages can be retried or moved to dead letter queues
1056
- * - Monitoring: Queue metrics include consumer processing statistics
1057
- *
1058
- * @example
1059
- * ```ts
1060
- * // First, define a queue
1061
- * emailQueue = $queue({
1062
- * name: "emails",
1063
- * schema: t.object({ to: t.text(), subject: t.text() })
1064
- * });
1065
- *
1066
- * // Then, create a consumer for that queue
1067
- * emailConsumer = $consumer({
1068
- * queue: this.emailQueue, // Reference the queue descriptor
1069
- * handler: async (message) => { } // process email
1070
- * });
1071
- * ```
1072
- */
1073
- queue: QueueDescriptor<T>;
1074
- /**
1075
- * Message handler function that processes individual messages from the queue.
1076
- *
1077
- * This function:
1078
- * - Receives fully typed and validated message payloads from the connected queue
1079
- * - Runs in the background worker system for non-blocking operation
1080
- * - Should implement the core business logic for processing this message type
1081
- * - Can throw errors to trigger the queue's retry mechanisms
1082
- * - Has access to the full Alepha dependency injection container
1083
- * - Should be idempotent to handle potential duplicate deliveries
1084
- *
1085
- * **Handler Design Guidelines**:
1086
- * - Keep handlers focused on a single responsibility
1087
- * - Use proper error handling and meaningful error messages
1088
- * - Log important processing steps for debugging and monitoring
1089
- * - Consider transaction boundaries for data consistency
1090
- * - Make operations idempotent when possible
1091
- * - Validate business rules within the handler logic
1092
- *
1093
- * **Error Handling Strategy**:
1094
- * - Throw errors for temporary failures that should be retried
1095
- * - Log and handle permanent failures gracefully
1096
- * - Use specific error types to control retry behavior
1097
- * - Consider implementing circuit breakers for external service calls
1098
- *
1099
- * @param message - The queue message containing the validated payload
1100
- * @param message.payload - The typed message data based on the queue's schema
1101
- * @returns Promise that resolves when processing is complete
1102
- *
1103
- * @example
1104
- * ```ts
1105
- * handler: async (message) => {
1106
- * const { userId, action, data } = message.payload;
1107
- *
1108
- * try {
1109
- * // Log processing start
1110
- * this.logger.info(`Processing ${action} for user ${userId}`);
1111
- *
1112
- * // Validate business rules
1113
- * if (!await this.userService.exists(userId)) {
1114
- * throw new Error(`User ${userId} not found`);
1115
- * }
1116
- *
1117
- * // Perform the main processing logic
1118
- * switch (action) {
1119
- * case "create":
1120
- * await this.processCreation(userId, data);
1121
- * break;
1122
- * case "update":
1123
- * await this.processUpdate(userId, data);
1124
- * break;
1125
- * default:
1126
- * throw new Error(`Unknown action: ${action}`);
1127
- * }
1128
- *
1129
- * // Log successful completion
1130
- * this.logger.info(`Successfully processed ${action} for user ${userId}`);
1131
- *
1132
- * } catch (error) {
1133
- * // Log error with context
1134
- * this.logger.error(`Failed to process ${action} for user ${userId}`, {
1135
- * error: error.message,
1136
- * userId,
1137
- * action,
1138
- * data
1139
- * });
1140
- *
1141
- * // Re-throw to trigger queue retry mechanism
1142
- * throw error;
1143
- * }
1144
- * }
1145
- * ```
1146
- */
1147
- handler: (message: {
1148
- payload: Static<T>;
1149
- }) => Promise<void>;
1150
- }
1151
- declare class ConsumerDescriptor<T extends TSchema> extends Descriptor<ConsumerDescriptorOptions<T>> {}
1152
- //#endregion
1153
- //#region src/queue/providers/WorkerProvider.d.ts
1154
- declare const envSchema: alepha1.TObject<{
1155
- /**
1156
- * The timeout in seconds for blocking job acquisition.
1157
- * Workers will check for shutdown after each timeout period.
1158
- */
1159
- QUEUE_WORKER_BLOCKING_TIMEOUT: alepha1.TInteger;
1160
- /**
1161
- * The number of workers to run concurrently. Defaults to 1.
1162
- * Useful only if you are doing a lot of I/O.
1163
- */
1164
- QUEUE_WORKER_CONCURRENCY: alepha1.TInteger;
1165
- /**
1166
- * Interval in milliseconds for renewing job locks during processing.
1167
- * Should be less than the job's lock duration.
1168
- */
1169
- QUEUE_WORKER_LOCK_RENEWAL_INTERVAL: alepha1.TInteger;
1170
- /**
1171
- * Interval in milliseconds for the scheduler to check delayed jobs and stalled jobs.
1172
- */
1173
- QUEUE_SCHEDULER_INTERVAL: alepha1.TInteger;
1174
- /**
1175
- * Threshold in milliseconds after lock expiration to consider a job stalled.
1176
- */
1177
- QUEUE_STALLED_THRESHOLD: alepha1.TInteger;
1178
- }>;
1179
- declare module "alepha" {
1180
- interface Env extends Partial<Static<typeof envSchema>> {}
1181
- }
1182
- declare class WorkerProvider {
1183
- protected readonly log: alepha_logger1.Logger;
1184
- protected readonly env: {
1185
- QUEUE_WORKER_BLOCKING_TIMEOUT: number;
1186
- QUEUE_WORKER_CONCURRENCY: number;
1187
- QUEUE_WORKER_LOCK_RENEWAL_INTERVAL: number;
1188
- QUEUE_SCHEDULER_INTERVAL: number;
1189
- QUEUE_STALLED_THRESHOLD: number;
1190
- };
1191
- protected readonly alepha: Alepha;
1192
- protected readonly queueProvider: QueueProvider;
1193
- protected readonly dateTime: DateTimeProvider;
1194
- protected workerPromises: Array<Promise<void>>;
1195
- protected workersRunning: number;
1196
- protected shouldStop: boolean;
1197
- protected consumers: Array<Consumer>;
1198
- protected consumersByProvider: Map<QueueProvider, Consumer[]>;
1199
- protected schedulerPromise: Promise<void> | undefined;
1200
- protected schedulerRunning: boolean;
1201
- protected abortController: AbortController | undefined;
1202
- protected workerId: string;
1203
- get isRunning(): boolean;
1204
- protected readonly start: alepha1.HookDescriptor<"start">;
1205
- /**
1206
- * Start the workers.
1207
- * Each worker acquires jobs and processes them with proper lifecycle management.
1208
- */
1209
- protected startWorkers(): void;
1210
- /**
1211
- * Start the scheduler for delayed job promotion and stalled job recovery.
1212
- */
1213
- protected startScheduler(): void;
1214
- /**
1215
- * Run one cycle of the scheduler.
1216
- * Promotes delayed jobs and recovers stalled jobs.
1217
- */
1218
- protected runSchedulerCycle(): Promise<void>;
1219
- protected readonly stop: alepha1.HookDescriptor<"stop">;
1220
- /**
1221
- * Acquire the next available job from any provider.
1222
- */
1223
- protected acquireNextJob(localWorkerId: string): Promise<AcquiredJobWithConsumer | undefined>;
1224
- /**
1225
- * Process a job with proper lifecycle management.
1226
- * - Starts a lock renewal interval
1227
- * - Calls the handler
1228
- * - Marks job as completed or failed
1229
- */
1230
- protected processJob({
1231
- acquired,
1232
- consumer,
1233
- provider
1234
- }: AcquiredJobWithConsumer, localWorkerId: string): Promise<void>;
1235
- /**
1236
- * Stop the workers and scheduler.
1237
- */
1238
- protected stopWorkers(): Promise<void>;
1239
- }
1240
- interface Consumer<T extends TSchema = TSchema> {
1241
- queue: QueueDescriptor<T>;
1242
- handler: (message: QueueMessage<T>) => Promise<void>;
1243
- }
1244
- interface AcquiredJobWithConsumer {
1245
- acquired: QueueAcquiredJob;
1246
- consumer: Consumer;
1247
- provider: QueueProvider;
1248
- }
1249
- //#endregion
1250
- //#region src/queue/index.d.ts
1251
- /**
1252
- * Provides asynchronous message queuing and processing capabilities through declarative queue descriptors.
1253
- *
1254
- * The queue module enables reliable background job processing and message passing using the `$queue` descriptor
1255
- * on class properties. It supports schema validation, automatic retries, and multiple queue backends for
1256
- * building scalable, decoupled applications with robust error handling.
1257
- *
1258
- * @see {@link $queue}
1259
- * @see {@link $consumer}
1260
- * @module alepha.queue
1261
- */
1262
- declare const AlephaQueue: alepha1.Service<alepha1.Module>;
1263
- //#endregion
1264
- export { $consumer, $queue, AcquiredJobWithConsumer, AlephaQueue, Consumer, ConsumerDescriptor, ConsumerDescriptorOptions, MemoryQueueProvider, type QueueAcquiredJob, type QueueAddJobOptions, type QueueCleanOptions, QueueDescriptor, QueueDescriptorOptions, type QueueEvent, type QueueEventActive, type QueueEventBase, type QueueEventCompleted, type QueueEventFailed, type QueueEventHandler, type QueueEventMap, type QueueEventProgress, type QueueEventRemoved, type QueueEventRetrying, type QueueEventStalled, type QueueEventType, type QueueEventWaiting, type QueueGetJobsOptions, type QueueJob, type QueueJobBackoff, type QueueJobCounts, type QueueJobOptions, type QueueJobState, type QueueJobStatus, QueueMessage, QueueMessageSchema, QueueProvider, WorkerProvider };
1265
- //# sourceMappingURL=index.d.cts.map