@microfox/ai-worker 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/handler.js CHANGED
@@ -20,9 +20,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/handler.ts
21
21
  var handler_exports = {};
22
22
  __export(handler_exports, {
23
- createLambdaHandler: () => createLambdaHandler
23
+ SQS_MAX_DELAY_SECONDS: () => SQS_MAX_DELAY_SECONDS,
24
+ createLambdaHandler: () => createLambdaHandler,
25
+ createWorkerLogger: () => createWorkerLogger,
26
+ wrapHandlerForQueue: () => wrapHandlerForQueue
24
27
  });
25
28
  module.exports = __toCommonJS(handler_exports);
29
+ var import_client_sqs = require("@aws-sdk/client-sqs");
26
30
 
27
31
  // src/mongoJobStore.ts
28
32
  var import_mongodb = require("mongodb");
@@ -49,6 +53,21 @@ async function getCollection() {
49
53
  const client = await getClient();
50
54
  return client.db(dbName).collection(collectionName);
51
55
  }
56
+ async function getJobById(jobId) {
57
+ try {
58
+ const coll = await getCollection();
59
+ const doc = await coll.findOne({ _id: jobId });
60
+ if (!doc) return null;
61
+ const { _id, ...r } = doc;
62
+ return r;
63
+ } catch (e) {
64
+ console.error("[Worker] MongoDB getJobById failed:", {
65
+ jobId,
66
+ error: e?.message ?? String(e)
67
+ });
68
+ return null;
69
+ }
70
+ }
52
71
  function createMongoJobStore(workerId, jobId, input, metadata) {
53
72
  return {
54
73
  update: async (update) => {
@@ -120,6 +139,36 @@ function createMongoJobStore(workerId, jobId, input, metadata) {
120
139
  });
121
140
  return null;
122
141
  }
142
+ },
143
+ appendInternalJob: async (entry) => {
144
+ try {
145
+ const coll = await getCollection();
146
+ await coll.updateOne(
147
+ { _id: jobId },
148
+ { $push: { internalJobs: entry } }
149
+ );
150
+ } catch (e) {
151
+ console.error("[Worker] MongoDB job store appendInternalJob failed:", {
152
+ jobId,
153
+ workerId,
154
+ error: e?.message ?? String(e)
155
+ });
156
+ }
157
+ },
158
+ getJob: async (otherJobId) => {
159
+ try {
160
+ const coll = await getCollection();
161
+ const doc = await coll.findOne({ _id: otherJobId });
162
+ if (!doc) return null;
163
+ const { _id, ...r } = doc;
164
+ return r;
165
+ } catch (e) {
166
+ console.error("[Worker] MongoDB job store getJob failed:", {
167
+ otherJobId,
168
+ error: e?.message ?? String(e)
169
+ });
170
+ return null;
171
+ }
123
172
  }
124
173
  };
125
174
  }
@@ -147,7 +196,696 @@ function isMongoJobStoreConfigured() {
147
196
  return Boolean(uri?.trim());
148
197
  }
149
198
 
199
+ // src/redisJobStore.ts
200
+ var import_redis = require("@upstash/redis");
201
+ var redisUrl = process.env.WORKER_UPSTASH_REDIS_REST_URL || process.env.UPSTASH_REDIS_REST_URL || process.env.UPSTASH_REDIS_URL;
202
+ var redisToken = process.env.WORKER_UPSTASH_REDIS_REST_TOKEN || process.env.UPSTASH_REDIS_REST_TOKEN || process.env.UPSTASH_REDIS_TOKEN;
203
+ var jobKeyPrefix = process.env.WORKER_UPSTASH_REDIS_JOBS_PREFIX || process.env.UPSTASH_REDIS_KEY_PREFIX || process.env.REDIS_WORKER_JOB_PREFIX || "worker:jobs:";
204
+ var defaultTtlSeconds = 60 * 60 * 24 * 7;
205
+ var jobTtlSeconds = typeof process.env.WORKER_JOBS_TTL_SECONDS === "string" ? parseInt(process.env.WORKER_JOBS_TTL_SECONDS, 10) || defaultTtlSeconds : typeof process.env.REDIS_WORKER_JOB_TTL_SECONDS === "string" ? parseInt(process.env.REDIS_WORKER_JOB_TTL_SECONDS, 10) || defaultTtlSeconds : typeof process.env.WORKFLOW_JOBS_TTL_SECONDS === "string" ? parseInt(process.env.WORKFLOW_JOBS_TTL_SECONDS, 10) || defaultTtlSeconds : defaultTtlSeconds;
206
+ var redisClient = null;
207
+ function getRedis() {
208
+ if (!redisUrl || !redisToken) {
209
+ throw new Error(
210
+ "Upstash Redis configuration missing. Set WORKER_UPSTASH_REDIS_REST_URL and WORKER_UPSTASH_REDIS_REST_TOKEN (or UPSTASH_REDIS_REST_URL/UPSTASH_REDIS_REST_TOKEN)."
211
+ );
212
+ }
213
+ if (!redisClient) {
214
+ redisClient = new import_redis.Redis({
215
+ url: redisUrl,
216
+ token: redisToken
217
+ });
218
+ }
219
+ return redisClient;
220
+ }
221
+ function jobKey(jobId) {
222
+ return `${jobKeyPrefix}${jobId}`;
223
+ }
224
+ function internalListKey(jobId) {
225
+ return `${jobKeyPrefix}${jobId}:internal`;
226
+ }
227
+ function isRedisJobStoreConfigured() {
228
+ return Boolean((redisUrl || "").trim() && (redisToken || "").trim());
229
+ }
230
+ async function loadJob(jobId) {
231
+ const redis = getRedis();
232
+ const key = jobKey(jobId);
233
+ const data = await redis.hgetall(key);
234
+ if (!data || Object.keys(data).length === 0) return null;
235
+ const parseJson = (val) => {
236
+ if (!val) return void 0;
237
+ try {
238
+ return JSON.parse(val);
239
+ } catch {
240
+ return void 0;
241
+ }
242
+ };
243
+ const listKey = internalListKey(jobId);
244
+ const listItems = await redis.lrange(listKey, 0, -1);
245
+ let internalJobs;
246
+ if (listItems && listItems.length > 0) {
247
+ internalJobs = listItems.map((s) => {
248
+ try {
249
+ return JSON.parse(s);
250
+ } catch {
251
+ return null;
252
+ }
253
+ }).filter(Boolean);
254
+ } else {
255
+ internalJobs = parseJson(data.internalJobs);
256
+ }
257
+ const record = {
258
+ jobId: data.jobId,
259
+ workerId: data.workerId,
260
+ status: data.status || "queued",
261
+ input: parseJson(data.input) ?? {},
262
+ output: parseJson(data.output),
263
+ error: parseJson(data.error),
264
+ metadata: parseJson(data.metadata) ?? {},
265
+ internalJobs,
266
+ createdAt: data.createdAt,
267
+ updatedAt: data.updatedAt,
268
+ completedAt: data.completedAt
269
+ };
270
+ return record;
271
+ }
272
+ function createRedisJobStore(workerId, jobId, input, metadata) {
273
+ return {
274
+ update: async (update) => {
275
+ const redis = getRedis();
276
+ const key = jobKey(jobId);
277
+ const now = (/* @__PURE__ */ new Date()).toISOString();
278
+ const existing = await loadJob(jobId);
279
+ const next = {};
280
+ const mergedMeta = { ...existing?.metadata ?? {} };
281
+ if (update.metadata) {
282
+ Object.assign(mergedMeta, update.metadata);
283
+ }
284
+ if (update.progress !== void 0 || update.progressMessage !== void 0) {
285
+ mergedMeta.progress = update.progress;
286
+ mergedMeta.progressMessage = update.progressMessage;
287
+ }
288
+ next.metadata = mergedMeta;
289
+ if (update.status !== void 0) {
290
+ next.status = update.error ? "failed" : update.status;
291
+ if ((update.status === "completed" || update.status === "failed") && !existing?.completedAt) {
292
+ next.completedAt = now;
293
+ }
294
+ }
295
+ if (update.output !== void 0) next.output = update.output;
296
+ if (update.error !== void 0) next.error = update.error;
297
+ const toSet = {};
298
+ if (next.status) toSet["status"] = String(next.status);
299
+ if (next.output !== void 0) toSet["output"] = JSON.stringify(next.output);
300
+ if (next.error !== void 0) toSet["error"] = JSON.stringify(next.error);
301
+ if (next.metadata !== void 0) toSet["metadata"] = JSON.stringify(next.metadata);
302
+ if (next.completedAt) {
303
+ toSet["completedAt"] = next.completedAt;
304
+ }
305
+ toSet["updatedAt"] = now;
306
+ await redis.hset(key, toSet);
307
+ if (jobTtlSeconds > 0) {
308
+ await redis.expire(key, jobTtlSeconds);
309
+ }
310
+ },
311
+ get: async () => {
312
+ return loadJob(jobId);
313
+ },
314
+ appendInternalJob: async (entry) => {
315
+ const redis = getRedis();
316
+ const listKey = internalListKey(jobId);
317
+ await redis.rpush(listKey, JSON.stringify(entry));
318
+ const mainKey = jobKey(jobId);
319
+ await redis.hset(mainKey, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
320
+ if (jobTtlSeconds > 0) {
321
+ await redis.expire(listKey, jobTtlSeconds);
322
+ await redis.expire(mainKey, jobTtlSeconds);
323
+ }
324
+ },
325
+ getJob: async (otherJobId) => {
326
+ return loadJob(otherJobId);
327
+ }
328
+ };
329
+ }
330
+ async function upsertRedisJob(jobId, workerId, input, metadata) {
331
+ const redis = getRedis();
332
+ const key = jobKey(jobId);
333
+ const now = (/* @__PURE__ */ new Date()).toISOString();
334
+ const doc = {
335
+ jobId,
336
+ workerId,
337
+ status: "queued",
338
+ input,
339
+ metadata,
340
+ createdAt: now,
341
+ updatedAt: now
342
+ };
343
+ const toSet = {
344
+ jobId,
345
+ workerId,
346
+ status: doc.status,
347
+ input: JSON.stringify(doc.input ?? {}),
348
+ metadata: JSON.stringify(doc.metadata ?? {}),
349
+ createdAt: now,
350
+ updatedAt: now
351
+ };
352
+ await redis.hset(key, toSet);
353
+ if (jobTtlSeconds > 0) {
354
+ await redis.expire(key, jobTtlSeconds);
355
+ }
356
+ }
357
+
358
+ // src/queueJobStore.ts
359
+ var import_redis2 = require("@upstash/redis");
360
+ var import_mongodb2 = require("mongodb");
361
+ var mongoUri = process.env.DATABASE_MONGODB_URI || process.env.MONGODB_URI;
362
+ var mongoDbName = process.env.DATABASE_MONGODB_DB || process.env.MONGODB_DB || "mediamake";
363
+ var mongoQueueCollectionName = process.env.MONGODB_QUEUE_JOBS_COLLECTION || "queue_jobs";
364
+ var mongoClientPromise = null;
365
+ async function getMongoClient() {
366
+ if (!mongoUri) {
367
+ throw new Error(
368
+ "MongoDB URI required for queue job store. Set DATABASE_MONGODB_URI or MONGODB_URI."
369
+ );
370
+ }
371
+ if (!mongoClientPromise) {
372
+ mongoClientPromise = new import_mongodb2.MongoClient(mongoUri, {
373
+ maxPoolSize: 10,
374
+ minPoolSize: 0,
375
+ serverSelectionTimeoutMS: 1e4
376
+ }).connect();
377
+ }
378
+ return mongoClientPromise;
379
+ }
380
+ async function getMongoQueueCollection() {
381
+ const client = await getMongoClient();
382
+ return client.db(mongoDbName).collection(mongoQueueCollectionName);
383
+ }
384
+ var redisUrl2 = process.env.WORKER_UPSTASH_REDIS_REST_URL || process.env.UPSTASH_REDIS_REST_URL || process.env.UPSTASH_REDIS_URL;
385
+ var redisToken2 = process.env.WORKER_UPSTASH_REDIS_REST_TOKEN || process.env.UPSTASH_REDIS_REST_TOKEN || process.env.UPSTASH_REDIS_TOKEN;
386
+ var queueKeyPrefix = process.env.WORKER_UPSTASH_REDIS_QUEUE_PREFIX || process.env.UPSTASH_REDIS_QUEUE_PREFIX || "worker:queue-jobs:";
387
+ var defaultTtlSeconds2 = 60 * 60 * 24 * 7;
388
+ var queueJobTtlSeconds = typeof process.env.WORKER_QUEUE_JOBS_TTL_SECONDS === "string" ? parseInt(process.env.WORKER_QUEUE_JOBS_TTL_SECONDS, 10) || defaultTtlSeconds2 : typeof process.env.WORKER_JOBS_TTL_SECONDS === "string" ? parseInt(process.env.WORKER_JOBS_TTL_SECONDS, 10) || defaultTtlSeconds2 : defaultTtlSeconds2;
389
+ var redisClient2 = null;
390
+ function getRedis2() {
391
+ if (!redisUrl2 || !redisToken2) {
392
+ throw new Error(
393
+ "Upstash Redis configuration missing for queue job store. Set WORKER_UPSTASH_REDIS_REST_URL and WORKER_UPSTASH_REDIS_REST_TOKEN (or UPSTASH_REDIS_REST_URL/UPSTASH_REDIS_REST_TOKEN)."
394
+ );
395
+ }
396
+ if (!redisClient2) {
397
+ redisClient2 = new import_redis2.Redis({
398
+ url: redisUrl2,
399
+ token: redisToken2
400
+ });
401
+ }
402
+ return redisClient2;
403
+ }
404
+ function queueKey(id) {
405
+ return `${queueKeyPrefix}${id}`;
406
+ }
407
+ function stepsFromHash(val) {
408
+ if (Array.isArray(val)) return val;
409
+ if (typeof val === "string") {
410
+ try {
411
+ const parsed = JSON.parse(val);
412
+ return Array.isArray(parsed) ? parsed : [];
413
+ } catch {
414
+ return [];
415
+ }
416
+ }
417
+ return [];
418
+ }
419
+ function metadataFromHash(val) {
420
+ if (val && typeof val === "object" && !Array.isArray(val)) return val;
421
+ if (typeof val === "string") {
422
+ try {
423
+ const parsed = JSON.parse(val);
424
+ return parsed && typeof parsed === "object" ? parsed : {};
425
+ } catch {
426
+ return {};
427
+ }
428
+ }
429
+ return {};
430
+ }
431
+ async function loadQueueJobRedis(queueJobId) {
432
+ const redis = getRedis2();
433
+ const key = queueKey(queueJobId);
434
+ const data = await redis.hgetall(key);
435
+ if (!data || typeof data !== "object" || Object.keys(data).length === 0) return null;
436
+ const d = data;
437
+ const record = {
438
+ id: d.id === void 0 ? queueJobId : String(d.id),
439
+ queueId: String(d.queueId ?? ""),
440
+ status: String(d.status ?? "running"),
441
+ steps: stepsFromHash(d.steps),
442
+ metadata: metadataFromHash(d.metadata),
443
+ createdAt: String(d.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()),
444
+ updatedAt: String(d.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()),
445
+ completedAt: d.completedAt != null ? String(d.completedAt) : void 0
446
+ };
447
+ return record;
448
+ }
449
+ async function saveQueueJobRedis(record) {
450
+ const redis = getRedis2();
451
+ const key = queueKey(record.id);
452
+ const now = (/* @__PURE__ */ new Date()).toISOString();
453
+ const toSet = {
454
+ id: record.id,
455
+ queueId: record.queueId,
456
+ status: record.status,
457
+ steps: JSON.stringify(record.steps || []),
458
+ metadata: JSON.stringify(record.metadata || {}),
459
+ createdAt: record.createdAt || now,
460
+ updatedAt: record.updatedAt || now
461
+ };
462
+ if (record.completedAt) {
463
+ toSet.completedAt = record.completedAt;
464
+ }
465
+ await redis.hset(key, toSet);
466
+ if (queueJobTtlSeconds > 0) {
467
+ await redis.expire(key, queueJobTtlSeconds);
468
+ }
469
+ }
470
+ function getStoreType() {
471
+ const t = (process.env.WORKER_DATABASE_TYPE || "upstash-redis").toLowerCase();
472
+ return t === "mongodb" ? "mongodb" : "upstash-redis";
473
+ }
474
+ function preferMongo() {
475
+ return getStoreType() === "mongodb" && Boolean(mongoUri?.trim());
476
+ }
477
+ function preferRedis() {
478
+ return getStoreType() !== "mongodb" && Boolean((redisUrl2 || "").trim() && (redisToken2 || "").trim());
479
+ }
480
+ async function upsertInitialQueueJob(options) {
481
+ const { queueJobId, queueId, firstWorkerId, firstWorkerJobId, metadata } = options;
482
+ const now = (/* @__PURE__ */ new Date()).toISOString();
483
+ if (preferMongo()) {
484
+ const coll = await getMongoQueueCollection();
485
+ const existing = await coll.findOne({ _id: queueJobId });
486
+ if (existing) {
487
+ const steps = existing.steps ?? [];
488
+ if (steps.length === 0) {
489
+ steps.push({
490
+ workerId: firstWorkerId,
491
+ workerJobId: firstWorkerJobId,
492
+ status: "queued"
493
+ });
494
+ }
495
+ await coll.updateOne(
496
+ { _id: queueJobId },
497
+ {
498
+ $set: {
499
+ steps,
500
+ updatedAt: now
501
+ }
502
+ }
503
+ );
504
+ } else {
505
+ const doc = {
506
+ _id: queueJobId,
507
+ id: queueJobId,
508
+ queueId,
509
+ status: "running",
510
+ steps: [
511
+ {
512
+ workerId: firstWorkerId,
513
+ workerJobId: firstWorkerJobId,
514
+ status: "queued"
515
+ }
516
+ ],
517
+ metadata: metadata ?? {},
518
+ createdAt: now,
519
+ updatedAt: now
520
+ };
521
+ await coll.updateOne(
522
+ { _id: queueJobId },
523
+ { $set: doc },
524
+ { upsert: true }
525
+ );
526
+ }
527
+ return;
528
+ }
529
+ if (preferRedis()) {
530
+ const existing = await loadQueueJobRedis(queueJobId);
531
+ if (existing) {
532
+ if (!existing.steps || existing.steps.length === 0) {
533
+ existing.steps = [
534
+ {
535
+ workerId: firstWorkerId,
536
+ workerJobId: firstWorkerJobId,
537
+ status: "queued"
538
+ }
539
+ ];
540
+ }
541
+ existing.updatedAt = now;
542
+ await saveQueueJobRedis(existing);
543
+ } else {
544
+ const record = {
545
+ id: queueJobId,
546
+ queueId,
547
+ status: "running",
548
+ steps: [
549
+ {
550
+ workerId: firstWorkerId,
551
+ workerJobId: firstWorkerJobId,
552
+ status: "queued"
553
+ }
554
+ ],
555
+ metadata: metadata ?? {},
556
+ createdAt: now,
557
+ updatedAt: now
558
+ };
559
+ await saveQueueJobRedis(record);
560
+ }
561
+ }
562
+ }
563
+ async function updateQueueJobStepInStore(options) {
564
+ const { queueJobId, stepIndex, status, input, output, error } = options;
565
+ const now = (/* @__PURE__ */ new Date()).toISOString();
566
+ if (preferMongo()) {
567
+ const coll = await getMongoQueueCollection();
568
+ const existing = await coll.findOne({ _id: queueJobId });
569
+ if (!existing) return;
570
+ const step = existing.steps[stepIndex];
571
+ if (!step) return;
572
+ const mergedStep = {
573
+ ...step,
574
+ status,
575
+ ...input !== void 0 && { input },
576
+ ...output !== void 0 && { output },
577
+ ...error !== void 0 && { error },
578
+ startedAt: step.startedAt ?? (status === "running" ? now : step.startedAt),
579
+ completedAt: step.completedAt ?? (status === "completed" || status === "failed" ? now : step.completedAt)
580
+ };
581
+ const setDoc = {
582
+ steps: existing.steps,
583
+ updatedAt: now
584
+ };
585
+ setDoc.steps[stepIndex] = mergedStep;
586
+ if (status === "failed") {
587
+ setDoc.status = "failed";
588
+ if (!existing.completedAt) setDoc.completedAt = now;
589
+ } else if (status === "completed" && stepIndex === existing.steps.length - 1) {
590
+ setDoc.status = "completed";
591
+ if (!existing.completedAt) setDoc.completedAt = now;
592
+ }
593
+ await coll.updateOne(
594
+ { _id: queueJobId },
595
+ {
596
+ $set: setDoc
597
+ }
598
+ );
599
+ return;
600
+ }
601
+ if (preferRedis()) {
602
+ const existing = await loadQueueJobRedis(queueJobId);
603
+ if (!existing) {
604
+ return;
605
+ }
606
+ const steps = existing.steps || [];
607
+ const step = steps[stepIndex];
608
+ if (!step) {
609
+ return;
610
+ }
611
+ step.status = status;
612
+ if (input !== void 0) step.input = input;
613
+ if (output !== void 0) step.output = output;
614
+ if (error !== void 0) step.error = error;
615
+ if (status === "running") {
616
+ step.startedAt = step.startedAt ?? now;
617
+ }
618
+ if (status === "completed" || status === "failed") {
619
+ step.completedAt = step.completedAt ?? now;
620
+ }
621
+ existing.steps = steps;
622
+ existing.updatedAt = now;
623
+ if (status === "failed") {
624
+ existing.status = "failed";
625
+ existing.completedAt = existing.completedAt ?? now;
626
+ } else if (status === "completed" && stepIndex === steps.length - 1) {
627
+ existing.status = "completed";
628
+ existing.completedAt = existing.completedAt ?? now;
629
+ }
630
+ await saveQueueJobRedis(existing);
631
+ }
632
+ }
633
+ async function appendQueueJobStepInStore(options) {
634
+ const { queueJobId, workerId, workerJobId } = options;
635
+ const now = (/* @__PURE__ */ new Date()).toISOString();
636
+ if (preferMongo()) {
637
+ const coll = await getMongoQueueCollection();
638
+ await coll.updateOne(
639
+ { _id: queueJobId },
640
+ {
641
+ $push: {
642
+ steps: {
643
+ workerId,
644
+ workerJobId,
645
+ status: "queued"
646
+ }
647
+ },
648
+ $set: { updatedAt: now }
649
+ }
650
+ );
651
+ return;
652
+ }
653
+ if (preferRedis()) {
654
+ const existing = await loadQueueJobRedis(queueJobId);
655
+ if (!existing) return;
656
+ const steps = existing.steps || [];
657
+ steps.push({
658
+ workerId,
659
+ workerJobId,
660
+ status: "queued"
661
+ });
662
+ existing.steps = steps;
663
+ existing.updatedAt = now;
664
+ await saveQueueJobRedis(existing);
665
+ }
666
+ }
667
+
150
668
  // src/handler.ts
669
+ var SQS_MAX_DELAY_SECONDS = 900;
670
+ function createWorkerLogger(jobId, workerId) {
671
+ const prefix = (level) => `[${level}] [${workerId}] [${jobId}]`;
672
+ return {
673
+ info(msg, data) {
674
+ console.log(prefix("INFO"), msg, data !== void 0 ? JSON.stringify(data) : "");
675
+ },
676
+ warn(msg, data) {
677
+ console.warn(prefix("WARN"), msg, data !== void 0 ? JSON.stringify(data) : "");
678
+ },
679
+ error(msg, data) {
680
+ console.error(prefix("ERROR"), msg, data !== void 0 ? JSON.stringify(data) : "");
681
+ },
682
+ debug(msg, data) {
683
+ if (process.env.DEBUG || process.env.WORKER_DEBUG) {
684
+ console.debug(prefix("DEBUG"), msg, data !== void 0 ? JSON.stringify(data) : "");
685
+ }
686
+ }
687
+ };
688
+ }
689
+ var WORKER_QUEUE_KEY = "__workerQueue";
690
+ async function notifyQueueJobStep(queueJobId, action, params) {
691
+ try {
692
+ if (action === "append") {
693
+ if (!params.workerId || !params.workerJobId) return;
694
+ await appendQueueJobStepInStore({
695
+ queueJobId,
696
+ workerId: params.workerId,
697
+ workerJobId: params.workerJobId
698
+ });
699
+ if (process.env.DEBUG_WORKER_QUEUES === "1") {
700
+ console.log("[Worker] Queue job step appended", {
701
+ queueJobId,
702
+ workerId: params.workerId,
703
+ workerJobId: params.workerJobId
704
+ });
705
+ }
706
+ return;
707
+ }
708
+ if (params.stepIndex === void 0) return;
709
+ const status = action === "start" ? "running" : action === "complete" ? "completed" : action === "fail" ? "failed" : void 0;
710
+ if (!status) return;
711
+ await updateQueueJobStepInStore({
712
+ queueJobId,
713
+ stepIndex: params.stepIndex,
714
+ workerId: params.workerId || "",
715
+ workerJobId: params.workerJobId,
716
+ status,
717
+ input: params.input,
718
+ output: params.output,
719
+ error: params.error
720
+ });
721
+ console.log("[Worker] Queue job step updated", {
722
+ queueId: params.queueId ?? queueJobId,
723
+ queueJobId,
724
+ stepIndex: params.stepIndex,
725
+ workerId: params.workerId,
726
+ status
727
+ });
728
+ } catch (err) {
729
+ console.warn("[Worker] Queue job update error:", {
730
+ queueJobId,
731
+ action,
732
+ error: err?.message ?? String(err)
733
+ });
734
+ }
735
+ }
736
+ function wrapHandlerForQueue(handler, queueRuntime) {
737
+ return async (params) => {
738
+ const queueContext = params.input?.[WORKER_QUEUE_KEY];
739
+ const output = await handler(params);
740
+ if (!queueContext || typeof queueContext !== "object" || !queueContext.id) {
741
+ return output;
742
+ }
743
+ const { id: queueId, stepIndex, initialInput, queueJobId } = queueContext;
744
+ const jobId = params.ctx?.jobId;
745
+ const workerId = params.ctx?.workerId ?? "";
746
+ const next = queueRuntime.getNextStep(queueId, stepIndex);
747
+ const childJobId = next ? `job-${Date.now()}-${Math.random().toString(36).slice(2, 11)}` : void 0;
748
+ if (next && queueJobId) {
749
+ await notifyQueueJobStep(queueJobId, "append", {
750
+ workerJobId: childJobId,
751
+ workerId: next.workerId
752
+ });
753
+ }
754
+ if (queueJobId && typeof stepIndex === "number") {
755
+ await notifyQueueJobStep(queueJobId, "complete", {
756
+ queueId,
757
+ stepIndex,
758
+ workerJobId: jobId,
759
+ workerId,
760
+ output
761
+ });
762
+ }
763
+ if (!next) {
764
+ return output;
765
+ }
766
+ let nextInput = output;
767
+ if (next.mapInputFromPrev && typeof queueRuntime.invokeMapInput === "function") {
768
+ let previousOutputs = [];
769
+ if (queueJobId && typeof queueRuntime.getQueueJob === "function") {
770
+ try {
771
+ const job = await queueRuntime.getQueueJob(queueJobId);
772
+ if (job?.steps) {
773
+ const fromStore = job.steps.slice(0, stepIndex).map((s, i) => ({ stepIndex: i, workerId: s.workerId, output: s.output }));
774
+ previousOutputs = fromStore.concat([
775
+ { stepIndex, workerId: params.ctx?.workerId ?? "", output }
776
+ ]);
777
+ }
778
+ } catch (e) {
779
+ if (process.env.AI_WORKER_QUEUES_DEBUG === "1") {
780
+ console.warn("[Worker] getQueueJob failed, mapping without previousOutputs:", e?.message ?? e);
781
+ }
782
+ }
783
+ }
784
+ nextInput = await queueRuntime.invokeMapInput(
785
+ queueId,
786
+ stepIndex + 1,
787
+ initialInput,
788
+ previousOutputs
789
+ );
790
+ }
791
+ const nextInputWithQueue = {
792
+ ...nextInput !== null && typeof nextInput === "object" ? nextInput : { value: nextInput },
793
+ [WORKER_QUEUE_KEY]: {
794
+ id: queueId,
795
+ stepIndex: stepIndex + 1,
796
+ initialInput,
797
+ queueJobId
798
+ }
799
+ };
800
+ const debug = process.env.AI_WORKER_QUEUES_DEBUG === "1";
801
+ if (debug) {
802
+ console.log("[Worker] Queue chain dispatching next:", {
803
+ queueId,
804
+ fromStep: stepIndex,
805
+ nextWorkerId: next.workerId,
806
+ delaySeconds: next.delaySeconds
807
+ });
808
+ }
809
+ await params.ctx.dispatchWorker(next.workerId, nextInputWithQueue, {
810
+ await: false,
811
+ delaySeconds: next.delaySeconds,
812
+ jobId: childJobId
813
+ });
814
+ return output;
815
+ };
816
+ }
817
+ var DEFAULT_POLL_INTERVAL_MS = 2e3;
818
+ var DEFAULT_POLL_TIMEOUT_MS = 15 * 60 * 1e3;
819
+ function sanitizeWorkerIdForEnv(workerId) {
820
+ return workerId.replace(/-/g, "_").toUpperCase();
821
+ }
822
+ function getQueueUrlForWorker(calleeWorkerId) {
823
+ const key = `WORKER_QUEUE_URL_${sanitizeWorkerIdForEnv(calleeWorkerId)}`;
824
+ return process.env[key]?.trim() || void 0;
825
+ }
826
+ function createDispatchWorker(parentJobId, parentWorkerId, parentContext, jobStore) {
827
+ return async (calleeWorkerId, input, options) => {
828
+ const childJobId = options?.jobId || `job-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
829
+ const metadata = options?.metadata ?? {};
830
+ const serializedContext = {};
831
+ if (parentContext.requestId) serializedContext.requestId = parentContext.requestId;
832
+ const messageBody = {
833
+ workerId: calleeWorkerId,
834
+ jobId: childJobId,
835
+ input: input ?? {},
836
+ context: serializedContext,
837
+ webhookUrl: options?.webhookUrl,
838
+ metadata,
839
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
840
+ };
841
+ const queueUrl = getQueueUrlForWorker(calleeWorkerId);
842
+ if (queueUrl) {
843
+ const region = process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || "us-east-1";
844
+ const sqs = new import_client_sqs.SQSClient({ region });
845
+ const delaySeconds = options?.await !== true && options?.delaySeconds != null ? Math.min(SQS_MAX_DELAY_SECONDS, Math.max(0, Math.floor(options.delaySeconds))) : void 0;
846
+ const sendResult = await sqs.send(
847
+ new import_client_sqs.SendMessageCommand({
848
+ QueueUrl: queueUrl,
849
+ MessageBody: JSON.stringify(messageBody),
850
+ ...delaySeconds !== void 0 && delaySeconds > 0 ? { DelaySeconds: delaySeconds } : {}
851
+ })
852
+ );
853
+ const messageId = sendResult.MessageId ?? void 0;
854
+ if (jobStore?.appendInternalJob) {
855
+ await jobStore.appendInternalJob({ jobId: childJobId, workerId: calleeWorkerId });
856
+ }
857
+ if (options?.await && jobStore?.getJob) {
858
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
859
+ const pollTimeoutMs = options.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
860
+ const deadline = Date.now() + pollTimeoutMs;
861
+ while (Date.now() < deadline) {
862
+ const child = await jobStore.getJob(childJobId);
863
+ if (!child) {
864
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
865
+ continue;
866
+ }
867
+ if (child.status === "completed") {
868
+ return { jobId: childJobId, messageId, output: child.output };
869
+ }
870
+ if (child.status === "failed") {
871
+ const err = child.error;
872
+ throw new Error(
873
+ err?.message ?? `Child worker ${calleeWorkerId} failed`
874
+ );
875
+ }
876
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
877
+ }
878
+ throw new Error(
879
+ `Child worker ${calleeWorkerId} (${childJobId}) did not complete within ${pollTimeoutMs}ms`
880
+ );
881
+ }
882
+ return { jobId: childJobId, messageId };
883
+ }
884
+ throw new Error(
885
+ `WORKER_QUEUE_URL_${sanitizeWorkerIdForEnv(calleeWorkerId)} is not set. Configure queue URL for worker-to-worker dispatch, or run in local mode.`
886
+ );
887
+ };
888
+ }
151
889
  async function sendWebhook(webhookUrl, payload) {
152
890
  try {
153
891
  const response = await fetch(webhookUrl, {
@@ -187,24 +925,63 @@ function createLambdaHandler(handler, outputSchema) {
187
925
  try {
188
926
  messageBody = JSON.parse(record.body);
189
927
  const { workerId, jobId, input, context, webhookUrl, metadata = {} } = messageBody;
928
+ const raw = (process.env.WORKER_DATABASE_TYPE || "upstash-redis").toLowerCase();
929
+ const jobStoreType = raw === "mongodb" ? "mongodb" : "upstash-redis";
930
+ if (jobStoreType === "upstash-redis" && isRedisJobStoreConfigured()) {
931
+ const existing = await loadJob(jobId);
932
+ if (existing && (existing.status === "completed" || existing.status === "failed")) {
933
+ console.log("[Worker] Skipping already terminal job (idempotent):", {
934
+ jobId,
935
+ workerId,
936
+ status: existing.status
937
+ });
938
+ return;
939
+ }
940
+ } else if (jobStoreType === "mongodb" || isMongoJobStoreConfigured()) {
941
+ const existing = await getJobById(jobId);
942
+ if (existing && (existing.status === "completed" || existing.status === "failed")) {
943
+ console.log("[Worker] Skipping already terminal job (idempotent):", {
944
+ jobId,
945
+ workerId,
946
+ status: existing.status
947
+ });
948
+ return;
949
+ }
950
+ }
190
951
  let jobStore;
191
- if (isMongoJobStoreConfigured()) {
952
+ if (jobStoreType === "upstash-redis" && isRedisJobStoreConfigured()) {
953
+ await upsertRedisJob(jobId, workerId, input, metadata);
954
+ jobStore = createRedisJobStore(workerId, jobId, input, metadata);
955
+ } else if (jobStoreType === "mongodb" || isMongoJobStoreConfigured()) {
192
956
  await upsertJob(jobId, workerId, input, metadata);
193
957
  jobStore = createMongoJobStore(workerId, jobId, input, metadata);
194
958
  }
195
- const handlerContext = {
959
+ const baseContext = {
196
960
  jobId,
197
961
  workerId,
198
962
  requestId: context.requestId || lambdaContext.awsRequestId,
199
- ...jobStore ? { jobStore } : {},
200
963
  ...context
201
964
  };
965
+ const handlerContext = {
966
+ ...baseContext,
967
+ ...jobStore ? { jobStore } : {},
968
+ logger: createWorkerLogger(jobId, workerId),
969
+ dispatchWorker: createDispatchWorker(
970
+ jobId,
971
+ workerId,
972
+ baseContext,
973
+ jobStore
974
+ )
975
+ };
202
976
  if (jobStore) {
203
977
  try {
204
978
  await jobStore.update({ status: "running" });
979
+ const queueCtxForLog = input?.__workerQueue ?? metadata?.__workerQueue;
205
980
  console.log("[Worker] Job status updated to running:", {
206
981
  jobId,
207
- workerId
982
+ workerId,
983
+ ...queueCtxForLog?.id && { queueId: queueCtxForLog.id },
984
+ ...queueCtxForLog?.queueJobId && { queueJobId: queueCtxForLog.queueJobId }
208
985
  });
209
986
  } catch (error) {
210
987
  console.warn("[Worker] Failed to update status to running:", {
@@ -214,6 +991,33 @@ function createLambdaHandler(handler, outputSchema) {
214
991
  });
215
992
  }
216
993
  }
994
+ const queueCtx = input?.__workerQueue ?? metadata?.__workerQueue;
995
+ if (queueCtx?.queueJobId && typeof queueCtx.stepIndex === "number") {
996
+ if (queueCtx.stepIndex === 0) {
997
+ try {
998
+ await upsertInitialQueueJob({
999
+ queueJobId: queueCtx.queueJobId,
1000
+ queueId: queueCtx.id,
1001
+ firstWorkerId: workerId,
1002
+ firstWorkerJobId: jobId,
1003
+ metadata
1004
+ });
1005
+ } catch (e) {
1006
+ console.warn("[Worker] Failed to upsert initial queue job:", {
1007
+ queueJobId: queueCtx.queueJobId,
1008
+ queueId: queueCtx.id,
1009
+ error: e?.message ?? String(e)
1010
+ });
1011
+ }
1012
+ }
1013
+ await notifyQueueJobStep(queueCtx.queueJobId, "start", {
1014
+ queueId: queueCtx.id,
1015
+ stepIndex: queueCtx.stepIndex,
1016
+ workerJobId: jobId,
1017
+ workerId,
1018
+ input
1019
+ });
1020
+ }
217
1021
  let output;
218
1022
  try {
219
1023
  output = await handler({
@@ -253,6 +1057,16 @@ function createLambdaHandler(handler, outputSchema) {
253
1057
  });
254
1058
  }
255
1059
  }
1060
+ const queueCtxFail = input?.__workerQueue ?? metadata?.__workerQueue;
1061
+ if (queueCtxFail?.queueJobId && typeof queueCtxFail.stepIndex === "number") {
1062
+ await notifyQueueJobStep(queueCtxFail.queueJobId, "fail", {
1063
+ queueId: queueCtxFail.id,
1064
+ stepIndex: queueCtxFail.stepIndex,
1065
+ workerJobId: jobId,
1066
+ workerId,
1067
+ error: errorPayload.error
1068
+ });
1069
+ }
256
1070
  if (webhookUrl) {
257
1071
  await sendWebhook(webhookUrl, errorPayload);
258
1072
  }
@@ -306,6 +1120,9 @@ function createLambdaHandler(handler, outputSchema) {
306
1120
  }
307
1121
  // Annotate the CommonJS export names for ESM import in node:
308
1122
  0 && (module.exports = {
309
- createLambdaHandler
1123
+ SQS_MAX_DELAY_SECONDS,
1124
+ createLambdaHandler,
1125
+ createWorkerLogger,
1126
+ wrapHandlerForQueue
310
1127
  });
311
1128
  //# sourceMappingURL=handler.js.map