@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
@@ -0,0 +1,28 @@
1
+ // src/jobs.capability.ts
2
+ import { defineCapability, StabilityEnum } from "@contractspec/lib.contracts";
3
+ var JobsCapability = defineCapability({
4
+ meta: {
5
+ key: "jobs",
6
+ version: "1.0.0",
7
+ kind: "api",
8
+ stability: StabilityEnum.Experimental,
9
+ description: "Background job processing",
10
+ owners: ["@platform.core"],
11
+ tags: ["jobs", "background", "async"]
12
+ }
13
+ });
14
+ var SchedulerCapability = defineCapability({
15
+ meta: {
16
+ key: "scheduler",
17
+ version: "1.0.0",
18
+ kind: "api",
19
+ stability: StabilityEnum.Experimental,
20
+ description: "Scheduled job execution",
21
+ owners: ["@platform.core"],
22
+ tags: ["scheduler", "cron", "jobs"]
23
+ }
24
+ });
25
+ export {
26
+ SchedulerCapability,
27
+ JobsCapability
28
+ };
@@ -0,0 +1,46 @@
1
+ // src/jobs.feature.ts
2
+ import { defineFeature } from "@contractspec/lib.contracts";
3
+ var JobsFeature = defineFeature({
4
+ meta: {
5
+ key: "jobs",
6
+ title: "Background Jobs",
7
+ description: "Background job processing, scheduling, and queue management",
8
+ domain: "platform",
9
+ owners: ["@platform.jobs"],
10
+ tags: ["jobs", "queue", "background", "scheduler"],
11
+ stability: "stable",
12
+ version: "1.0.0"
13
+ },
14
+ operations: [
15
+ { key: "jobs.enqueue", version: "1.0.0" },
16
+ { key: "jobs.cancel", version: "1.0.0" },
17
+ { key: "jobs.get", version: "1.0.0" },
18
+ { key: "jobs.stats", version: "1.0.0" },
19
+ { key: "jobs.schedule.create", version: "1.0.0" },
20
+ { key: "jobs.schedule.toggle", version: "1.0.0" },
21
+ { key: "jobs.schedule.list", version: "1.0.0" }
22
+ ],
23
+ events: [
24
+ { key: "job.enqueued", version: "1.0.0" },
25
+ { key: "job.started", version: "1.0.0" },
26
+ { key: "job.completed", version: "1.0.0" },
27
+ { key: "job.failed", version: "1.0.0" },
28
+ { key: "job.retrying", version: "1.0.0" },
29
+ { key: "job.dead_lettered", version: "1.0.0" },
30
+ { key: "job.cancelled", version: "1.0.0" },
31
+ { key: "scheduler.job_triggered", version: "1.0.0" }
32
+ ],
33
+ presentations: [],
34
+ opToPresentation: [],
35
+ presentationsTargets: [],
36
+ capabilities: {
37
+ provides: [
38
+ { key: "jobs", version: "1.0.0" },
39
+ { key: "scheduler", version: "1.0.0" }
40
+ ],
41
+ requires: []
42
+ }
43
+ });
44
+ export {
45
+ JobsFeature
46
+ };
@@ -0,0 +1,66 @@
1
+ // src/queue/types.ts
2
+ export * from "@contractspec/lib.contracts/jobs/queue";
3
+ import {
4
+ calculateBackoff,
5
+ DEFAULT_RETRY_POLICY
6
+ } from "@contractspec/lib.contracts/jobs/queue";
7
+
8
+ // src/queue/gcp-cloud-tasks.ts
9
+ import { randomUUID } from "node:crypto";
10
+ class GcpCloudTasksQueue {
11
+ options;
12
+ handlers = new Map;
13
+ constructor(options) {
14
+ this.options = options;
15
+ }
16
+ async enqueue(jobType, payload, options = {}) {
17
+ const now = new Date;
18
+ const enqueueTime = options.delaySeconds != null ? { seconds: Math.floor(Date.now() / 1000) + options.delaySeconds } : undefined;
19
+ const body = Buffer.from(JSON.stringify({
20
+ id: randomUUID(),
21
+ type: jobType,
22
+ payload
23
+ }), "utf-8");
24
+ await this.options.client.createTask({
25
+ parent: `projects/${this.options.projectId}/locations/${this.options.location}/queues/${this.options.queue}`,
26
+ task: {
27
+ httpRequest: {
28
+ httpMethod: "POST",
29
+ url: this.options.resolveUrl(jobType),
30
+ body,
31
+ headers: { "Content-Type": "application/json" },
32
+ oidcToken: this.options.serviceAccountEmail ? { serviceAccountEmail: this.options.serviceAccountEmail } : undefined
33
+ },
34
+ scheduleTime: enqueueTime
35
+ }
36
+ });
37
+ return {
38
+ id: randomUUID(),
39
+ type: jobType,
40
+ version: "1.0.0",
41
+ payload,
42
+ status: "pending",
43
+ priority: options.priority ?? 0,
44
+ attempts: 0,
45
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
46
+ createdAt: now,
47
+ updatedAt: now,
48
+ scheduledAt: options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now,
49
+ dedupeKey: options.dedupeKey,
50
+ tenantId: options.tenantId,
51
+ userId: options.userId,
52
+ traceId: options.traceId,
53
+ metadata: options.metadata
54
+ };
55
+ }
56
+ register(jobType, handler) {
57
+ this.handlers.set(jobType, handler);
58
+ }
59
+ start() {}
60
+ async stop() {
61
+ this.handlers.clear();
62
+ }
63
+ }
64
+ export {
65
+ GcpCloudTasksQueue
66
+ };
@@ -0,0 +1,54 @@
1
+ // src/queue/types.ts
2
+ export * from "@contractspec/lib.contracts/jobs/queue";
3
+ import {
4
+ calculateBackoff,
5
+ DEFAULT_RETRY_POLICY
6
+ } from "@contractspec/lib.contracts/jobs/queue";
7
+
8
+ // src/queue/gcp-pubsub.ts
9
+ import { randomUUID } from "node:crypto";
10
+ class GcpPubSubQueue {
11
+ options;
12
+ handlers = new Map;
13
+ constructor(options) {
14
+ this.options = options;
15
+ }
16
+ async enqueue(jobType, payload, options = {}) {
17
+ const now = new Date;
18
+ await this.options.client.topic(this.options.topicName).publishMessage({
19
+ data: Buffer.from(JSON.stringify({
20
+ id: randomUUID(),
21
+ type: jobType,
22
+ payload
23
+ }), "utf-8")
24
+ });
25
+ return {
26
+ id: randomUUID(),
27
+ type: jobType,
28
+ version: "1.0.0",
29
+ payload,
30
+ status: "pending",
31
+ priority: options.priority ?? 0,
32
+ attempts: 0,
33
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
34
+ createdAt: now,
35
+ updatedAt: now,
36
+ scheduledAt: options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now,
37
+ dedupeKey: options.dedupeKey,
38
+ tenantId: options.tenantId,
39
+ userId: options.userId,
40
+ traceId: options.traceId,
41
+ metadata: options.metadata
42
+ };
43
+ }
44
+ register(jobType, handler) {
45
+ this.handlers.set(jobType, handler);
46
+ }
47
+ start() {}
48
+ async stop() {
49
+ this.handlers.clear();
50
+ }
51
+ }
52
+ export {
53
+ GcpPubSubQueue
54
+ };
@@ -0,0 +1,478 @@
1
+ // src/queue/register-defined-job.ts
2
+ function registerDefinedJob(queue, def) {
3
+ const wrapped = async (job) => {
4
+ const payload = def.schema.parse(job.payload);
5
+ const typedJob = {
6
+ ...job,
7
+ payload
8
+ };
9
+ await def.handler(payload, typedJob);
10
+ };
11
+ queue.register(def.type, wrapped);
12
+ }
13
+
14
+ // src/queue/types.ts
15
+ export * from "@contractspec/lib.contracts/jobs/queue";
16
+ import {
17
+ calculateBackoff,
18
+ DEFAULT_RETRY_POLICY
19
+ } from "@contractspec/lib.contracts/jobs/queue";
20
+
21
+ // src/queue/memory-queue.ts
22
+ import { randomUUID } from "node:crypto";
23
+ class MemoryJobQueue {
24
+ jobs = new Map;
25
+ handlers = new Map;
26
+ timer;
27
+ activeCount = 0;
28
+ pollIntervalMs;
29
+ concurrency;
30
+ retryPolicy;
31
+ constructor(options = {}) {
32
+ this.pollIntervalMs = options.pollIntervalMs ?? 200;
33
+ this.concurrency = options.concurrency ?? 5;
34
+ this.retryPolicy = options.retryPolicy ?? DEFAULT_RETRY_POLICY;
35
+ }
36
+ async enqueue(jobType, payload, options = {}) {
37
+ if (options.dedupeKey) {
38
+ const existing = Array.from(this.jobs.values()).find((j) => j.dedupeKey === options.dedupeKey && j.status === "pending");
39
+ if (existing) {
40
+ return existing;
41
+ }
42
+ }
43
+ const now = new Date;
44
+ const scheduledAt = options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now;
45
+ const job = {
46
+ id: randomUUID(),
47
+ type: jobType,
48
+ version: "1.0.0",
49
+ payload,
50
+ status: "pending",
51
+ priority: options.priority ?? 0,
52
+ attempts: 0,
53
+ maxRetries: options.maxRetries ?? this.retryPolicy.maxRetries,
54
+ createdAt: now,
55
+ updatedAt: now,
56
+ scheduledAt,
57
+ dedupeKey: options.dedupeKey,
58
+ tenantId: options.tenantId,
59
+ userId: options.userId,
60
+ traceId: options.traceId,
61
+ metadata: options.metadata
62
+ };
63
+ if (options.timeoutMs) {
64
+ job.timeoutAt = new Date(now.getTime() + options.timeoutMs);
65
+ }
66
+ this.jobs.set(job.id, job);
67
+ return job;
68
+ }
69
+ register(jobType, handler) {
70
+ this.handlers.set(jobType, handler);
71
+ }
72
+ start() {
73
+ if (this.timer)
74
+ return;
75
+ this.timer = setInterval(() => {
76
+ this.processNext();
77
+ }, this.pollIntervalMs);
78
+ }
79
+ async stop() {
80
+ if (this.timer) {
81
+ clearInterval(this.timer);
82
+ this.timer = undefined;
83
+ }
84
+ while (this.activeCount > 0) {
85
+ await new Promise((resolve) => setTimeout(resolve, 50));
86
+ }
87
+ }
88
+ async getJob(jobId) {
89
+ return this.jobs.get(jobId) ?? null;
90
+ }
91
+ async cancelJob(jobId) {
92
+ const job = this.jobs.get(jobId);
93
+ if (!job || job.status !== "pending") {
94
+ return false;
95
+ }
96
+ job.status = "cancelled";
97
+ job.updatedAt = new Date;
98
+ return true;
99
+ }
100
+ async getStats() {
101
+ const stats = {
102
+ pending: 0,
103
+ running: 0,
104
+ completed: 0,
105
+ failed: 0,
106
+ deadLetter: 0
107
+ };
108
+ for (const job of this.jobs.values()) {
109
+ switch (job.status) {
110
+ case "pending":
111
+ stats.pending++;
112
+ break;
113
+ case "running":
114
+ stats.running++;
115
+ break;
116
+ case "completed":
117
+ stats.completed++;
118
+ break;
119
+ case "failed":
120
+ stats.failed++;
121
+ break;
122
+ case "dead_letter":
123
+ stats.deadLetter++;
124
+ break;
125
+ }
126
+ }
127
+ return stats;
128
+ }
129
+ async processNext() {
130
+ if (this.activeCount >= this.concurrency)
131
+ return;
132
+ const now = new Date;
133
+ const pendingJobs = Array.from(this.jobs.values()).filter((j) => j.status === "pending" && (!j.scheduledAt || j.scheduledAt <= now)).sort((a, b) => {
134
+ if (a.priority !== b.priority) {
135
+ return b.priority - a.priority;
136
+ }
137
+ return (a.scheduledAt?.getTime() ?? 0) - (b.scheduledAt?.getTime() ?? 0);
138
+ });
139
+ const job = pendingJobs[0];
140
+ if (!job)
141
+ return;
142
+ const handler = this.handlers.get(job.type);
143
+ if (!handler)
144
+ return;
145
+ this.activeCount++;
146
+ job.status = "running";
147
+ job.startedAt = new Date;
148
+ job.updatedAt = new Date;
149
+ job.attempts += 1;
150
+ try {
151
+ const result = await handler(job);
152
+ job.status = "completed";
153
+ job.completedAt = new Date;
154
+ job.result = result;
155
+ } catch (error) {
156
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
157
+ job.lastError = errorMessage;
158
+ if (job.attempts >= job.maxRetries) {
159
+ job.status = "dead_letter";
160
+ } else {
161
+ const backoff = calculateBackoff(job.attempts, this.retryPolicy);
162
+ job.status = "pending";
163
+ job.scheduledAt = new Date(Date.now() + backoff);
164
+ }
165
+ } finally {
166
+ job.updatedAt = new Date;
167
+ this.activeCount--;
168
+ }
169
+ }
170
+ }
171
+
172
+ // src/queue/scaleway-sqs-queue.ts
173
+ import { randomUUID as randomUUID2 } from "node:crypto";
174
+ import {
175
+ DeleteMessageCommand,
176
+ ReceiveMessageCommand,
177
+ SendMessageCommand,
178
+ SQSClient
179
+ } from "@aws-sdk/client-sqs";
180
+ class ScalewaySqsJobQueue {
181
+ sqs;
182
+ queueUrl;
183
+ waitTimeSeconds;
184
+ maxNumberOfMessages;
185
+ visibilityTimeoutSeconds;
186
+ handlers = new Map;
187
+ logger;
188
+ running = false;
189
+ constructor(config) {
190
+ this.logger = config.logger;
191
+ const accessKeyId = config.credentials?.accessKeyId ?? process.env.SCALEWAY_ACCESS_KEY_QUEUE;
192
+ const secretAccessKey = config.credentials?.secretAccessKey ?? process.env.SCALEWAY_SECRET_KEY_QUEUE;
193
+ if (!accessKeyId || !secretAccessKey) {
194
+ throw new Error("Missing SCALEWAY_ACCESS_KEY_QUEUE / SCALEWAY_SECRET_KEY_QUEUE in env");
195
+ }
196
+ const region = config.region ?? process.env.SCALEWAY_REGION ?? "par";
197
+ const endpoint = config.endpoint ?? "https://sqs.mnq.fr-par.scaleway.com";
198
+ this.sqs = new SQSClient({
199
+ region,
200
+ endpoint,
201
+ credentials: {
202
+ accessKeyId,
203
+ secretAccessKey
204
+ }
205
+ });
206
+ this.queueUrl = config.queueUrl;
207
+ this.waitTimeSeconds = config.waitTimeSeconds ?? 20;
208
+ this.maxNumberOfMessages = config.maxNumberOfMessages ?? 5;
209
+ this.visibilityTimeoutSeconds = config.visibilityTimeoutSeconds ?? 60;
210
+ }
211
+ async enqueue(jobType, payload, options = {}) {
212
+ const id = randomUUID2();
213
+ const now = new Date;
214
+ const scheduledAt = options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now;
215
+ const envelope = {
216
+ id,
217
+ type: jobType,
218
+ payload
219
+ };
220
+ await this.sqs.send(new SendMessageCommand({
221
+ QueueUrl: this.queueUrl,
222
+ MessageBody: JSON.stringify(envelope),
223
+ DelaySeconds: options.delaySeconds ?? 0
224
+ }));
225
+ return {
226
+ id,
227
+ type: jobType,
228
+ version: "1.0.0",
229
+ payload,
230
+ status: "pending",
231
+ priority: options.priority ?? 0,
232
+ attempts: 0,
233
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
234
+ createdAt: now,
235
+ updatedAt: now,
236
+ scheduledAt,
237
+ dedupeKey: options.dedupeKey,
238
+ tenantId: options.tenantId,
239
+ userId: options.userId,
240
+ traceId: options.traceId,
241
+ metadata: options.metadata
242
+ };
243
+ }
244
+ register(jobType, handler) {
245
+ if (this.handlers.has(jobType)) {
246
+ throw new Error(`Handler already registered for job type "${jobType}"`);
247
+ }
248
+ this.handlers.set(jobType, handler);
249
+ }
250
+ start() {
251
+ if (this.running)
252
+ return;
253
+ this.running = true;
254
+ this.pollLoop().catch((error) => {
255
+ this.logger?.error?.("jobs.queue.scaleway_sqs.poll_loop_fatal", {
256
+ error: error instanceof Error ? error.message : String(error)
257
+ });
258
+ this.running = false;
259
+ });
260
+ }
261
+ async stop() {
262
+ this.running = false;
263
+ }
264
+ async pollLoop() {
265
+ this.logger?.info?.("jobs.queue.scaleway_sqs.started", {
266
+ queueUrl: this.queueUrl
267
+ });
268
+ while (this.running) {
269
+ try {
270
+ const res = await this.sqs.send(new ReceiveMessageCommand({
271
+ QueueUrl: this.queueUrl,
272
+ MaxNumberOfMessages: this.maxNumberOfMessages,
273
+ WaitTimeSeconds: this.waitTimeSeconds,
274
+ VisibilityTimeout: this.visibilityTimeoutSeconds,
275
+ MessageSystemAttributeNames: ["ApproximateReceiveCount"]
276
+ }));
277
+ const messages = res.Messages ?? [];
278
+ if (messages.length === 0) {
279
+ continue;
280
+ }
281
+ for (const msg of messages) {
282
+ if (!msg.Body || !msg.ReceiptHandle) {
283
+ this.logger?.warn?.("jobs.queue.scaleway_sqs.invalid_message", {
284
+ messageId: msg.MessageId,
285
+ reason: "missing_body_or_receipt"
286
+ });
287
+ continue;
288
+ }
289
+ let envelope;
290
+ try {
291
+ envelope = JSON.parse(msg.Body);
292
+ } catch (err) {
293
+ this.logger?.warn?.("jobs.queue.scaleway_sqs.parse_failed", {
294
+ messageId: msg.MessageId,
295
+ error: err instanceof Error ? err.message : String(err)
296
+ });
297
+ await this.deleteMessage(msg.ReceiptHandle);
298
+ continue;
299
+ }
300
+ const handler = this.handlers.get(envelope.type);
301
+ if (!handler) {
302
+ this.logger?.warn?.("jobs.queue.scaleway_sqs.missing_handler", {
303
+ jobType: envelope.type,
304
+ messageId: msg.MessageId
305
+ });
306
+ await this.deleteMessage(msg.ReceiptHandle);
307
+ continue;
308
+ }
309
+ const now = new Date;
310
+ const attempts = parseInt(msg.Attributes?.ApproximateReceiveCount ?? "1", 10);
311
+ const job = {
312
+ id: envelope.id,
313
+ type: envelope.type,
314
+ version: "1.0.0",
315
+ payload: envelope.payload,
316
+ status: "pending",
317
+ priority: 0,
318
+ attempts,
319
+ maxRetries: DEFAULT_RETRY_POLICY.maxRetries,
320
+ createdAt: now,
321
+ updatedAt: now
322
+ };
323
+ job.status = "running";
324
+ job.updatedAt = new Date;
325
+ try {
326
+ await handler(job);
327
+ job.status = "completed";
328
+ job.updatedAt = new Date;
329
+ await this.deleteMessage(msg.ReceiptHandle);
330
+ } catch (err) {
331
+ job.status = "failed";
332
+ job.lastError = err instanceof Error ? err.message : "Unknown job error";
333
+ job.updatedAt = new Date;
334
+ this.logger?.error?.("jobs.queue.scaleway_sqs.job_failed", {
335
+ jobType: job.type,
336
+ jobId: job.id,
337
+ error: err instanceof Error ? err.message : String(err)
338
+ });
339
+ }
340
+ }
341
+ } catch (err) {
342
+ this.logger?.error?.("jobs.queue.scaleway_sqs.poll_error", {
343
+ error: err instanceof Error ? err.message : String(err)
344
+ });
345
+ await this.sleep(5000);
346
+ }
347
+ }
348
+ this.logger?.info?.("jobs.queue.scaleway_sqs.stopped", {
349
+ queueUrl: this.queueUrl
350
+ });
351
+ }
352
+ async deleteMessage(receiptHandle) {
353
+ try {
354
+ await this.sqs.send(new DeleteMessageCommand({
355
+ QueueUrl: this.queueUrl,
356
+ ReceiptHandle: receiptHandle
357
+ }));
358
+ } catch (err) {
359
+ this.logger?.warn?.("jobs.queue.scaleway_sqs.delete_failed", {
360
+ error: err instanceof Error ? err.message : String(err)
361
+ });
362
+ }
363
+ }
364
+ async sleep(ms) {
365
+ await new Promise((resolve) => setTimeout(resolve, ms));
366
+ }
367
+ }
368
+
369
+ // src/queue/gcp-cloud-tasks.ts
370
+ import { randomUUID as randomUUID3 } from "node:crypto";
371
+ class GcpCloudTasksQueue {
372
+ options;
373
+ handlers = new Map;
374
+ constructor(options) {
375
+ this.options = options;
376
+ }
377
+ async enqueue(jobType, payload, options = {}) {
378
+ const now = new Date;
379
+ const enqueueTime = options.delaySeconds != null ? { seconds: Math.floor(Date.now() / 1000) + options.delaySeconds } : undefined;
380
+ const body = Buffer.from(JSON.stringify({
381
+ id: randomUUID3(),
382
+ type: jobType,
383
+ payload
384
+ }), "utf-8");
385
+ await this.options.client.createTask({
386
+ parent: `projects/${this.options.projectId}/locations/${this.options.location}/queues/${this.options.queue}`,
387
+ task: {
388
+ httpRequest: {
389
+ httpMethod: "POST",
390
+ url: this.options.resolveUrl(jobType),
391
+ body,
392
+ headers: { "Content-Type": "application/json" },
393
+ oidcToken: this.options.serviceAccountEmail ? { serviceAccountEmail: this.options.serviceAccountEmail } : undefined
394
+ },
395
+ scheduleTime: enqueueTime
396
+ }
397
+ });
398
+ return {
399
+ id: randomUUID3(),
400
+ type: jobType,
401
+ version: "1.0.0",
402
+ payload,
403
+ status: "pending",
404
+ priority: options.priority ?? 0,
405
+ attempts: 0,
406
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
407
+ createdAt: now,
408
+ updatedAt: now,
409
+ scheduledAt: options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now,
410
+ dedupeKey: options.dedupeKey,
411
+ tenantId: options.tenantId,
412
+ userId: options.userId,
413
+ traceId: options.traceId,
414
+ metadata: options.metadata
415
+ };
416
+ }
417
+ register(jobType, handler) {
418
+ this.handlers.set(jobType, handler);
419
+ }
420
+ start() {}
421
+ async stop() {
422
+ this.handlers.clear();
423
+ }
424
+ }
425
+
426
+ // src/queue/gcp-pubsub.ts
427
+ import { randomUUID as randomUUID4 } from "node:crypto";
428
+ class GcpPubSubQueue {
429
+ options;
430
+ handlers = new Map;
431
+ constructor(options) {
432
+ this.options = options;
433
+ }
434
+ async enqueue(jobType, payload, options = {}) {
435
+ const now = new Date;
436
+ await this.options.client.topic(this.options.topicName).publishMessage({
437
+ data: Buffer.from(JSON.stringify({
438
+ id: randomUUID4(),
439
+ type: jobType,
440
+ payload
441
+ }), "utf-8")
442
+ });
443
+ return {
444
+ id: randomUUID4(),
445
+ type: jobType,
446
+ version: "1.0.0",
447
+ payload,
448
+ status: "pending",
449
+ priority: options.priority ?? 0,
450
+ attempts: 0,
451
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
452
+ createdAt: now,
453
+ updatedAt: now,
454
+ scheduledAt: options.delaySeconds ? new Date(now.getTime() + options.delaySeconds * 1000) : now,
455
+ dedupeKey: options.dedupeKey,
456
+ tenantId: options.tenantId,
457
+ userId: options.userId,
458
+ traceId: options.traceId,
459
+ metadata: options.metadata
460
+ };
461
+ }
462
+ register(jobType, handler) {
463
+ this.handlers.set(jobType, handler);
464
+ }
465
+ start() {}
466
+ async stop() {
467
+ this.handlers.clear();
468
+ }
469
+ }
470
+ export {
471
+ registerDefinedJob,
472
+ calculateBackoff,
473
+ ScalewaySqsJobQueue,
474
+ MemoryJobQueue,
475
+ GcpPubSubQueue,
476
+ GcpCloudTasksQueue,
477
+ DEFAULT_RETRY_POLICY
478
+ };