@contractspec/lib.jobs 1.57.0 → 1.59.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.
Files changed (92) hide show
  1. package/dist/contracts/index.d.ts +494 -500
  2. package/dist/contracts/index.d.ts.map +1 -1
  3. package/dist/contracts/index.js +298 -461
  4. package/dist/entities/index.d.ts +117 -122
  5. package/dist/entities/index.d.ts.map +1 -1
  6. package/dist/entities/index.js +170 -193
  7. package/dist/events.d.ts +297 -303
  8. package/dist/events.d.ts.map +1 -1
  9. package/dist/events.js +199 -351
  10. package/dist/handlers/gmail-sync-handler.d.ts +5 -9
  11. package/dist/handlers/gmail-sync-handler.d.ts.map +1 -1
  12. package/dist/handlers/gmail-sync-handler.js +8 -8
  13. package/dist/handlers/index.d.ts +5 -9
  14. package/dist/handlers/index.d.ts.map +1 -1
  15. package/dist/handlers/index.js +53 -10
  16. package/dist/handlers/ping-job.d.ts +6 -10
  17. package/dist/handlers/ping-job.d.ts.map +1 -1
  18. package/dist/handlers/ping-job.js +13 -12
  19. package/dist/handlers/storage-document-handler.d.ts +7 -11
  20. package/dist/handlers/storage-document-handler.d.ts.map +1 -1
  21. package/dist/handlers/storage-document-handler.js +15 -13
  22. package/dist/index.d.ts +7 -24
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1366 -64
  25. package/dist/jobs.capability.d.ts +2 -7
  26. package/dist/jobs.capability.d.ts.map +1 -1
  27. package/dist/jobs.capability.js +29 -33
  28. package/dist/jobs.feature.d.ts +1 -6
  29. package/dist/jobs.feature.d.ts.map +1 -1
  30. package/dist/jobs.feature.js +45 -108
  31. package/dist/node/contracts/index.js +318 -0
  32. package/dist/node/entities/index.js +174 -0
  33. package/dist/node/events.js +200 -0
  34. package/dist/node/handlers/gmail-sync-handler.js +9 -0
  35. package/dist/node/handlers/index.js +55 -0
  36. package/dist/node/handlers/ping-job.js +14 -0
  37. package/dist/node/handlers/storage-document-handler.js +16 -0
  38. package/dist/node/index.js +1368 -0
  39. package/dist/node/jobs.capability.js +28 -0
  40. package/dist/node/jobs.feature.js +46 -0
  41. package/dist/node/queue/gcp-cloud-tasks.js +66 -0
  42. package/dist/node/queue/gcp-pubsub.js +54 -0
  43. package/dist/node/queue/index.js +478 -0
  44. package/dist/node/queue/memory-queue.js +160 -0
  45. package/dist/node/queue/register-defined-job.js +15 -0
  46. package/dist/node/queue/scaleway-sqs-queue.js +206 -0
  47. package/dist/node/queue/types.js +10 -0
  48. package/dist/node/scheduler/index.js +117 -0
  49. package/dist/queue/gcp-cloud-tasks.d.ts +33 -36
  50. package/dist/queue/gcp-cloud-tasks.d.ts.map +1 -1
  51. package/dist/queue/gcp-cloud-tasks.js +65 -59
  52. package/dist/queue/gcp-pubsub.d.ts +18 -21
  53. package/dist/queue/gcp-pubsub.d.ts.map +1 -1
  54. package/dist/queue/gcp-pubsub.js +53 -45
  55. package/dist/queue/index.d.ts +6 -15
  56. package/dist/queue/index.d.ts.map +1 -1
  57. package/dist/queue/index.js +476 -20
  58. package/dist/queue/memory-queue.d.ts +25 -29
  59. package/dist/queue/memory-queue.d.ts.map +1 -1
  60. package/dist/queue/memory-queue.js +159 -138
  61. package/dist/queue/register-defined-job.d.ts +3 -7
  62. package/dist/queue/register-defined-job.d.ts.map +1 -1
  63. package/dist/queue/register-defined-job.js +14 -14
  64. package/dist/queue/scaleway-sqs-queue.d.ts +31 -35
  65. package/dist/queue/scaleway-sqs-queue.d.ts.map +1 -1
  66. package/dist/queue/scaleway-sqs-queue.js +205 -173
  67. package/dist/queue/types.d.ts +2 -8
  68. package/dist/queue/types.d.ts.map +1 -1
  69. package/dist/queue/types.js +11 -12
  70. package/dist/scheduler/index.d.ts +68 -72
  71. package/dist/scheduler/index.d.ts.map +1 -1
  72. package/dist/scheduler/index.js +113 -141
  73. package/package.json +176 -50
  74. package/dist/_virtual/_rolldown/runtime.js +0 -36
  75. package/dist/contracts/index.js.map +0 -1
  76. package/dist/entities/index.js.map +0 -1
  77. package/dist/events.js.map +0 -1
  78. package/dist/handlers/gmail-sync-handler.js.map +0 -1
  79. package/dist/handlers/index.js.map +0 -1
  80. package/dist/handlers/ping-job.js.map +0 -1
  81. package/dist/handlers/storage-document-handler.js.map +0 -1
  82. package/dist/index.js.map +0 -1
  83. package/dist/jobs.capability.js.map +0 -1
  84. package/dist/jobs.feature.js.map +0 -1
  85. package/dist/queue/gcp-cloud-tasks.js.map +0 -1
  86. package/dist/queue/gcp-pubsub.js.map +0 -1
  87. package/dist/queue/index.js.map +0 -1
  88. package/dist/queue/memory-queue.js.map +0 -1
  89. package/dist/queue/register-defined-job.js.map +0 -1
  90. package/dist/queue/scaleway-sqs-queue.js.map +0 -1
  91. package/dist/queue/types.js.map +0 -1
  92. package/dist/scheduler/index.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,67 +1,1369 @@
1
- import { __exportAll, __reExport } from "./_virtual/_rolldown/runtime.js";
2
- import { JobCancelledEvent, JobCompletedEvent, JobDeadLetteredEvent, JobEnqueuedEvent, JobEvents, JobFailedEvent, JobRetryingEvent, JobStartedEvent, ScheduledJobTriggeredEvent } from "./events.js";
3
- import { JobEntity, JobExecutionEntity, JobStatusEnum, ScheduledJobEntity, jobEntities, jobsSchemaContribution } from "./entities/index.js";
4
- import { MemoryJobQueue } from "./queue/memory-queue.js";
5
- import { ScalewaySqsJobQueue } from "./queue/scaleway-sqs-queue.js";
6
- import { GcpCloudTasksQueue } from "./queue/gcp-cloud-tasks.js";
7
- import { GcpPubSubQueue } from "./queue/gcp-pubsub.js";
8
- import { registerDefinedJob } from "./queue/register-defined-job.js";
9
- import { queue_exports } from "./queue/index.js";
10
- import { PING_JOB_TYPE, PingPayloadSchema, pingJob } from "./handlers/ping-job.js";
11
- import { createGmailSyncHandler } from "./handlers/gmail-sync-handler.js";
12
- import { createStorageDocumentHandler } from "./handlers/storage-document-handler.js";
13
- import { registerAllJobs } from "./handlers/index.js";
14
- import { JobScheduler, createScheduler, defineSchedule } from "./scheduler/index.js";
15
- import { CancelJobContract, CreateScheduledJobContract, EnqueueJobContract, GetJobContract, GetQueueStatsContract, JobModel, ListScheduledJobsContract, QueueStatsModel, ScheduledJobModel, ToggleScheduledJobContract } from "./contracts/index.js";
16
- import { JobsFeature } from "./jobs.feature.js";
1
+ // @bun
2
+ // src/contracts/index.ts
3
+ import { ScalarTypeEnum, defineSchemaModel } from "@contractspec/lib.schema";
4
+ import { defineCommand, defineQuery } from "@contractspec/lib.contracts";
5
+ var OWNERS = ["platform.jobs"];
6
+ var JobModel = defineSchemaModel({
7
+ name: "Job",
8
+ description: "Represents a background job",
9
+ fields: {
10
+ id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
11
+ type: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
12
+ version: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
13
+ payload: { type: ScalarTypeEnum.JSON(), isOptional: false },
14
+ status: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
15
+ priority: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
16
+ attempts: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
17
+ maxRetries: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
18
+ createdAt: { type: ScalarTypeEnum.DateTime(), isOptional: false },
19
+ updatedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false },
20
+ scheduledAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
21
+ startedAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
22
+ completedAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
23
+ lastError: { type: ScalarTypeEnum.String_unsecure(), isOptional: true }
24
+ }
25
+ });
26
+ var ScheduledJobModel = defineSchemaModel({
27
+ name: "ScheduledJob",
28
+ description: "Represents a scheduled/recurring job",
29
+ fields: {
30
+ id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
31
+ name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
32
+ description: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
33
+ cronExpression: {
34
+ type: ScalarTypeEnum.String_unsecure(),
35
+ isOptional: false
36
+ },
37
+ timezone: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
38
+ jobType: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
39
+ enabled: { type: ScalarTypeEnum.Boolean(), isOptional: false },
40
+ lastRunAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
41
+ nextRunAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
42
+ createdAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
43
+ }
44
+ });
45
+ var QueueStatsModel = defineSchemaModel({
46
+ name: "QueueStats",
47
+ description: "Job queue statistics",
48
+ fields: {
49
+ pending: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
50
+ running: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
51
+ completed: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
52
+ failed: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
53
+ deadLetter: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false }
54
+ }
55
+ });
56
+ var EnqueueJobInput = defineSchemaModel({
57
+ name: "EnqueueJobInput",
58
+ description: "Input for enqueuing a new job",
59
+ fields: {
60
+ type: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
61
+ payload: { type: ScalarTypeEnum.JSON(), isOptional: false },
62
+ delaySeconds: { type: ScalarTypeEnum.Int_unsecure(), isOptional: true },
63
+ dedupeKey: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
64
+ maxRetries: { type: ScalarTypeEnum.Int_unsecure(), isOptional: true },
65
+ priority: { type: ScalarTypeEnum.Int_unsecure(), isOptional: true },
66
+ timeoutMs: { type: ScalarTypeEnum.Int_unsecure(), isOptional: true }
67
+ }
68
+ });
69
+ var GetJobInput = defineSchemaModel({
70
+ name: "GetJobInput",
71
+ description: "Input for getting a job by ID",
72
+ fields: {
73
+ jobId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
74
+ }
75
+ });
76
+ var CancelJobInput = defineSchemaModel({
77
+ name: "CancelJobInput",
78
+ description: "Input for cancelling a job",
79
+ fields: {
80
+ jobId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
81
+ }
82
+ });
83
+ var CancelJobOutput = defineSchemaModel({
84
+ name: "CancelJobOutput",
85
+ description: "Output for cancel job operation",
86
+ fields: {
87
+ success: { type: ScalarTypeEnum.Boolean(), isOptional: false }
88
+ }
89
+ });
90
+ var CreateScheduledJobInput = defineSchemaModel({
91
+ name: "CreateScheduledJobInput",
92
+ description: "Input for creating a scheduled job",
93
+ fields: {
94
+ name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
95
+ description: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
96
+ cronExpression: {
97
+ type: ScalarTypeEnum.String_unsecure(),
98
+ isOptional: false
99
+ },
100
+ timezone: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
101
+ jobType: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
102
+ payload: { type: ScalarTypeEnum.JSON(), isOptional: true },
103
+ maxRetries: { type: ScalarTypeEnum.Int_unsecure(), isOptional: true },
104
+ enabled: { type: ScalarTypeEnum.Boolean(), isOptional: true }
105
+ }
106
+ });
107
+ var ListScheduledJobsOutput = defineSchemaModel({
108
+ name: "ListScheduledJobsOutput",
109
+ description: "Output for listing scheduled jobs",
110
+ fields: {
111
+ schedules: { type: ScheduledJobModel, isArray: true, isOptional: false }
112
+ }
113
+ });
114
+ var ToggleScheduledJobInput = defineSchemaModel({
115
+ name: "ToggleScheduledJobInput",
116
+ description: "Input for toggling a scheduled job",
117
+ fields: {
118
+ name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
119
+ enabled: { type: ScalarTypeEnum.Boolean(), isOptional: false }
120
+ }
121
+ });
122
+ var JobEnqueuedPayload = defineSchemaModel({
123
+ name: "JobEnqueuedPayload",
124
+ description: "Payload for job.enqueued event",
125
+ fields: {
126
+ jobId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
127
+ type: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
128
+ priority: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
129
+ scheduledAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
130
+ tenantId: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
131
+ enqueuedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
132
+ }
133
+ });
134
+ var JobCancelledPayload = defineSchemaModel({
135
+ name: "JobCancelledPayload",
136
+ description: "Payload for job.cancelled event",
137
+ fields: {
138
+ jobId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
139
+ }
140
+ });
141
+ var EnqueueJobContract = defineCommand({
142
+ meta: {
143
+ key: "jobs.enqueue",
144
+ version: "1.0.0",
145
+ stability: "stable",
146
+ owners: [...OWNERS],
147
+ tags: ["jobs", "enqueue"],
148
+ description: "Enqueue a background job for async processing.",
149
+ goal: "Allow services to offload work to background processing.",
150
+ context: "Called by any service that needs async processing."
151
+ },
152
+ io: {
153
+ input: EnqueueJobInput,
154
+ output: JobModel
155
+ },
156
+ policy: {
157
+ auth: "user"
158
+ },
159
+ sideEffects: {
160
+ emits: [
161
+ {
162
+ key: "job.enqueued",
163
+ version: "1.0.0",
164
+ when: "Job is enqueued",
165
+ payload: JobEnqueuedPayload
166
+ }
167
+ ]
168
+ }
169
+ });
170
+ var GetJobContract = defineQuery({
171
+ meta: {
172
+ key: "jobs.get",
173
+ version: "1.0.0",
174
+ stability: "stable",
175
+ owners: [...OWNERS],
176
+ tags: ["jobs", "get"],
177
+ description: "Get a job by ID.",
178
+ goal: "Check job status and result.",
179
+ context: "Called to poll job status or retrieve results."
180
+ },
181
+ io: {
182
+ input: GetJobInput,
183
+ output: JobModel
184
+ },
185
+ policy: {
186
+ auth: "user"
187
+ }
188
+ });
189
+ var CancelJobContract = defineCommand({
190
+ meta: {
191
+ key: "jobs.cancel",
192
+ version: "1.0.0",
193
+ stability: "stable",
194
+ owners: [...OWNERS],
195
+ tags: ["jobs", "cancel"],
196
+ description: "Cancel a pending job.",
197
+ goal: "Allow cancellation of jobs that are no longer needed.",
198
+ context: "Only pending jobs can be cancelled."
199
+ },
200
+ io: {
201
+ input: CancelJobInput,
202
+ output: CancelJobOutput,
203
+ errors: {
204
+ JOB_NOT_FOUND: {
205
+ description: "Job does not exist",
206
+ http: 404,
207
+ gqlCode: "JOB_NOT_FOUND",
208
+ when: "Job ID is invalid"
209
+ },
210
+ JOB_NOT_PENDING: {
211
+ description: "Job is not in pending state",
212
+ http: 409,
213
+ gqlCode: "JOB_NOT_PENDING",
214
+ when: "Job has already started or completed"
215
+ }
216
+ }
217
+ },
218
+ policy: {
219
+ auth: "user"
220
+ },
221
+ sideEffects: {
222
+ emits: [
223
+ {
224
+ key: "job.cancelled",
225
+ version: "1.0.0",
226
+ when: "Job is cancelled",
227
+ payload: JobCancelledPayload
228
+ }
229
+ ]
230
+ }
231
+ });
232
+ var GetQueueStatsContract = defineQuery({
233
+ meta: {
234
+ key: "jobs.stats",
235
+ version: "1.0.0",
236
+ stability: "stable",
237
+ owners: [...OWNERS],
238
+ tags: ["jobs", "stats", "admin"],
239
+ description: "Get job queue statistics.",
240
+ goal: "Monitor queue health and backlog.",
241
+ context: "Admin dashboard monitoring."
242
+ },
243
+ io: {
244
+ input: null,
245
+ output: QueueStatsModel
246
+ },
247
+ policy: {
248
+ auth: "admin"
249
+ }
250
+ });
251
+ var CreateScheduledJobContract = defineCommand({
252
+ meta: {
253
+ key: "jobs.schedule.create",
254
+ version: "1.0.0",
255
+ stability: "stable",
256
+ owners: [...OWNERS],
257
+ tags: ["jobs", "schedule", "create"],
258
+ description: "Create a scheduled/recurring job.",
259
+ goal: "Set up recurring background tasks.",
260
+ context: "Admin configuration for periodic tasks."
261
+ },
262
+ io: {
263
+ input: CreateScheduledJobInput,
264
+ output: ScheduledJobModel
265
+ },
266
+ policy: {
267
+ auth: "admin"
268
+ }
269
+ });
270
+ var ListScheduledJobsContract = defineQuery({
271
+ meta: {
272
+ key: "jobs.schedule.list",
273
+ version: "1.0.0",
274
+ stability: "stable",
275
+ owners: [...OWNERS],
276
+ tags: ["jobs", "schedule", "list"],
277
+ description: "List all scheduled jobs.",
278
+ goal: "View configured recurring tasks.",
279
+ context: "Admin dashboard."
280
+ },
281
+ io: {
282
+ input: null,
283
+ output: ListScheduledJobsOutput
284
+ },
285
+ policy: {
286
+ auth: "admin"
287
+ }
288
+ });
289
+ var ToggleScheduledJobContract = defineCommand({
290
+ meta: {
291
+ key: "jobs.schedule.toggle",
292
+ version: "1.0.0",
293
+ stability: "stable",
294
+ owners: [...OWNERS],
295
+ tags: ["jobs", "schedule", "toggle"],
296
+ description: "Enable or disable a scheduled job.",
297
+ goal: "Control when recurring tasks run.",
298
+ context: "Admin control over scheduled tasks."
299
+ },
300
+ io: {
301
+ input: ToggleScheduledJobInput,
302
+ output: ScheduledJobModel
303
+ },
304
+ policy: {
305
+ auth: "admin"
306
+ }
307
+ });
308
+
309
+ // src/entities/index.ts
310
+ import {
311
+ defineEntity,
312
+ defineEntityEnum,
313
+ field,
314
+ index
315
+ } from "@contractspec/lib.schema";
316
+ var JobStatusEnum = defineEntityEnum({
317
+ name: "JobStatus",
318
+ values: [
319
+ "PENDING",
320
+ "RUNNING",
321
+ "COMPLETED",
322
+ "FAILED",
323
+ "CANCELLED",
324
+ "DEAD_LETTER"
325
+ ],
326
+ schema: "lssm_jobs",
327
+ description: "Status of a background job."
328
+ });
329
+ var JobEntity = defineEntity({
330
+ name: "Job",
331
+ description: "A background job for async processing.",
332
+ schema: "lssm_jobs",
333
+ map: "job",
334
+ fields: {
335
+ id: field.id({ description: "Unique job identifier" }),
336
+ type: field.string({ description: "Job type identifier" }),
337
+ version: field.int({ default: 1, description: "Job type version" }),
338
+ payload: field.json({ description: "Job payload data" }),
339
+ status: field.enum("JobStatus", { default: "PENDING" }),
340
+ priority: field.int({ default: 0, description: "Higher = more urgent" }),
341
+ attempts: field.int({
342
+ default: 0,
343
+ description: "Number of execution attempts"
344
+ }),
345
+ maxRetries: field.int({
346
+ default: 3,
347
+ description: "Maximum retry attempts"
348
+ }),
349
+ lastError: field.string({
350
+ isOptional: true,
351
+ description: "Last error message"
352
+ }),
353
+ lastErrorStack: field.string({
354
+ isOptional: true,
355
+ description: "Last error stack trace"
356
+ }),
357
+ scheduledAt: field.dateTime({
358
+ isOptional: true,
359
+ description: "When job should be processed"
360
+ }),
361
+ startedAt: field.dateTime({
362
+ isOptional: true,
363
+ description: "When processing started"
364
+ }),
365
+ completedAt: field.dateTime({
366
+ isOptional: true,
367
+ description: "When processing completed"
368
+ }),
369
+ timeoutAt: field.dateTime({
370
+ isOptional: true,
371
+ description: "Job timeout deadline"
372
+ }),
373
+ dedupeKey: field.string({
374
+ isOptional: true,
375
+ description: "Key for deduplication"
376
+ }),
377
+ tenantId: field.string({
378
+ isOptional: true,
379
+ description: "Tenant/org context"
380
+ }),
381
+ userId: field.string({
382
+ isOptional: true,
383
+ description: "User who enqueued"
384
+ }),
385
+ traceId: field.string({
386
+ isOptional: true,
387
+ description: "Distributed trace ID"
388
+ }),
389
+ metadata: field.json({
390
+ isOptional: true,
391
+ description: "Additional metadata"
392
+ }),
393
+ result: field.json({ isOptional: true, description: "Job result data" }),
394
+ createdAt: field.createdAt(),
395
+ updatedAt: field.updatedAt(),
396
+ scheduledJob: field.belongsTo("ScheduledJob", ["scheduledJobId"], ["id"]),
397
+ scheduledJobId: field.string({ isOptional: true }),
398
+ executions: field.hasMany("JobExecution")
399
+ },
400
+ indexes: [
401
+ index.on(["status", "scheduledAt"]),
402
+ index.on(["type", "status"]),
403
+ index.on(["tenantId", "status"]),
404
+ index.unique(["dedupeKey"], { name: "job_dedupe_key_unique" })
405
+ ],
406
+ enums: [JobStatusEnum]
407
+ });
408
+ var ScheduledJobEntity = defineEntity({
409
+ name: "ScheduledJob",
410
+ description: "A scheduled/recurring job definition.",
411
+ schema: "lssm_jobs",
412
+ map: "scheduled_job",
413
+ fields: {
414
+ id: field.id(),
415
+ name: field.string({ isUnique: true, description: "Unique schedule name" }),
416
+ description: field.string({ isOptional: true }),
417
+ cronExpression: field.string({
418
+ description: "Cron expression for scheduling"
419
+ }),
420
+ timezone: field.string({
421
+ default: '"UTC"',
422
+ description: "Timezone for cron evaluation"
423
+ }),
424
+ jobType: field.string({ description: "Job type to create" }),
425
+ jobVersion: field.int({ default: 1 }),
426
+ payload: field.json({
427
+ isOptional: true,
428
+ description: "Default payload for created jobs"
429
+ }),
430
+ maxRetries: field.int({ default: 3 }),
431
+ timeoutMs: field.int({
432
+ isOptional: true,
433
+ description: "Job timeout in milliseconds"
434
+ }),
435
+ enabled: field.boolean({ default: true }),
436
+ lastRunAt: field.dateTime({ isOptional: true }),
437
+ nextRunAt: field.dateTime({ isOptional: true }),
438
+ tenantId: field.string({ isOptional: true }),
439
+ createdAt: field.createdAt(),
440
+ updatedAt: field.updatedAt(),
441
+ jobs: field.hasMany("Job")
442
+ },
443
+ indexes: [index.on(["enabled", "nextRunAt"])]
444
+ });
445
+ var JobExecutionEntity = defineEntity({
446
+ name: "JobExecution",
447
+ description: "A single execution attempt of a job.",
448
+ schema: "lssm_jobs",
449
+ map: "job_execution",
450
+ fields: {
451
+ id: field.id(),
452
+ jobId: field.foreignKey(),
453
+ attemptNumber: field.int({ description: "Which attempt this is" }),
454
+ startedAt: field.dateTime(),
455
+ completedAt: field.dateTime({ isOptional: true }),
456
+ durationMs: field.int({ isOptional: true }),
457
+ success: field.boolean({ isOptional: true }),
458
+ error: field.string({ isOptional: true }),
459
+ errorStack: field.string({ isOptional: true }),
460
+ result: field.json({ isOptional: true }),
461
+ workerId: field.string({
462
+ isOptional: true,
463
+ description: "ID of worker that processed"
464
+ }),
465
+ job: field.belongsTo("Job", ["jobId"], ["id"], { onDelete: "Cascade" })
466
+ },
467
+ indexes: [index.on(["jobId", "attemptNumber"])]
468
+ });
469
+ var jobEntities = [JobEntity, ScheduledJobEntity, JobExecutionEntity];
470
+ var jobsSchemaContribution = {
471
+ moduleId: "@contractspec/lib.jobs",
472
+ entities: jobEntities,
473
+ enums: [JobStatusEnum]
474
+ };
475
+
476
+ // src/events.ts
477
+ import { ScalarTypeEnum as ScalarTypeEnum2, defineSchemaModel as defineSchemaModel2 } from "@contractspec/lib.schema";
478
+ import { defineEvent, StabilityEnum } from "@contractspec/lib.contracts";
479
+ var JobEnqueuedPayload2 = defineSchemaModel2({
480
+ name: "JobEnqueuedEventPayload",
481
+ description: "Payload when a job is added to the queue",
482
+ fields: {
483
+ jobId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
484
+ type: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
485
+ priority: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
486
+ scheduledAt: { type: ScalarTypeEnum2.DateTime(), isOptional: true },
487
+ tenantId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
488
+ enqueuedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
489
+ }
490
+ });
491
+ var JobStartedPayload = defineSchemaModel2({
492
+ name: "JobStartedEventPayload",
493
+ description: "Payload when a job starts processing",
494
+ fields: {
495
+ jobId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
496
+ type: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
497
+ attempt: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
498
+ startedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
499
+ }
500
+ });
501
+ var JobCompletedPayload = defineSchemaModel2({
502
+ name: "JobCompletedEventPayload",
503
+ description: "Payload when a job completes successfully",
504
+ fields: {
505
+ jobId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
506
+ type: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
507
+ attempt: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
508
+ durationMs: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
509
+ completedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
510
+ }
511
+ });
512
+ var JobFailedPayload = defineSchemaModel2({
513
+ name: "JobFailedEventPayload",
514
+ description: "Payload when a job attempt fails",
515
+ fields: {
516
+ jobId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
517
+ type: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
518
+ attempt: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
519
+ error: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
520
+ willRetry: { type: ScalarTypeEnum2.Boolean(), isOptional: false },
521
+ failedAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
522
+ }
523
+ });
524
+ var JobRetryingPayload = defineSchemaModel2({
525
+ name: "JobRetryingEventPayload",
526
+ description: "Payload when a job is scheduled for retry",
527
+ fields: {
528
+ jobId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
529
+ type: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
530
+ attempt: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
531
+ nextAttemptAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false },
532
+ backoffMs: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false }
533
+ }
534
+ });
535
+ var JobDeadLetteredPayload = defineSchemaModel2({
536
+ name: "JobDeadLetteredEventPayload",
537
+ description: "Payload when a job is moved to dead letter queue",
538
+ fields: {
539
+ jobId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
540
+ type: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
541
+ attempts: { type: ScalarTypeEnum2.Int_unsecure(), isOptional: false },
542
+ lastError: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
543
+ deadLetteredAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
544
+ }
545
+ });
546
+ var JobCancelledPayload2 = defineSchemaModel2({
547
+ name: "JobCancelledEventPayload",
548
+ description: "Payload when a job is cancelled",
549
+ fields: {
550
+ jobId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
551
+ type: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
552
+ cancelledBy: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
553
+ cancelledAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
554
+ }
555
+ });
556
+ var ScheduledJobTriggeredPayload = defineSchemaModel2({
557
+ name: "ScheduledJobTriggeredEventPayload",
558
+ description: "Payload when a scheduled job is triggered",
559
+ fields: {
560
+ scheduleName: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
561
+ jobId: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
562
+ jobType: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
563
+ triggeredAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false },
564
+ nextRunAt: { type: ScalarTypeEnum2.DateTime(), isOptional: true }
565
+ }
566
+ });
567
+ var JobEnqueuedEvent = defineEvent({
568
+ meta: {
569
+ key: "job.enqueued",
570
+ version: "1.0.0",
571
+ description: "A job has been added to the queue.",
572
+ stability: StabilityEnum.Stable,
573
+ owners: ["@contractspec.libs.jobs"],
574
+ tags: ["job-queue", "lifecycle"]
575
+ },
576
+ payload: JobEnqueuedPayload2
577
+ });
578
+ var JobStartedEvent = defineEvent({
579
+ meta: {
580
+ key: "job.started",
581
+ version: "1.0.0",
582
+ description: "A job has started processing.",
583
+ stability: StabilityEnum.Stable,
584
+ owners: ["@contractspec.libs.jobs"],
585
+ tags: ["job-queue", "lifecycle"]
586
+ },
587
+ payload: JobStartedPayload
588
+ });
589
+ var JobCompletedEvent = defineEvent({
590
+ meta: {
591
+ key: "job.completed",
592
+ version: "1.0.0",
593
+ description: "A job has completed successfully.",
594
+ stability: StabilityEnum.Stable,
595
+ owners: ["@contractspec.libs.jobs"],
596
+ tags: ["job-queue", "lifecycle"]
597
+ },
598
+ payload: JobCompletedPayload
599
+ });
600
+ var JobFailedEvent = defineEvent({
601
+ meta: {
602
+ key: "job.failed",
603
+ version: "1.0.0",
604
+ description: "A job attempt has failed.",
605
+ stability: StabilityEnum.Stable,
606
+ owners: ["@contractspec.libs.jobs"],
607
+ tags: ["job-queue", "lifecycle", "error"]
608
+ },
609
+ payload: JobFailedPayload
610
+ });
611
+ var JobRetryingEvent = defineEvent({
612
+ meta: {
613
+ key: "job.retrying",
614
+ version: "1.0.0",
615
+ description: "A job is being scheduled for retry.",
616
+ stability: StabilityEnum.Stable,
617
+ owners: ["@contractspec.libs.jobs"],
618
+ tags: ["job-queue", "lifecycle", "retry"]
619
+ },
620
+ payload: JobRetryingPayload
621
+ });
622
+ var JobDeadLetteredEvent = defineEvent({
623
+ meta: {
624
+ key: "job.dead_lettered",
625
+ version: "1.0.0",
626
+ description: "A job has exhausted all retries and moved to dead letter queue.",
627
+ stability: StabilityEnum.Stable,
628
+ owners: ["@contractspec.libs.jobs"],
629
+ tags: ["job-queue", "lifecycle", "error"]
630
+ },
631
+ payload: JobDeadLetteredPayload
632
+ });
633
+ var JobCancelledEvent = defineEvent({
634
+ meta: {
635
+ key: "job.cancelled",
636
+ version: "1.0.0",
637
+ description: "A job has been cancelled.",
638
+ stability: StabilityEnum.Stable,
639
+ owners: ["@contractspec.libs.jobs"],
640
+ tags: ["job-queue", "lifecycle"]
641
+ },
642
+ payload: JobCancelledPayload2
643
+ });
644
+ var ScheduledJobTriggeredEvent = defineEvent({
645
+ meta: {
646
+ key: "scheduler.job_triggered",
647
+ version: "1.0.0",
648
+ description: "A scheduled job has been triggered.",
649
+ stability: StabilityEnum.Stable,
650
+ owners: ["@contractspec.libs.jobs"],
651
+ tags: ["job-queue", "scheduler"]
652
+ },
653
+ payload: ScheduledJobTriggeredPayload
654
+ });
655
+ var JobEvents = {
656
+ JobEnqueuedEvent,
657
+ JobStartedEvent,
658
+ JobCompletedEvent,
659
+ JobFailedEvent,
660
+ JobRetryingEvent,
661
+ JobDeadLetteredEvent,
662
+ JobCancelledEvent,
663
+ ScheduledJobTriggeredEvent
664
+ };
665
+
666
+ // src/handlers/gmail-sync-handler.ts
667
+ function createGmailSyncHandler(adapter) {
668
+ return async (job) => {
669
+ await adapter.syncThreads(job.payload);
670
+ };
671
+ }
672
+
673
+ // src/handlers/ping-job.ts
674
+ import * as z from "zod";
675
+ var PING_JOB_TYPE = "core.ping";
676
+ var PingPayloadSchema = z.object({});
677
+ var pingJob = {
678
+ type: PING_JOB_TYPE,
679
+ schema: PingPayloadSchema,
680
+ handler: async (_payload, _job) => {}
681
+ };
682
+
683
+ // src/handlers/storage-document-handler.ts
684
+ function createStorageDocumentHandler(storage, adapter) {
685
+ return async (job) => {
686
+ const object2 = await storage.getObject({
687
+ bucket: job.payload.bucket,
688
+ key: job.payload.key
689
+ });
690
+ if (!object2) {
691
+ throw new Error(`Object ${job.payload.bucket}/${job.payload.key} not found`);
692
+ }
693
+ await adapter.ingestObject(object2);
694
+ };
695
+ }
17
696
 
18
- export * from "@contractspec/lib.contracts/jobs/queue"
697
+ // src/queue/register-defined-job.ts
698
+ function registerDefinedJob(queue, def) {
699
+ const wrapped = async (job) => {
700
+ const payload = def.schema.parse(job.payload);
701
+ const typedJob = {
702
+ ...job,
703
+ payload
704
+ };
705
+ await def.handler(payload, typedJob);
706
+ };
707
+ queue.register(def.type, wrapped);
708
+ }
709
+ // src/handlers/index.ts
710
+ function registerAllJobs(queue) {
711
+ registerDefinedJob(queue, pingJob);
712
+ }
19
713
 
20
- //#region src/index.ts
21
- var src_exports = /* @__PURE__ */ __exportAll({
22
- CancelJobContract: () => CancelJobContract,
23
- CreateScheduledJobContract: () => CreateScheduledJobContract,
24
- EnqueueJobContract: () => EnqueueJobContract,
25
- GcpCloudTasksQueue: () => GcpCloudTasksQueue,
26
- GcpPubSubQueue: () => GcpPubSubQueue,
27
- GetJobContract: () => GetJobContract,
28
- GetQueueStatsContract: () => GetQueueStatsContract,
29
- JobCancelledEvent: () => JobCancelledEvent,
30
- JobCompletedEvent: () => JobCompletedEvent,
31
- JobDeadLetteredEvent: () => JobDeadLetteredEvent,
32
- JobEnqueuedEvent: () => JobEnqueuedEvent,
33
- JobEntity: () => JobEntity,
34
- JobEvents: () => JobEvents,
35
- JobExecutionEntity: () => JobExecutionEntity,
36
- JobFailedEvent: () => JobFailedEvent,
37
- JobModel: () => JobModel,
38
- JobRetryingEvent: () => JobRetryingEvent,
39
- JobScheduler: () => JobScheduler,
40
- JobStartedEvent: () => JobStartedEvent,
41
- JobStatusEnum: () => JobStatusEnum,
42
- JobsFeature: () => JobsFeature,
43
- ListScheduledJobsContract: () => ListScheduledJobsContract,
44
- MemoryJobQueue: () => MemoryJobQueue,
45
- PING_JOB_TYPE: () => PING_JOB_TYPE,
46
- PingPayloadSchema: () => PingPayloadSchema,
47
- QueueStatsModel: () => QueueStatsModel,
48
- ScalewaySqsJobQueue: () => ScalewaySqsJobQueue,
49
- ScheduledJobEntity: () => ScheduledJobEntity,
50
- ScheduledJobModel: () => ScheduledJobModel,
51
- ScheduledJobTriggeredEvent: () => ScheduledJobTriggeredEvent,
52
- ToggleScheduledJobContract: () => ToggleScheduledJobContract,
53
- createGmailSyncHandler: () => createGmailSyncHandler,
54
- createScheduler: () => createScheduler,
55
- createStorageDocumentHandler: () => createStorageDocumentHandler,
56
- defineSchedule: () => defineSchedule,
57
- jobEntities: () => jobEntities,
58
- jobsSchemaContribution: () => jobsSchemaContribution,
59
- pingJob: () => pingJob,
60
- registerAllJobs: () => registerAllJobs,
61
- registerDefinedJob: () => registerDefinedJob
62
- });
63
- __reExport(src_exports, queue_exports);
714
+ // src/queue/types.ts
715
+ export * from "@contractspec/lib.contracts/jobs/queue";
716
+ import {
717
+ calculateBackoff,
718
+ DEFAULT_RETRY_POLICY
719
+ } from "@contractspec/lib.contracts/jobs/queue";
64
720
 
65
- //#endregion
66
- export { CancelJobContract, CreateScheduledJobContract, EnqueueJobContract, GcpCloudTasksQueue, GcpPubSubQueue, GetJobContract, GetQueueStatsContract, JobCancelledEvent, JobCompletedEvent, JobDeadLetteredEvent, JobEnqueuedEvent, JobEntity, JobEvents, JobExecutionEntity, JobFailedEvent, JobModel, JobRetryingEvent, JobScheduler, JobStartedEvent, JobStatusEnum, JobsFeature, ListScheduledJobsContract, MemoryJobQueue, PING_JOB_TYPE, PingPayloadSchema, QueueStatsModel, ScalewaySqsJobQueue, ScheduledJobEntity, ScheduledJobModel, ScheduledJobTriggeredEvent, ToggleScheduledJobContract, createGmailSyncHandler, createScheduler, createStorageDocumentHandler, defineSchedule, jobEntities, jobsSchemaContribution, pingJob, registerAllJobs, registerDefinedJob };
67
- //# sourceMappingURL=index.js.map
721
+ // src/queue/memory-queue.ts
722
+ import { randomUUID } from "crypto";
723
+ class MemoryJobQueue {
724
+ jobs = new Map;
725
+ handlers = new Map;
726
+ timer;
727
+ activeCount = 0;
728
+ pollIntervalMs;
729
+ concurrency;
730
+ retryPolicy;
731
+ constructor(options = {}) {
732
+ this.pollIntervalMs = options.pollIntervalMs ?? 200;
733
+ this.concurrency = options.concurrency ?? 5;
734
+ this.retryPolicy = options.retryPolicy ?? DEFAULT_RETRY_POLICY;
735
+ }
736
+ async enqueue(jobType, payload, options = {}) {
737
+ if (options.dedupeKey) {
738
+ const existing = Array.from(this.jobs.values()).find((j) => j.dedupeKey === options.dedupeKey && j.status === "pending");
739
+ if (existing) {
740
+ return existing;
741
+ }
742
+ }
743
+ const now = new Date;
744
+ const scheduledAt = options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now;
745
+ const job = {
746
+ id: randomUUID(),
747
+ type: jobType,
748
+ version: "1.0.0",
749
+ payload,
750
+ status: "pending",
751
+ priority: options.priority ?? 0,
752
+ attempts: 0,
753
+ maxRetries: options.maxRetries ?? this.retryPolicy.maxRetries,
754
+ createdAt: now,
755
+ updatedAt: now,
756
+ scheduledAt,
757
+ dedupeKey: options.dedupeKey,
758
+ tenantId: options.tenantId,
759
+ userId: options.userId,
760
+ traceId: options.traceId,
761
+ metadata: options.metadata
762
+ };
763
+ if (options.timeoutMs) {
764
+ job.timeoutAt = new Date(now.getTime() + options.timeoutMs);
765
+ }
766
+ this.jobs.set(job.id, job);
767
+ return job;
768
+ }
769
+ register(jobType, handler) {
770
+ this.handlers.set(jobType, handler);
771
+ }
772
+ start() {
773
+ if (this.timer)
774
+ return;
775
+ this.timer = setInterval(() => {
776
+ this.processNext();
777
+ }, this.pollIntervalMs);
778
+ }
779
+ async stop() {
780
+ if (this.timer) {
781
+ clearInterval(this.timer);
782
+ this.timer = undefined;
783
+ }
784
+ while (this.activeCount > 0) {
785
+ await new Promise((resolve) => setTimeout(resolve, 50));
786
+ }
787
+ }
788
+ async getJob(jobId) {
789
+ return this.jobs.get(jobId) ?? null;
790
+ }
791
+ async cancelJob(jobId) {
792
+ const job = this.jobs.get(jobId);
793
+ if (!job || job.status !== "pending") {
794
+ return false;
795
+ }
796
+ job.status = "cancelled";
797
+ job.updatedAt = new Date;
798
+ return true;
799
+ }
800
+ async getStats() {
801
+ const stats = {
802
+ pending: 0,
803
+ running: 0,
804
+ completed: 0,
805
+ failed: 0,
806
+ deadLetter: 0
807
+ };
808
+ for (const job of this.jobs.values()) {
809
+ switch (job.status) {
810
+ case "pending":
811
+ stats.pending++;
812
+ break;
813
+ case "running":
814
+ stats.running++;
815
+ break;
816
+ case "completed":
817
+ stats.completed++;
818
+ break;
819
+ case "failed":
820
+ stats.failed++;
821
+ break;
822
+ case "dead_letter":
823
+ stats.deadLetter++;
824
+ break;
825
+ }
826
+ }
827
+ return stats;
828
+ }
829
+ async processNext() {
830
+ if (this.activeCount >= this.concurrency)
831
+ return;
832
+ const now = new Date;
833
+ const pendingJobs = Array.from(this.jobs.values()).filter((j) => j.status === "pending" && (!j.scheduledAt || j.scheduledAt <= now)).sort((a, b) => {
834
+ if (a.priority !== b.priority) {
835
+ return b.priority - a.priority;
836
+ }
837
+ return (a.scheduledAt?.getTime() ?? 0) - (b.scheduledAt?.getTime() ?? 0);
838
+ });
839
+ const job = pendingJobs[0];
840
+ if (!job)
841
+ return;
842
+ const handler = this.handlers.get(job.type);
843
+ if (!handler)
844
+ return;
845
+ this.activeCount++;
846
+ job.status = "running";
847
+ job.startedAt = new Date;
848
+ job.updatedAt = new Date;
849
+ job.attempts += 1;
850
+ try {
851
+ const result = await handler(job);
852
+ job.status = "completed";
853
+ job.completedAt = new Date;
854
+ job.result = result;
855
+ } catch (error) {
856
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
857
+ job.lastError = errorMessage;
858
+ if (job.attempts >= job.maxRetries) {
859
+ job.status = "dead_letter";
860
+ } else {
861
+ const backoff = calculateBackoff(job.attempts, this.retryPolicy);
862
+ job.status = "pending";
863
+ job.scheduledAt = new Date(Date.now() + backoff);
864
+ }
865
+ } finally {
866
+ job.updatedAt = new Date;
867
+ this.activeCount--;
868
+ }
869
+ }
870
+ }
871
+
872
+ // src/queue/scaleway-sqs-queue.ts
873
+ import { randomUUID as randomUUID2 } from "crypto";
874
+ import {
875
+ DeleteMessageCommand,
876
+ ReceiveMessageCommand,
877
+ SendMessageCommand,
878
+ SQSClient
879
+ } from "@aws-sdk/client-sqs";
880
+ class ScalewaySqsJobQueue {
881
+ sqs;
882
+ queueUrl;
883
+ waitTimeSeconds;
884
+ maxNumberOfMessages;
885
+ visibilityTimeoutSeconds;
886
+ handlers = new Map;
887
+ logger;
888
+ running = false;
889
+ constructor(config) {
890
+ this.logger = config.logger;
891
+ const accessKeyId = config.credentials?.accessKeyId ?? process.env.SCALEWAY_ACCESS_KEY_QUEUE;
892
+ const secretAccessKey = config.credentials?.secretAccessKey ?? process.env.SCALEWAY_SECRET_KEY_QUEUE;
893
+ if (!accessKeyId || !secretAccessKey) {
894
+ throw new Error("Missing SCALEWAY_ACCESS_KEY_QUEUE / SCALEWAY_SECRET_KEY_QUEUE in env");
895
+ }
896
+ const region = config.region ?? process.env.SCALEWAY_REGION ?? "par";
897
+ const endpoint = config.endpoint ?? "https://sqs.mnq.fr-par.scaleway.com";
898
+ this.sqs = new SQSClient({
899
+ region,
900
+ endpoint,
901
+ credentials: {
902
+ accessKeyId,
903
+ secretAccessKey
904
+ }
905
+ });
906
+ this.queueUrl = config.queueUrl;
907
+ this.waitTimeSeconds = config.waitTimeSeconds ?? 20;
908
+ this.maxNumberOfMessages = config.maxNumberOfMessages ?? 5;
909
+ this.visibilityTimeoutSeconds = config.visibilityTimeoutSeconds ?? 60;
910
+ }
911
+ async enqueue(jobType, payload, options = {}) {
912
+ const id = randomUUID2();
913
+ const now = new Date;
914
+ const scheduledAt = options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now;
915
+ const envelope = {
916
+ id,
917
+ type: jobType,
918
+ payload
919
+ };
920
+ await this.sqs.send(new SendMessageCommand({
921
+ QueueUrl: this.queueUrl,
922
+ MessageBody: JSON.stringify(envelope),
923
+ DelaySeconds: options.delaySeconds ?? 0
924
+ }));
925
+ return {
926
+ id,
927
+ type: jobType,
928
+ version: "1.0.0",
929
+ payload,
930
+ status: "pending",
931
+ priority: options.priority ?? 0,
932
+ attempts: 0,
933
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
934
+ createdAt: now,
935
+ updatedAt: now,
936
+ scheduledAt,
937
+ dedupeKey: options.dedupeKey,
938
+ tenantId: options.tenantId,
939
+ userId: options.userId,
940
+ traceId: options.traceId,
941
+ metadata: options.metadata
942
+ };
943
+ }
944
+ register(jobType, handler) {
945
+ if (this.handlers.has(jobType)) {
946
+ throw new Error(`Handler already registered for job type "${jobType}"`);
947
+ }
948
+ this.handlers.set(jobType, handler);
949
+ }
950
+ start() {
951
+ if (this.running)
952
+ return;
953
+ this.running = true;
954
+ this.pollLoop().catch((error) => {
955
+ this.logger?.error?.("jobs.queue.scaleway_sqs.poll_loop_fatal", {
956
+ error: error instanceof Error ? error.message : String(error)
957
+ });
958
+ this.running = false;
959
+ });
960
+ }
961
+ async stop() {
962
+ this.running = false;
963
+ }
964
+ async pollLoop() {
965
+ this.logger?.info?.("jobs.queue.scaleway_sqs.started", {
966
+ queueUrl: this.queueUrl
967
+ });
968
+ while (this.running) {
969
+ try {
970
+ const res = await this.sqs.send(new ReceiveMessageCommand({
971
+ QueueUrl: this.queueUrl,
972
+ MaxNumberOfMessages: this.maxNumberOfMessages,
973
+ WaitTimeSeconds: this.waitTimeSeconds,
974
+ VisibilityTimeout: this.visibilityTimeoutSeconds,
975
+ MessageSystemAttributeNames: ["ApproximateReceiveCount"]
976
+ }));
977
+ const messages = res.Messages ?? [];
978
+ if (messages.length === 0) {
979
+ continue;
980
+ }
981
+ for (const msg of messages) {
982
+ if (!msg.Body || !msg.ReceiptHandle) {
983
+ this.logger?.warn?.("jobs.queue.scaleway_sqs.invalid_message", {
984
+ messageId: msg.MessageId,
985
+ reason: "missing_body_or_receipt"
986
+ });
987
+ continue;
988
+ }
989
+ let envelope;
990
+ try {
991
+ envelope = JSON.parse(msg.Body);
992
+ } catch (err) {
993
+ this.logger?.warn?.("jobs.queue.scaleway_sqs.parse_failed", {
994
+ messageId: msg.MessageId,
995
+ error: err instanceof Error ? err.message : String(err)
996
+ });
997
+ await this.deleteMessage(msg.ReceiptHandle);
998
+ continue;
999
+ }
1000
+ const handler = this.handlers.get(envelope.type);
1001
+ if (!handler) {
1002
+ this.logger?.warn?.("jobs.queue.scaleway_sqs.missing_handler", {
1003
+ jobType: envelope.type,
1004
+ messageId: msg.MessageId
1005
+ });
1006
+ await this.deleteMessage(msg.ReceiptHandle);
1007
+ continue;
1008
+ }
1009
+ const now = new Date;
1010
+ const attempts = parseInt(msg.Attributes?.ApproximateReceiveCount ?? "1", 10);
1011
+ const job = {
1012
+ id: envelope.id,
1013
+ type: envelope.type,
1014
+ version: "1.0.0",
1015
+ payload: envelope.payload,
1016
+ status: "pending",
1017
+ priority: 0,
1018
+ attempts,
1019
+ maxRetries: DEFAULT_RETRY_POLICY.maxRetries,
1020
+ createdAt: now,
1021
+ updatedAt: now
1022
+ };
1023
+ job.status = "running";
1024
+ job.updatedAt = new Date;
1025
+ try {
1026
+ await handler(job);
1027
+ job.status = "completed";
1028
+ job.updatedAt = new Date;
1029
+ await this.deleteMessage(msg.ReceiptHandle);
1030
+ } catch (err) {
1031
+ job.status = "failed";
1032
+ job.lastError = err instanceof Error ? err.message : "Unknown job error";
1033
+ job.updatedAt = new Date;
1034
+ this.logger?.error?.("jobs.queue.scaleway_sqs.job_failed", {
1035
+ jobType: job.type,
1036
+ jobId: job.id,
1037
+ error: err instanceof Error ? err.message : String(err)
1038
+ });
1039
+ }
1040
+ }
1041
+ } catch (err) {
1042
+ this.logger?.error?.("jobs.queue.scaleway_sqs.poll_error", {
1043
+ error: err instanceof Error ? err.message : String(err)
1044
+ });
1045
+ await this.sleep(5000);
1046
+ }
1047
+ }
1048
+ this.logger?.info?.("jobs.queue.scaleway_sqs.stopped", {
1049
+ queueUrl: this.queueUrl
1050
+ });
1051
+ }
1052
+ async deleteMessage(receiptHandle) {
1053
+ try {
1054
+ await this.sqs.send(new DeleteMessageCommand({
1055
+ QueueUrl: this.queueUrl,
1056
+ ReceiptHandle: receiptHandle
1057
+ }));
1058
+ } catch (err) {
1059
+ this.logger?.warn?.("jobs.queue.scaleway_sqs.delete_failed", {
1060
+ error: err instanceof Error ? err.message : String(err)
1061
+ });
1062
+ }
1063
+ }
1064
+ async sleep(ms) {
1065
+ await new Promise((resolve) => setTimeout(resolve, ms));
1066
+ }
1067
+ }
1068
+
1069
+ // src/queue/gcp-cloud-tasks.ts
1070
+ import { randomUUID as randomUUID3 } from "crypto";
1071
+ class GcpCloudTasksQueue {
1072
+ options;
1073
+ handlers = new Map;
1074
+ constructor(options) {
1075
+ this.options = options;
1076
+ }
1077
+ async enqueue(jobType, payload, options = {}) {
1078
+ const now = new Date;
1079
+ const enqueueTime = options.delaySeconds != null ? { seconds: Math.floor(Date.now() / 1000) + options.delaySeconds } : undefined;
1080
+ const body = Buffer.from(JSON.stringify({
1081
+ id: randomUUID3(),
1082
+ type: jobType,
1083
+ payload
1084
+ }), "utf-8");
1085
+ await this.options.client.createTask({
1086
+ parent: `projects/${this.options.projectId}/locations/${this.options.location}/queues/${this.options.queue}`,
1087
+ task: {
1088
+ httpRequest: {
1089
+ httpMethod: "POST",
1090
+ url: this.options.resolveUrl(jobType),
1091
+ body,
1092
+ headers: { "Content-Type": "application/json" },
1093
+ oidcToken: this.options.serviceAccountEmail ? { serviceAccountEmail: this.options.serviceAccountEmail } : undefined
1094
+ },
1095
+ scheduleTime: enqueueTime
1096
+ }
1097
+ });
1098
+ return {
1099
+ id: randomUUID3(),
1100
+ type: jobType,
1101
+ version: "1.0.0",
1102
+ payload,
1103
+ status: "pending",
1104
+ priority: options.priority ?? 0,
1105
+ attempts: 0,
1106
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
1107
+ createdAt: now,
1108
+ updatedAt: now,
1109
+ scheduledAt: options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now,
1110
+ dedupeKey: options.dedupeKey,
1111
+ tenantId: options.tenantId,
1112
+ userId: options.userId,
1113
+ traceId: options.traceId,
1114
+ metadata: options.metadata
1115
+ };
1116
+ }
1117
+ register(jobType, handler) {
1118
+ this.handlers.set(jobType, handler);
1119
+ }
1120
+ start() {}
1121
+ async stop() {
1122
+ this.handlers.clear();
1123
+ }
1124
+ }
1125
+
1126
+ // src/queue/gcp-pubsub.ts
1127
+ import { randomUUID as randomUUID4 } from "crypto";
1128
+ class GcpPubSubQueue {
1129
+ options;
1130
+ handlers = new Map;
1131
+ constructor(options) {
1132
+ this.options = options;
1133
+ }
1134
+ async enqueue(jobType, payload, options = {}) {
1135
+ const now = new Date;
1136
+ await this.options.client.topic(this.options.topicName).publishMessage({
1137
+ data: Buffer.from(JSON.stringify({
1138
+ id: randomUUID4(),
1139
+ type: jobType,
1140
+ payload
1141
+ }), "utf-8")
1142
+ });
1143
+ return {
1144
+ id: randomUUID4(),
1145
+ type: jobType,
1146
+ version: "1.0.0",
1147
+ payload,
1148
+ status: "pending",
1149
+ priority: options.priority ?? 0,
1150
+ attempts: 0,
1151
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
1152
+ createdAt: now,
1153
+ updatedAt: now,
1154
+ scheduledAt: options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now,
1155
+ dedupeKey: options.dedupeKey,
1156
+ tenantId: options.tenantId,
1157
+ userId: options.userId,
1158
+ traceId: options.traceId,
1159
+ metadata: options.metadata
1160
+ };
1161
+ }
1162
+ register(jobType, handler) {
1163
+ this.handlers.set(jobType, handler);
1164
+ }
1165
+ start() {}
1166
+ async stop() {
1167
+ this.handlers.clear();
1168
+ }
1169
+ }
1170
+ // src/scheduler/index.ts
1171
+ function getNextCronRun(cronExpression, after = new Date) {
1172
+ try {
1173
+ const parts = cronExpression.trim().split(/\s+/);
1174
+ if (parts.length !== 5) {
1175
+ console.warn(`Invalid cron expression: ${cronExpression}`);
1176
+ return null;
1177
+ }
1178
+ const minute = parts[0];
1179
+ const hour = parts[1];
1180
+ const dayOfMonth = parts[2];
1181
+ const month = parts[3];
1182
+ const next = new Date(after);
1183
+ next.setSeconds(0);
1184
+ next.setMilliseconds(0);
1185
+ if (minute && hour && minute !== "*" && hour !== "*" && dayOfMonth === "*" && month === "*") {
1186
+ const targetMinute = Number.parseInt(minute, 10);
1187
+ const targetHour = Number.parseInt(hour, 10);
1188
+ next.setHours(targetHour, targetMinute, 0, 0);
1189
+ if (next <= after) {
1190
+ next.setDate(next.getDate() + 1);
1191
+ }
1192
+ return next;
1193
+ }
1194
+ next.setMinutes(next.getMinutes() + 1);
1195
+ return next;
1196
+ } catch {
1197
+ return null;
1198
+ }
1199
+ }
1200
+
1201
+ class JobScheduler {
1202
+ queue;
1203
+ schedules = new Map;
1204
+ timer;
1205
+ checkIntervalMs;
1206
+ constructor(queue2, options = {}) {
1207
+ this.queue = queue2;
1208
+ this.checkIntervalMs = options.checkIntervalMs ?? 60000;
1209
+ }
1210
+ schedule(config) {
1211
+ const nextRun = config.enabled !== false ? getNextCronRun(config.cronExpression) : null;
1212
+ this.schedules.set(config.name, {
1213
+ ...config,
1214
+ enabled: config.enabled ?? true,
1215
+ nextRun,
1216
+ lastRun: null
1217
+ });
1218
+ }
1219
+ unschedule(name) {
1220
+ return this.schedules.delete(name);
1221
+ }
1222
+ enable(name) {
1223
+ const schedule = this.schedules.get(name);
1224
+ if (!schedule)
1225
+ return false;
1226
+ schedule.enabled = true;
1227
+ schedule.nextRun = getNextCronRun(schedule.cronExpression);
1228
+ return true;
1229
+ }
1230
+ disable(name) {
1231
+ const schedule = this.schedules.get(name);
1232
+ if (!schedule)
1233
+ return false;
1234
+ schedule.enabled = false;
1235
+ schedule.nextRun = null;
1236
+ return true;
1237
+ }
1238
+ getSchedules() {
1239
+ return Array.from(this.schedules.values());
1240
+ }
1241
+ getSchedule(name) {
1242
+ return this.schedules.get(name);
1243
+ }
1244
+ start() {
1245
+ if (this.timer)
1246
+ return;
1247
+ this.checkSchedules();
1248
+ this.timer = setInterval(() => {
1249
+ this.checkSchedules();
1250
+ }, this.checkIntervalMs);
1251
+ }
1252
+ stop() {
1253
+ if (this.timer) {
1254
+ clearInterval(this.timer);
1255
+ this.timer = undefined;
1256
+ }
1257
+ }
1258
+ async checkSchedules() {
1259
+ const now = new Date;
1260
+ for (const schedule of this.schedules.values()) {
1261
+ if (!schedule.enabled || !schedule.nextRun)
1262
+ continue;
1263
+ if (schedule.nextRun <= now) {
1264
+ try {
1265
+ const payload = typeof schedule.payload === "function" ? await schedule.payload() : schedule.payload;
1266
+ await this.queue.enqueue(schedule.jobType, payload, schedule.options);
1267
+ schedule.lastRun = now;
1268
+ schedule.nextRun = getNextCronRun(schedule.cronExpression, now);
1269
+ } catch (error) {
1270
+ console.error(`Failed to enqueue scheduled job ${schedule.name}:`, error);
1271
+ }
1272
+ }
1273
+ }
1274
+ }
1275
+ }
1276
+ function createScheduler(queue2, options) {
1277
+ return new JobScheduler(queue2, options);
1278
+ }
1279
+ function defineSchedule(config) {
1280
+ return config;
1281
+ }
1282
+
1283
+ // src/jobs.feature.ts
1284
+ import { defineFeature } from "@contractspec/lib.contracts";
1285
+ var JobsFeature = defineFeature({
1286
+ meta: {
1287
+ key: "jobs",
1288
+ title: "Background Jobs",
1289
+ description: "Background job processing, scheduling, and queue management",
1290
+ domain: "platform",
1291
+ owners: ["@platform.jobs"],
1292
+ tags: ["jobs", "queue", "background", "scheduler"],
1293
+ stability: "stable",
1294
+ version: "1.0.0"
1295
+ },
1296
+ operations: [
1297
+ { key: "jobs.enqueue", version: "1.0.0" },
1298
+ { key: "jobs.cancel", version: "1.0.0" },
1299
+ { key: "jobs.get", version: "1.0.0" },
1300
+ { key: "jobs.stats", version: "1.0.0" },
1301
+ { key: "jobs.schedule.create", version: "1.0.0" },
1302
+ { key: "jobs.schedule.toggle", version: "1.0.0" },
1303
+ { key: "jobs.schedule.list", version: "1.0.0" }
1304
+ ],
1305
+ events: [
1306
+ { key: "job.enqueued", version: "1.0.0" },
1307
+ { key: "job.started", version: "1.0.0" },
1308
+ { key: "job.completed", version: "1.0.0" },
1309
+ { key: "job.failed", version: "1.0.0" },
1310
+ { key: "job.retrying", version: "1.0.0" },
1311
+ { key: "job.dead_lettered", version: "1.0.0" },
1312
+ { key: "job.cancelled", version: "1.0.0" },
1313
+ { key: "scheduler.job_triggered", version: "1.0.0" }
1314
+ ],
1315
+ presentations: [],
1316
+ opToPresentation: [],
1317
+ presentationsTargets: [],
1318
+ capabilities: {
1319
+ provides: [
1320
+ { key: "jobs", version: "1.0.0" },
1321
+ { key: "scheduler", version: "1.0.0" }
1322
+ ],
1323
+ requires: []
1324
+ }
1325
+ });
1326
+ export {
1327
+ registerDefinedJob,
1328
+ registerAllJobs,
1329
+ pingJob,
1330
+ jobsSchemaContribution,
1331
+ jobEntities,
1332
+ defineSchedule,
1333
+ createStorageDocumentHandler,
1334
+ createScheduler,
1335
+ createGmailSyncHandler,
1336
+ calculateBackoff,
1337
+ ToggleScheduledJobContract,
1338
+ ScheduledJobTriggeredEvent,
1339
+ ScheduledJobModel,
1340
+ ScheduledJobEntity,
1341
+ ScalewaySqsJobQueue,
1342
+ QueueStatsModel,
1343
+ PingPayloadSchema,
1344
+ PING_JOB_TYPE,
1345
+ MemoryJobQueue,
1346
+ ListScheduledJobsContract,
1347
+ JobsFeature,
1348
+ JobStatusEnum,
1349
+ JobStartedEvent,
1350
+ JobScheduler,
1351
+ JobRetryingEvent,
1352
+ JobModel,
1353
+ JobFailedEvent,
1354
+ JobExecutionEntity,
1355
+ JobEvents,
1356
+ JobEntity,
1357
+ JobEnqueuedEvent,
1358
+ JobDeadLetteredEvent,
1359
+ JobCompletedEvent,
1360
+ JobCancelledEvent,
1361
+ GetQueueStatsContract,
1362
+ GetJobContract,
1363
+ GcpPubSubQueue,
1364
+ GcpCloudTasksQueue,
1365
+ EnqueueJobContract,
1366
+ DEFAULT_RETRY_POLICY,
1367
+ CreateScheduledJobContract,
1368
+ CancelJobContract
1369
+ };