@supergrowthai/tq 1.0.1-canary.a2ffe03

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/index.js ADDED
@@ -0,0 +1,1985 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const types = require("./types.js");
4
+ const mongodb = require("mongodb");
5
+ const mq = require("@supergrowthai/mq");
6
+ const memooseJs = require("memoose-js");
7
+ const ioredis = require("ioredis");
8
+ const moment = require("moment");
9
+ class MemoryCronTasksAdapter {
10
+ constructor() {
11
+ this.tasks = /* @__PURE__ */ new Map();
12
+ this.idCounter = 0;
13
+ }
14
+ generateTaskId() {
15
+ return `cron_task_${++this.idCounter}`;
16
+ }
17
+ async insertTasks(tasks) {
18
+ for (const task of tasks) {
19
+ if (!task._id) {
20
+ task._id = this.generateTaskId();
21
+ }
22
+ task.created_at = task.created_at || /* @__PURE__ */ new Date();
23
+ task.status = task.status || "scheduled";
24
+ this.tasks.set(task._id, task);
25
+ }
26
+ }
27
+ async findScheduledTasks(queueId, limit) {
28
+ const now = /* @__PURE__ */ new Date();
29
+ const scheduled = [];
30
+ for (const task of this.tasks.values()) {
31
+ if (scheduled.length >= limit) break;
32
+ if (task.queue_id === queueId && task.status === "scheduled" && (!task.execute_at || task.execute_at <= now)) {
33
+ scheduled.push(task);
34
+ }
35
+ }
36
+ return scheduled;
37
+ }
38
+ async markTasksAsProcessing(taskIds) {
39
+ for (const id of taskIds) {
40
+ const task = this.tasks.get(id);
41
+ if (task) {
42
+ task.status = "processing";
43
+ task.processing_started_at = /* @__PURE__ */ new Date();
44
+ }
45
+ }
46
+ }
47
+ async markTasksAsExecuted(taskIds) {
48
+ for (const id of taskIds) {
49
+ const task = this.tasks.get(id);
50
+ if (task) {
51
+ task.status = "executed";
52
+ task.updated_at = /* @__PURE__ */ new Date();
53
+ }
54
+ }
55
+ }
56
+ async markTasksAsFailed(taskIds) {
57
+ for (const id of taskIds) {
58
+ const task = this.tasks.get(id);
59
+ if (task) {
60
+ task.status = "failed";
61
+ task.updated_at = /* @__PURE__ */ new Date();
62
+ task.retries = (task.retries || 0) + 1;
63
+ }
64
+ }
65
+ }
66
+ }
67
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
68
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
69
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
70
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
71
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
72
+ return LogLevel2;
73
+ })(LogLevel || {});
74
+ class Logger {
75
+ constructor(prefix, initialLogLevel = 1) {
76
+ this.prefix = prefix;
77
+ this.logLevel = initialLogLevel;
78
+ }
79
+ getLogLevel() {
80
+ return this.logLevel;
81
+ }
82
+ setLogLevel(level) {
83
+ this.logLevel = level;
84
+ }
85
+ debug(message, ...args) {
86
+ if (this.logLevel === 0) {
87
+ console.debug(`[${this.prefix}] ${message}`, ...args);
88
+ }
89
+ }
90
+ info(message, ...args) {
91
+ if (this.logLevel <= 1) {
92
+ console.info(`[${this.prefix}] ${message}`, ...args);
93
+ }
94
+ }
95
+ error(message, ...args) {
96
+ console.error(`[${this.prefix}] ${message}`, ...args);
97
+ }
98
+ warn(message, ...args) {
99
+ if (this.logLevel <= 2) {
100
+ console.warn(`[${this.prefix}] ${message}`, ...args);
101
+ }
102
+ }
103
+ time(message) {
104
+ if (this.logLevel < 1) {
105
+ console.time(`[${this.prefix}] ${message}`);
106
+ }
107
+ }
108
+ timeEnd(message) {
109
+ if (this.logLevel < 1) {
110
+ console.timeEnd(`[${this.prefix}] ${message}`);
111
+ }
112
+ }
113
+ }
114
+ class LockManager {
115
+ constructor(cacheProvider2, options) {
116
+ this.cacheProvider = cacheProvider2;
117
+ this.acquireLocks = /* @__PURE__ */ new Map();
118
+ this.logger = new Logger("MetricsCollector", LogLevel.INFO);
119
+ this.cacheProvider = cacheProvider2;
120
+ this.prefix = options?.prefix || "lock:";
121
+ this.defaultTimeout = options?.defaultTimeout || 30 * 60;
122
+ if (options?.debugLogs)
123
+ this.logger.setLogLevel(LogLevel.INFO);
124
+ }
125
+ /**
126
+ * Check if a resource is locked
127
+ */
128
+ async isLocked(resourceId) {
129
+ this.logger.debug("isLocked" + resourceId);
130
+ const exists = await this.cacheProvider.get(this.getKey(resourceId));
131
+ return !!exists;
132
+ }
133
+ /**
134
+ * Filter out locked resources from an array
135
+ */
136
+ async filterLocked(resources, getResourceId) {
137
+ if (!resources.length) return [];
138
+ const lockChecks = resources.map((resource) => this.isLocked(getResourceId(resource)));
139
+ const lockResults = await Promise.all(lockChecks);
140
+ return resources.filter((_, index) => !lockResults[index]);
141
+ }
142
+ /**
143
+ * Acquire a lock
144
+ * @returns true if lock was acquired, false if already locked
145
+ */
146
+ async acquire(resourceId, timeout = this.defaultTimeout) {
147
+ this.logger.debug("Acquire" + resourceId);
148
+ const existingLock = this.acquireLocks.get(resourceId);
149
+ if (existingLock) {
150
+ await existingLock;
151
+ return false;
152
+ }
153
+ const lockPromise = this.acquireInternal(resourceId, timeout);
154
+ this.acquireLocks.set(resourceId, lockPromise);
155
+ try {
156
+ return await lockPromise;
157
+ } finally {
158
+ this.acquireLocks.delete(resourceId);
159
+ }
160
+ }
161
+ /**
162
+ * Release a lock
163
+ */
164
+ async release(resourceId) {
165
+ this.logger.debug("Release" + resourceId);
166
+ const key = this.getKey(resourceId);
167
+ await this.cacheProvider.del(key);
168
+ }
169
+ async acquireInternal(resourceId, timeout) {
170
+ if (await this.isLocked(resourceId)) return false;
171
+ const key = this.getKey(resourceId);
172
+ const result = await this.cacheProvider.set(key, "1", timeout);
173
+ return result === "OK" || result === "1" || result === 1;
174
+ }
175
+ getKey(resourceId) {
176
+ return `${this.prefix}${resourceId}`;
177
+ }
178
+ }
179
+ const logger$5 = new Logger("MongoDbAdapter", LogLevel.INFO);
180
+ const TWO_DAYS_MS = 2 * 24 * 60 * 60 * 1e3;
181
+ class MongoDbAdapter {
182
+ constructor(uri = process.env.MONGODB_URI || "mongodb://localhost:27017", dbName = process.env.DB_NAME || "taskqueue", collectionName = "scheduled") {
183
+ this.client = null;
184
+ this.db = null;
185
+ this.tasksCollection = null;
186
+ this.uri = uri;
187
+ this.dbName = dbName;
188
+ this.collectionName = collectionName;
189
+ }
190
+ async initialize() {
191
+ if (this.db) return;
192
+ this.client = new mongodb.MongoClient(this.uri);
193
+ await this.client.connect();
194
+ this.db = this.client.db(this.dbName);
195
+ this.tasksCollection = this.db.collection(this.collectionName);
196
+ await this.tasksCollection.createIndex({ execute_at: 1, status: 1 });
197
+ await this.tasksCollection.createIndex({ status: 1, processing_started_at: 1 });
198
+ await this.tasksCollection.createIndex({ expires_at: 1 }, { sparse: true });
199
+ logger$5.info(`Connected to MongoDB at ${this.uri}/${this.dbName}`);
200
+ }
201
+ async addTasksToScheduled(tasks) {
202
+ if (!tasks.length) return [];
203
+ const collection = await this.ensureConnection();
204
+ const transformedTasks = tasks.map((task) => ({
205
+ _id: task._id,
206
+ type: task.type,
207
+ payload: task.payload,
208
+ execute_at: task.execute_at,
209
+ status: task.status || "scheduled",
210
+ retries: task.retries || 0,
211
+ created_at: task.created_at || /* @__PURE__ */ new Date(),
212
+ updated_at: /* @__PURE__ */ new Date(),
213
+ queue_id: task.queue_id,
214
+ processing_started_at: task.processing_started_at || /* @__PURE__ */ new Date(),
215
+ expires_at: task.expires_at,
216
+ task_group: task.task_group,
217
+ task_hash: task.task_hash,
218
+ retry_after: task.retry_after,
219
+ execution_stats: task.execution_stats,
220
+ force_store: task.force_store
221
+ }));
222
+ try {
223
+ await collection.insertMany(transformedTasks, { ordered: false });
224
+ return transformedTasks;
225
+ } catch (error) {
226
+ if (error.writeErrors) {
227
+ const successfulTasks = transformedTasks.filter(
228
+ (_, index) => !error.writeErrors.some((e) => e.index === index)
229
+ );
230
+ return successfulTasks;
231
+ }
232
+ throw error;
233
+ }
234
+ }
235
+ async getMatureTasks(timestamp) {
236
+ const collection = await this.ensureConnection();
237
+ const staleTimestamp = Date.now() - TWO_DAYS_MS;
238
+ await collection.updateMany(
239
+ {
240
+ status: "processing",
241
+ processing_started_at: { $lt: new Date(staleTimestamp) }
242
+ },
243
+ {
244
+ $set: { status: "scheduled" },
245
+ $inc: { retries: 1 }
246
+ }
247
+ );
248
+ const filter = {
249
+ status: "scheduled",
250
+ execute_at: { $lte: new Date(timestamp) }
251
+ };
252
+ const tasks = await collection.find(filter).limit(1e3).toArray();
253
+ if (tasks.length > 0) {
254
+ const taskIds = tasks.map((t) => t._id);
255
+ await collection.updateMany(
256
+ { _id: { $in: taskIds } },
257
+ {
258
+ $set: {
259
+ status: "processing",
260
+ processing_started_at: /* @__PURE__ */ new Date()
261
+ }
262
+ }
263
+ );
264
+ }
265
+ return tasks;
266
+ }
267
+ async markTasksAsProcessing(taskIds, processingStartedAt) {
268
+ const collection = await this.ensureConnection();
269
+ await collection.updateMany(
270
+ { _id: { $in: taskIds } },
271
+ {
272
+ $set: {
273
+ status: "processing",
274
+ processing_started_at: processingStartedAt,
275
+ updated_at: /* @__PURE__ */ new Date()
276
+ }
277
+ }
278
+ );
279
+ }
280
+ async markTasksAsExecuted(taskIds) {
281
+ const collection = await this.ensureConnection();
282
+ await collection.updateMany(
283
+ { _id: { $in: taskIds } },
284
+ {
285
+ $set: {
286
+ status: "executed",
287
+ updated_at: /* @__PURE__ */ new Date()
288
+ }
289
+ }
290
+ );
291
+ }
292
+ async markTasksAsFailed(taskIds) {
293
+ const collection = await this.ensureConnection();
294
+ await collection.updateMany(
295
+ { _id: { $in: taskIds } },
296
+ {
297
+ $set: {
298
+ status: "failed",
299
+ updated_at: /* @__PURE__ */ new Date()
300
+ },
301
+ $inc: { retries: 1 }
302
+ }
303
+ );
304
+ }
305
+ async getTasksByIds(taskIds) {
306
+ const collection = await this.ensureConnection();
307
+ return collection.find({ _id: { $in: taskIds } }).toArray();
308
+ }
309
+ async updateTasks(updates) {
310
+ const collection = await this.ensureConnection();
311
+ const bulkOps = updates.map(({ id, updates: updates2 }) => ({
312
+ updateOne: {
313
+ filter: { _id: id },
314
+ update: {
315
+ $set: {
316
+ ...updates2,
317
+ updated_at: /* @__PURE__ */ new Date()
318
+ }
319
+ }
320
+ }
321
+ }));
322
+ if (bulkOps.length > 0) {
323
+ await collection.bulkWrite(bulkOps);
324
+ }
325
+ }
326
+ async getCleanupStats() {
327
+ const collection = await this.ensureConnection();
328
+ const orphanedBefore = new Date(Date.now() - TWO_DAYS_MS);
329
+ const orphanedTasks = await collection.countDocuments({
330
+ status: "processing",
331
+ processing_started_at: { $lt: orphanedBefore }
332
+ });
333
+ const expiredTasks = await collection.countDocuments({
334
+ expires_at: { $lt: /* @__PURE__ */ new Date() }
335
+ });
336
+ return { orphanedTasks, expiredTasks };
337
+ }
338
+ async cleanupTasks(orphanedBefore, expiredBefore) {
339
+ const collection = await this.ensureConnection();
340
+ await collection.deleteMany({
341
+ status: "processing",
342
+ processing_started_at: { $lt: orphanedBefore }
343
+ });
344
+ await collection.deleteMany({
345
+ expires_at: { $lt: expiredBefore }
346
+ });
347
+ }
348
+ async close() {
349
+ if (this.client) {
350
+ await this.client.close();
351
+ this.client = null;
352
+ this.db = null;
353
+ this.tasksCollection = null;
354
+ logger$5.info("Disconnected from MongoDB");
355
+ }
356
+ }
357
+ async ensureConnection() {
358
+ if (!this.tasksCollection) {
359
+ await this.initialize();
360
+ }
361
+ return this.tasksCollection;
362
+ }
363
+ }
364
+ const databaseAdapter = new MongoDbAdapter();
365
+ databaseAdapter.initialize().catch(console.error);
366
+ async function addTasksToScheduled(tasks) {
367
+ if (!tasks.length) return [];
368
+ const transformedTasks = tasks.map((task) => ({
369
+ _id: task._id,
370
+ type: task.type,
371
+ queue_id: mq.getEnvironmentQueueName(task.queue_id),
372
+ payload: task.payload,
373
+ execute_at: task.execute_at,
374
+ expires_at: task.expires_at,
375
+ status: "scheduled",
376
+ task_group: task.task_group,
377
+ task_hash: task.task_hash,
378
+ retries: task.retries || 0,
379
+ retry_after: task.retry_after,
380
+ execution_stats: task.execution_stats,
381
+ created_at: task.created_at || /* @__PURE__ */ new Date(),
382
+ updated_at: task.updated_at || /* @__PURE__ */ new Date(),
383
+ processing_started_at: task.processing_started_at || /* @__PURE__ */ new Date(),
384
+ force_store: task.force_store
385
+ }));
386
+ return await databaseAdapter.addTasksToScheduled(transformedTasks);
387
+ }
388
+ async function getMatureTasks(timestamp) {
389
+ return await databaseAdapter.getMatureTasks(timestamp);
390
+ }
391
+ async function markTasksAsProcessing(taskIds) {
392
+ await databaseAdapter.markTasksAsProcessing(taskIds, /* @__PURE__ */ new Date());
393
+ }
394
+ async function markTasksAsExecuted(taskIds) {
395
+ await databaseAdapter.markTasksAsExecuted(taskIds);
396
+ }
397
+ async function markTasksAsFailed(taskIds) {
398
+ await databaseAdapter.markTasksAsFailed(taskIds);
399
+ }
400
+ async function updateTasks(updates) {
401
+ await databaseAdapter.updateTasks(updates);
402
+ }
403
+ async function getTasksByIds(taskIds) {
404
+ return await databaseAdapter.getTasksByIds(taskIds);
405
+ }
406
+ async function getCleanupStats() {
407
+ return await databaseAdapter.getCleanupStats();
408
+ }
409
+ async function cleanupTasks() {
410
+ const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1e3);
411
+ const now = /* @__PURE__ */ new Date();
412
+ await databaseAdapter.cleanupTasks(twoDaysAgo, now);
413
+ }
414
+ async function updateTasksForRetry(tasks) {
415
+ const updates = tasks.map((task) => ({
416
+ id: task._id,
417
+ updates: {
418
+ execute_at: task.execute_at,
419
+ status: task.status,
420
+ execution_stats: task.execution_stats,
421
+ updated_at: /* @__PURE__ */ new Date()
422
+ }
423
+ }));
424
+ await databaseAdapter.updateTasks(updates);
425
+ }
426
+ async function markTasksAsSuccess(tasks) {
427
+ const taskIds = tasks.map((task) => task._id);
428
+ await databaseAdapter.markTasksAsExecuted(taskIds);
429
+ }
430
+ async function markTasksAsIgnored(tasks) {
431
+ const taskIds = tasks.map((task) => task._id);
432
+ await databaseAdapter.markTasksAsFailed(taskIds);
433
+ }
434
+ const TaskStore = {
435
+ addTasksToScheduled,
436
+ getMatureTasks,
437
+ markTasksAsProcessing,
438
+ markTasksAsExecuted,
439
+ markTasksAsFailed,
440
+ updateTasks,
441
+ getTasksByIds,
442
+ getCleanupStats,
443
+ cleanupTasks,
444
+ updateTasksForRetry,
445
+ markTasksAsSuccess,
446
+ markTasksAsIgnored
447
+ };
448
+ class DisableCachePipeline {
449
+ constructor() {
450
+ this.actions = [];
451
+ }
452
+ del(key) {
453
+ this.actions.push(["del", key]);
454
+ return this;
455
+ }
456
+ expire(key, new_ttl_from_now) {
457
+ this.actions.push(["expire", key, new_ttl_from_now]);
458
+ return this;
459
+ }
460
+ async exec() {
461
+ return this.actions.map(([action, ...args]) => {
462
+ switch (action) {
463
+ case "get":
464
+ case "del":
465
+ case "expire":
466
+ case "set":
467
+ default:
468
+ return null;
469
+ }
470
+ });
471
+ }
472
+ get(key) {
473
+ this.actions.push(["get", key]);
474
+ return this;
475
+ }
476
+ set(key, data, ttl) {
477
+ this.actions.push(["set", key, data, ttl]);
478
+ return this;
479
+ }
480
+ }
481
+ class DisabledCache {
482
+ constructor() {
483
+ this.storesAsObj = false;
484
+ memooseJs.stats[this.name()] = {};
485
+ }
486
+ name() {
487
+ return "disabled-cache";
488
+ }
489
+ pipeline() {
490
+ return new DisableCachePipeline();
491
+ }
492
+ async get(key) {
493
+ return null;
494
+ }
495
+ async mget(...key) {
496
+ return key.map(() => null);
497
+ }
498
+ async mset(...key) {
499
+ return "OK";
500
+ }
501
+ async set(key, data, ttl) {
502
+ return "OK";
503
+ }
504
+ async del(...key) {
505
+ return key.length;
506
+ }
507
+ async expire(key, new_ttl_from_now) {
508
+ return 1;
509
+ }
510
+ }
511
+ class RedisClusterCacheProvider {
512
+ constructor(name, config, connect = true) {
513
+ this.storesAsObj = false;
514
+ const { nodes, options } = config;
515
+ this.client_client = new ioredis.Cluster(nodes, options);
516
+ this.connect = connect;
517
+ if (connect)
518
+ this.connected_promise = this.client_client.connect();
519
+ else
520
+ this.connected_promise = Promise.resolve("told not to connect");
521
+ const errorOrCloseCB = (...args) => {
522
+ console.log(`Error in RedisClient: ${name}.`, "\r\n", ...args);
523
+ process.exit(55666);
524
+ };
525
+ this.client_client.on("end", errorOrCloseCB.bind(null, "end"));
526
+ this.client_client.on("error", errorOrCloseCB.bind(null, "error"));
527
+ this.client_client.on("close", errorOrCloseCB.bind(null, "close"));
528
+ this.client_client.on("finish", errorOrCloseCB.bind(null, "finish"));
529
+ }
530
+ get client() {
531
+ return this.client_client;
532
+ }
533
+ name() {
534
+ return "redis";
535
+ }
536
+ getClientConnectionPromise() {
537
+ if (this.connect)
538
+ return this.connected_promise;
539
+ else
540
+ throw new Error("shouldnt call as client initialised with connect=false");
541
+ }
542
+ get(key) {
543
+ return this.client_client.get(key);
544
+ }
545
+ set(key, value, ttl = -1) {
546
+ if (ttl > 0)
547
+ return this.client_client.set(key, value, "EX", ttl);
548
+ else
549
+ return this.client_client.set(key, value);
550
+ }
551
+ del(...keys) {
552
+ return this.client_client.del(...keys);
553
+ }
554
+ awaitTillReady() {
555
+ return new Promise((resolve, reject) => {
556
+ this.client_client.once("ready", resolve);
557
+ this.client_client.once("error", reject);
558
+ });
559
+ }
560
+ pipeline() {
561
+ return this.client_client.pipeline();
562
+ }
563
+ expire(key, ttl) {
564
+ return this.client_client.expire(key, ttl);
565
+ }
566
+ mget(...keys) {
567
+ return this.client_client.mget(...keys);
568
+ }
569
+ mset(...keyValues) {
570
+ return this.client_client.mset(...keyValues);
571
+ }
572
+ exists(...keys) {
573
+ return this.client_client.exists(...keys);
574
+ }
575
+ lpush(key, ...values) {
576
+ return this.client_client.lpush(key, ...values);
577
+ }
578
+ llen(key) {
579
+ return this.client_client.llen(key);
580
+ }
581
+ scard(key) {
582
+ return this.client_client.scard(key);
583
+ }
584
+ sismember(key, member) {
585
+ return this.client_client.sismember(key, member);
586
+ }
587
+ sadd(key, member) {
588
+ return this.client_client.sadd(key, member);
589
+ }
590
+ srem(key, member) {
591
+ return this.client_client.srem(key, member);
592
+ }
593
+ smembers(key) {
594
+ return this.client_client.smembers(key);
595
+ }
596
+ rpush(key, ...values) {
597
+ return this.client_client.rpush(key, ...values);
598
+ }
599
+ lrange(key, start, stop) {
600
+ return this.client_client.lrange(key, start, stop);
601
+ }
602
+ ping() {
603
+ return this.client_client.ping();
604
+ }
605
+ subscribe(...channels) {
606
+ return this.client_client.subscribe(...channels);
607
+ }
608
+ on(event, listener) {
609
+ return this.client_client.on(event, listener);
610
+ }
611
+ publish(channel, message) {
612
+ return this.client_client.publish(channel, message);
613
+ }
614
+ flushdb() {
615
+ return this.client_client.flushdb();
616
+ }
617
+ lpop(key) {
618
+ return this.client_client.lpop(key);
619
+ }
620
+ decrby(key, count) {
621
+ return this.client_client.decrby(key, count);
622
+ }
623
+ }
624
+ class MemoryPipeline {
625
+ constructor(cache) {
626
+ this.operations = [];
627
+ this.cache = cache;
628
+ }
629
+ get(key) {
630
+ this.operations.push(async () => {
631
+ const entry = this.cache.get(key);
632
+ if (!entry || entry.expiresAt && entry.expiresAt < Date.now()) {
633
+ return null;
634
+ }
635
+ return entry.value;
636
+ });
637
+ return this;
638
+ }
639
+ set(key, data, ttl) {
640
+ this.operations.push(async () => {
641
+ const entry = {
642
+ value: data,
643
+ expiresAt: ttl ? Date.now() + ttl * 1e3 : void 0
644
+ };
645
+ this.cache.set(key, entry);
646
+ return "OK";
647
+ });
648
+ return this;
649
+ }
650
+ del(key) {
651
+ this.operations.push(async () => {
652
+ return this.cache.delete(key) ? 1 : 0;
653
+ });
654
+ return this;
655
+ }
656
+ expire(key, new_ttl_from_now) {
657
+ this.operations.push(async () => {
658
+ const entry = this.cache.get(key);
659
+ if (!entry) return 0;
660
+ entry.expiresAt = Date.now() + new_ttl_from_now * 1e3;
661
+ return 1;
662
+ });
663
+ return this;
664
+ }
665
+ async exec() {
666
+ const results = await Promise.all(this.operations.map((op) => op()));
667
+ this.operations = [];
668
+ return results;
669
+ }
670
+ }
671
+ class InMemoryCacheProvider {
672
+ constructor() {
673
+ this.storesAsObj = false;
674
+ this.cache = /* @__PURE__ */ new Map();
675
+ }
676
+ name() {
677
+ return "memory";
678
+ }
679
+ async get(key) {
680
+ const entry = this.cache.get(key);
681
+ if (!entry || this.isExpired(entry)) {
682
+ if (entry) this.cache.delete(key);
683
+ return null;
684
+ }
685
+ return entry.value;
686
+ }
687
+ async mget(...keys) {
688
+ return Promise.all(keys.map((key) => this.get(key)));
689
+ }
690
+ async mset(...keyValues) {
691
+ for (const [key, value] of keyValues) {
692
+ await this.set(key, value);
693
+ }
694
+ return "OK";
695
+ }
696
+ async set(key, data, ttl) {
697
+ const entry = {
698
+ value: data,
699
+ expiresAt: ttl ? Date.now() + ttl * 1e3 : void 0
700
+ };
701
+ this.cache.set(key, entry);
702
+ return "OK";
703
+ }
704
+ async del(...keys) {
705
+ let count = 0;
706
+ for (const key of keys) {
707
+ if (this.cache.delete(key)) {
708
+ count++;
709
+ }
710
+ }
711
+ return count;
712
+ }
713
+ async expire(key, new_ttl_from_now) {
714
+ const entry = this.cache.get(key);
715
+ if (!entry) return 0;
716
+ entry.expiresAt = Date.now() + new_ttl_from_now * 1e3;
717
+ return 1;
718
+ }
719
+ pipeline() {
720
+ return new MemoryPipeline(this.cache);
721
+ }
722
+ isExpired(entry) {
723
+ return entry.expiresAt !== void 0 && entry.expiresAt < Date.now();
724
+ }
725
+ }
726
+ class CacheFactory {
727
+ static create(config) {
728
+ console.log("Creating cache with config:", JSON.stringify(config));
729
+ switch (config.provider) {
730
+ case "redis":
731
+ if (!config.redis)
732
+ throw new Error("Redis configuration required");
733
+ if (config.redis.type === "cluster") {
734
+ return new RedisClusterCacheProvider("redis", config.redis, false);
735
+ } else {
736
+ return new memooseJs.RedisCacheProvider("redis", config.redis, false);
737
+ }
738
+ case "memory":
739
+ return new InMemoryCacheProvider();
740
+ case "disabled":
741
+ default:
742
+ return new DisabledCache();
743
+ }
744
+ }
745
+ }
746
+ const configs = {
747
+ "standalone[redis-cfg]": {
748
+ provider: "redis",
749
+ redis: {
750
+ type: "cluster",
751
+ nodes: [{
752
+ host: process.env.REDIS_HOST || "localhost",
753
+ port: parseInt(process.env.REDIS_PORT || "6379")
754
+ }],
755
+ options: {
756
+ dnsLookup: (address, callback) => callback(null, address),
757
+ redisOptions: {
758
+ tls: {}
759
+ },
760
+ lazyConnect: true
761
+ }
762
+ }
763
+ },
764
+ standalone: {
765
+ provider: "redis",
766
+ redis: {
767
+ type: "standalone",
768
+ host: process.env.REDIS_HOST || "localhost",
769
+ port: parseInt(process.env.REDIS_PORT || "6379"),
770
+ lazyConnect: false
771
+ }
772
+ },
773
+ serverless: {
774
+ provider: "memory"
775
+ //redis as a service later?
776
+ }
777
+ };
778
+ const getConfig = () => {
779
+ const env = process.env.ENV_TYPE || "serverless";
780
+ return configs[env] || configs.serverless;
781
+ };
782
+ const cacheProvider = CacheFactory.create(getConfig());
783
+ class CacheKeyGeneratorProvider extends memooseJs.CacheKeyGenerator {
784
+ constructor(function_name, should_sort_args) {
785
+ super(function_name, should_sort_args);
786
+ this.fnName = function_name;
787
+ }
788
+ for(...args) {
789
+ const key = super.for(...args);
790
+ return `{${this.fnName}}:${key}`;
791
+ }
792
+ }
793
+ const getCacheKeyGenerator = (fn, argsOrder = false) => new CacheKeyGeneratorProvider(fn, argsOrder);
794
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
795
+ function getDefaultExportFromCjs(x) {
796
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
797
+ }
798
+ var _baseSlice;
799
+ var hasRequired_baseSlice;
800
+ function require_baseSlice() {
801
+ if (hasRequired_baseSlice) return _baseSlice;
802
+ hasRequired_baseSlice = 1;
803
+ function baseSlice(array, start, end) {
804
+ var index = -1, length = array.length;
805
+ if (start < 0) {
806
+ start = -start > length ? 0 : length + start;
807
+ }
808
+ end = end > length ? length : end;
809
+ if (end < 0) {
810
+ end += length;
811
+ }
812
+ length = start > end ? 0 : end - start >>> 0;
813
+ start >>>= 0;
814
+ var result = Array(length);
815
+ while (++index < length) {
816
+ result[index] = array[index + start];
817
+ }
818
+ return result;
819
+ }
820
+ _baseSlice = baseSlice;
821
+ return _baseSlice;
822
+ }
823
+ var eq_1;
824
+ var hasRequiredEq;
825
+ function requireEq() {
826
+ if (hasRequiredEq) return eq_1;
827
+ hasRequiredEq = 1;
828
+ function eq(value, other) {
829
+ return value === other || value !== value && other !== other;
830
+ }
831
+ eq_1 = eq;
832
+ return eq_1;
833
+ }
834
+ var _freeGlobal;
835
+ var hasRequired_freeGlobal;
836
+ function require_freeGlobal() {
837
+ if (hasRequired_freeGlobal) return _freeGlobal;
838
+ hasRequired_freeGlobal = 1;
839
+ var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
840
+ _freeGlobal = freeGlobal;
841
+ return _freeGlobal;
842
+ }
843
+ var _root;
844
+ var hasRequired_root;
845
+ function require_root() {
846
+ if (hasRequired_root) return _root;
847
+ hasRequired_root = 1;
848
+ var freeGlobal = require_freeGlobal();
849
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
850
+ var root = freeGlobal || freeSelf || Function("return this")();
851
+ _root = root;
852
+ return _root;
853
+ }
854
+ var _Symbol;
855
+ var hasRequired_Symbol;
856
+ function require_Symbol() {
857
+ if (hasRequired_Symbol) return _Symbol;
858
+ hasRequired_Symbol = 1;
859
+ var root = require_root();
860
+ var Symbol2 = root.Symbol;
861
+ _Symbol = Symbol2;
862
+ return _Symbol;
863
+ }
864
+ var _getRawTag;
865
+ var hasRequired_getRawTag;
866
+ function require_getRawTag() {
867
+ if (hasRequired_getRawTag) return _getRawTag;
868
+ hasRequired_getRawTag = 1;
869
+ var Symbol2 = require_Symbol();
870
+ var objectProto = Object.prototype;
871
+ var hasOwnProperty = objectProto.hasOwnProperty;
872
+ var nativeObjectToString = objectProto.toString;
873
+ var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
874
+ function getRawTag(value) {
875
+ var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
876
+ try {
877
+ value[symToStringTag] = void 0;
878
+ var unmasked = true;
879
+ } catch (e) {
880
+ }
881
+ var result = nativeObjectToString.call(value);
882
+ if (unmasked) {
883
+ if (isOwn) {
884
+ value[symToStringTag] = tag;
885
+ } else {
886
+ delete value[symToStringTag];
887
+ }
888
+ }
889
+ return result;
890
+ }
891
+ _getRawTag = getRawTag;
892
+ return _getRawTag;
893
+ }
894
+ var _objectToString;
895
+ var hasRequired_objectToString;
896
+ function require_objectToString() {
897
+ if (hasRequired_objectToString) return _objectToString;
898
+ hasRequired_objectToString = 1;
899
+ var objectProto = Object.prototype;
900
+ var nativeObjectToString = objectProto.toString;
901
+ function objectToString(value) {
902
+ return nativeObjectToString.call(value);
903
+ }
904
+ _objectToString = objectToString;
905
+ return _objectToString;
906
+ }
907
+ var _baseGetTag;
908
+ var hasRequired_baseGetTag;
909
+ function require_baseGetTag() {
910
+ if (hasRequired_baseGetTag) return _baseGetTag;
911
+ hasRequired_baseGetTag = 1;
912
+ var Symbol2 = require_Symbol(), getRawTag = require_getRawTag(), objectToString = require_objectToString();
913
+ var nullTag = "[object Null]", undefinedTag = "[object Undefined]";
914
+ var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
915
+ function baseGetTag(value) {
916
+ if (value == null) {
917
+ return value === void 0 ? undefinedTag : nullTag;
918
+ }
919
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
920
+ }
921
+ _baseGetTag = baseGetTag;
922
+ return _baseGetTag;
923
+ }
924
+ var isObject_1;
925
+ var hasRequiredIsObject;
926
+ function requireIsObject() {
927
+ if (hasRequiredIsObject) return isObject_1;
928
+ hasRequiredIsObject = 1;
929
+ function isObject(value) {
930
+ var type = typeof value;
931
+ return value != null && (type == "object" || type == "function");
932
+ }
933
+ isObject_1 = isObject;
934
+ return isObject_1;
935
+ }
936
+ var isFunction_1;
937
+ var hasRequiredIsFunction;
938
+ function requireIsFunction() {
939
+ if (hasRequiredIsFunction) return isFunction_1;
940
+ hasRequiredIsFunction = 1;
941
+ var baseGetTag = require_baseGetTag(), isObject = requireIsObject();
942
+ var asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
943
+ function isFunction(value) {
944
+ if (!isObject(value)) {
945
+ return false;
946
+ }
947
+ var tag = baseGetTag(value);
948
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
949
+ }
950
+ isFunction_1 = isFunction;
951
+ return isFunction_1;
952
+ }
953
+ var isLength_1;
954
+ var hasRequiredIsLength;
955
+ function requireIsLength() {
956
+ if (hasRequiredIsLength) return isLength_1;
957
+ hasRequiredIsLength = 1;
958
+ var MAX_SAFE_INTEGER = 9007199254740991;
959
+ function isLength(value) {
960
+ return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
961
+ }
962
+ isLength_1 = isLength;
963
+ return isLength_1;
964
+ }
965
+ var isArrayLike_1;
966
+ var hasRequiredIsArrayLike;
967
+ function requireIsArrayLike() {
968
+ if (hasRequiredIsArrayLike) return isArrayLike_1;
969
+ hasRequiredIsArrayLike = 1;
970
+ var isFunction = requireIsFunction(), isLength = requireIsLength();
971
+ function isArrayLike(value) {
972
+ return value != null && isLength(value.length) && !isFunction(value);
973
+ }
974
+ isArrayLike_1 = isArrayLike;
975
+ return isArrayLike_1;
976
+ }
977
+ var _isIndex;
978
+ var hasRequired_isIndex;
979
+ function require_isIndex() {
980
+ if (hasRequired_isIndex) return _isIndex;
981
+ hasRequired_isIndex = 1;
982
+ var MAX_SAFE_INTEGER = 9007199254740991;
983
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
984
+ function isIndex(value, length) {
985
+ var type = typeof value;
986
+ length = length == null ? MAX_SAFE_INTEGER : length;
987
+ return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
988
+ }
989
+ _isIndex = isIndex;
990
+ return _isIndex;
991
+ }
992
+ var _isIterateeCall;
993
+ var hasRequired_isIterateeCall;
994
+ function require_isIterateeCall() {
995
+ if (hasRequired_isIterateeCall) return _isIterateeCall;
996
+ hasRequired_isIterateeCall = 1;
997
+ var eq = requireEq(), isArrayLike = requireIsArrayLike(), isIndex = require_isIndex(), isObject = requireIsObject();
998
+ function isIterateeCall(value, index, object) {
999
+ if (!isObject(object)) {
1000
+ return false;
1001
+ }
1002
+ var type = typeof index;
1003
+ if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) {
1004
+ return eq(object[index], value);
1005
+ }
1006
+ return false;
1007
+ }
1008
+ _isIterateeCall = isIterateeCall;
1009
+ return _isIterateeCall;
1010
+ }
1011
+ var _trimmedEndIndex;
1012
+ var hasRequired_trimmedEndIndex;
1013
+ function require_trimmedEndIndex() {
1014
+ if (hasRequired_trimmedEndIndex) return _trimmedEndIndex;
1015
+ hasRequired_trimmedEndIndex = 1;
1016
+ var reWhitespace = /\s/;
1017
+ function trimmedEndIndex(string) {
1018
+ var index = string.length;
1019
+ while (index-- && reWhitespace.test(string.charAt(index))) {
1020
+ }
1021
+ return index;
1022
+ }
1023
+ _trimmedEndIndex = trimmedEndIndex;
1024
+ return _trimmedEndIndex;
1025
+ }
1026
+ var _baseTrim;
1027
+ var hasRequired_baseTrim;
1028
+ function require_baseTrim() {
1029
+ if (hasRequired_baseTrim) return _baseTrim;
1030
+ hasRequired_baseTrim = 1;
1031
+ var trimmedEndIndex = require_trimmedEndIndex();
1032
+ var reTrimStart = /^\s+/;
1033
+ function baseTrim(string) {
1034
+ return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string;
1035
+ }
1036
+ _baseTrim = baseTrim;
1037
+ return _baseTrim;
1038
+ }
1039
+ var isObjectLike_1;
1040
+ var hasRequiredIsObjectLike;
1041
+ function requireIsObjectLike() {
1042
+ if (hasRequiredIsObjectLike) return isObjectLike_1;
1043
+ hasRequiredIsObjectLike = 1;
1044
+ function isObjectLike(value) {
1045
+ return value != null && typeof value == "object";
1046
+ }
1047
+ isObjectLike_1 = isObjectLike;
1048
+ return isObjectLike_1;
1049
+ }
1050
+ var isSymbol_1;
1051
+ var hasRequiredIsSymbol;
1052
+ function requireIsSymbol() {
1053
+ if (hasRequiredIsSymbol) return isSymbol_1;
1054
+ hasRequiredIsSymbol = 1;
1055
+ var baseGetTag = require_baseGetTag(), isObjectLike = requireIsObjectLike();
1056
+ var symbolTag = "[object Symbol]";
1057
+ function isSymbol(value) {
1058
+ return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag;
1059
+ }
1060
+ isSymbol_1 = isSymbol;
1061
+ return isSymbol_1;
1062
+ }
1063
+ var toNumber_1;
1064
+ var hasRequiredToNumber;
1065
+ function requireToNumber() {
1066
+ if (hasRequiredToNumber) return toNumber_1;
1067
+ hasRequiredToNumber = 1;
1068
+ var baseTrim = require_baseTrim(), isObject = requireIsObject(), isSymbol = requireIsSymbol();
1069
+ var NAN = 0 / 0;
1070
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
1071
+ var reIsBinary = /^0b[01]+$/i;
1072
+ var reIsOctal = /^0o[0-7]+$/i;
1073
+ var freeParseInt = parseInt;
1074
+ function toNumber(value) {
1075
+ if (typeof value == "number") {
1076
+ return value;
1077
+ }
1078
+ if (isSymbol(value)) {
1079
+ return NAN;
1080
+ }
1081
+ if (isObject(value)) {
1082
+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;
1083
+ value = isObject(other) ? other + "" : other;
1084
+ }
1085
+ if (typeof value != "string") {
1086
+ return value === 0 ? value : +value;
1087
+ }
1088
+ value = baseTrim(value);
1089
+ var isBinary = reIsBinary.test(value);
1090
+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
1091
+ }
1092
+ toNumber_1 = toNumber;
1093
+ return toNumber_1;
1094
+ }
1095
+ var toFinite_1;
1096
+ var hasRequiredToFinite;
1097
+ function requireToFinite() {
1098
+ if (hasRequiredToFinite) return toFinite_1;
1099
+ hasRequiredToFinite = 1;
1100
+ var toNumber = requireToNumber();
1101
+ var INFINITY = 1 / 0, MAX_INTEGER = 17976931348623157e292;
1102
+ function toFinite(value) {
1103
+ if (!value) {
1104
+ return value === 0 ? value : 0;
1105
+ }
1106
+ value = toNumber(value);
1107
+ if (value === INFINITY || value === -INFINITY) {
1108
+ var sign = value < 0 ? -1 : 1;
1109
+ return sign * MAX_INTEGER;
1110
+ }
1111
+ return value === value ? value : 0;
1112
+ }
1113
+ toFinite_1 = toFinite;
1114
+ return toFinite_1;
1115
+ }
1116
+ var toInteger_1;
1117
+ var hasRequiredToInteger;
1118
+ function requireToInteger() {
1119
+ if (hasRequiredToInteger) return toInteger_1;
1120
+ hasRequiredToInteger = 1;
1121
+ var toFinite = requireToFinite();
1122
+ function toInteger(value) {
1123
+ var result = toFinite(value), remainder = result % 1;
1124
+ return result === result ? remainder ? result - remainder : result : 0;
1125
+ }
1126
+ toInteger_1 = toInteger;
1127
+ return toInteger_1;
1128
+ }
1129
+ var chunk_1;
1130
+ var hasRequiredChunk;
1131
+ function requireChunk() {
1132
+ if (hasRequiredChunk) return chunk_1;
1133
+ hasRequiredChunk = 1;
1134
+ var baseSlice = require_baseSlice(), isIterateeCall = require_isIterateeCall(), toInteger = requireToInteger();
1135
+ var nativeCeil = Math.ceil, nativeMax = Math.max;
1136
+ function chunk2(array, size, guard) {
1137
+ if (guard ? isIterateeCall(array, size, guard) : size === void 0) {
1138
+ size = 1;
1139
+ } else {
1140
+ size = nativeMax(toInteger(size), 0);
1141
+ }
1142
+ var length = array == null ? 0 : array.length;
1143
+ if (!length || size < 1) {
1144
+ return [];
1145
+ }
1146
+ var index = 0, resIndex = 0, result = Array(nativeCeil(length / size));
1147
+ while (index < length) {
1148
+ result[resIndex++] = baseSlice(array, index, index += size);
1149
+ }
1150
+ return result;
1151
+ }
1152
+ chunk_1 = chunk2;
1153
+ return chunk_1;
1154
+ }
1155
+ var chunkExports = requireChunk();
1156
+ const chunk = /* @__PURE__ */ getDefaultExportFromCjs(chunkExports);
1157
+ const taskIdCacheKeyGen = getCacheKeyGenerator("task-id-gen");
1158
+ function tId(task) {
1159
+ if (task._id) return task._id.toString();
1160
+ if (task.task_hash) return task.task_hash;
1161
+ return taskIdCacheKeyGen.for(task.type, task.queue_id, task.created_at, task.payload);
1162
+ }
1163
+ const logger$4 = new Logger("Actions", LogLevel.INFO);
1164
+ class Actions {
1165
+ constructor(taskRunnerId) {
1166
+ this.taskContexts = /* @__PURE__ */ new Map();
1167
+ this.taskRunnerId = taskRunnerId;
1168
+ }
1169
+ /**
1170
+ * Fork execution context for a specific task (for single-task executors)
1171
+ */
1172
+ forkForTask(task) {
1173
+ const taskId = tId(task);
1174
+ const context = { task, actions: [] };
1175
+ this.taskContexts.set(taskId, context);
1176
+ return {
1177
+ fail: (t) => {
1178
+ context.actions.push({
1179
+ type: "fail",
1180
+ timestamp: Date.now(),
1181
+ task: t
1182
+ });
1183
+ logger$4.error(`[${this.taskRunnerId}] Task failed: ${tId(t)} (${t.type})`);
1184
+ },
1185
+ success: (t) => {
1186
+ context.actions.push({
1187
+ type: "success",
1188
+ timestamp: Date.now(),
1189
+ task: t
1190
+ });
1191
+ logger$4.info(`[${this.taskRunnerId}] Task succeeded: ${tId(t)} (${t.type})`);
1192
+ },
1193
+ addTasks: (tasks) => {
1194
+ context.actions.push({
1195
+ type: "addTasks",
1196
+ timestamp: Date.now(),
1197
+ newTasks: tasks
1198
+ });
1199
+ logger$4.info(`[${this.taskRunnerId}] Task ${taskId} adding ${tasks.length} new tasks`);
1200
+ }
1201
+ };
1202
+ }
1203
+ // For multi-task executors - they use the root Actions directly (no forking)
1204
+ fail(task) {
1205
+ const taskId = tId(task);
1206
+ let context = this.taskContexts.get(taskId);
1207
+ if (!context) {
1208
+ context = { task, actions: [] };
1209
+ this.taskContexts.set(taskId, context);
1210
+ }
1211
+ context.actions.push({
1212
+ type: "fail",
1213
+ timestamp: Date.now(),
1214
+ task
1215
+ });
1216
+ logger$4.error(`[${this.taskRunnerId}] Task failed: ${taskId} (${task.type})`);
1217
+ }
1218
+ success(task) {
1219
+ const taskId = tId(task);
1220
+ let context = this.taskContexts.get(taskId);
1221
+ if (!context) {
1222
+ context = { task, actions: [] };
1223
+ this.taskContexts.set(taskId, context);
1224
+ }
1225
+ context.actions.push({
1226
+ type: "success",
1227
+ timestamp: Date.now(),
1228
+ task
1229
+ });
1230
+ logger$4.info(`[${this.taskRunnerId}] Task succeeded: ${taskId} (${task.type})`);
1231
+ }
1232
+ addTasks(tasks) {
1233
+ logger$4.info(`[${this.taskRunnerId}] Adding ${tasks.length} new tasks`);
1234
+ const batchKey = `__batch_${this.taskRunnerId}__`;
1235
+ let batchContext = this.taskContexts.get(batchKey);
1236
+ if (!batchContext) {
1237
+ batchContext = { task: null, actions: [] };
1238
+ this.taskContexts.set(batchKey, batchContext);
1239
+ }
1240
+ batchContext.actions.push({
1241
+ type: "addTasks",
1242
+ timestamp: Date.now(),
1243
+ newTasks: tasks
1244
+ });
1245
+ }
1246
+ addIgnoredTask(task) {
1247
+ const taskId = tId(task);
1248
+ this.taskContexts.set(taskId, { task, actions: [] });
1249
+ logger$4.warn(`[${this.taskRunnerId}] Task ignored: ${taskId} (${task.type})`);
1250
+ }
1251
+ /**
1252
+ * Extract actions for a single task (used by async tasks)
1253
+ */
1254
+ extractTaskActions(taskId) {
1255
+ const results = {
1256
+ failedTasks: [],
1257
+ successTasks: [],
1258
+ newTasks: [],
1259
+ ignoredTasks: []
1260
+ };
1261
+ const context = this.taskContexts.get(taskId);
1262
+ if (!context) return results;
1263
+ if (context.actions.length === 0 && context.task) {
1264
+ results.ignoredTasks.push(context.task);
1265
+ } else {
1266
+ for (const action of context.actions) {
1267
+ if (action.type === "success" && action.task) {
1268
+ results.successTasks.push(action.task);
1269
+ const targetTaskId = tId(action.task);
1270
+ if (targetTaskId !== taskId) {
1271
+ this.taskContexts.delete(targetTaskId);
1272
+ }
1273
+ } else if (action.type === "fail" && action.task) {
1274
+ results.failedTasks.push(action.task);
1275
+ const targetTaskId = tId(action.task);
1276
+ if (targetTaskId !== taskId) {
1277
+ this.taskContexts.delete(targetTaskId);
1278
+ }
1279
+ } else if (action.type === "addTasks" && action.newTasks) {
1280
+ results.newTasks.push(...action.newTasks);
1281
+ }
1282
+ }
1283
+ }
1284
+ this.taskContexts.delete(taskId);
1285
+ return results;
1286
+ }
1287
+ /**
1288
+ * Extract sync results including batch context (for sync processing)
1289
+ */
1290
+ extractSyncResults(excludeTaskIds) {
1291
+ const results = {
1292
+ failedTasks: [],
1293
+ successTasks: [],
1294
+ newTasks: [],
1295
+ ignoredTasks: []
1296
+ };
1297
+ const excludeSet = new Set(excludeTaskIds);
1298
+ const batchKey = `__batch_${this.taskRunnerId}__`;
1299
+ for (const [taskId, context] of this.taskContexts) {
1300
+ if (excludeSet.has(taskId)) continue;
1301
+ if (taskId === batchKey) {
1302
+ for (const action of context.actions) {
1303
+ if (action.type === "addTasks" && action.newTasks) {
1304
+ results.newTasks.push(...action.newTasks);
1305
+ }
1306
+ }
1307
+ } else {
1308
+ if (context.actions.length === 0 && context.task) {
1309
+ results.ignoredTasks.push(context.task);
1310
+ } else {
1311
+ for (const action of context.actions) {
1312
+ if (action.type === "success" && action.task) {
1313
+ results.successTasks.push(action.task);
1314
+ } else if (action.type === "fail" && action.task) {
1315
+ results.failedTasks.push(action.task);
1316
+ } else if (action.type === "addTasks" && action.newTasks) {
1317
+ results.newTasks.push(...action.newTasks);
1318
+ }
1319
+ }
1320
+ }
1321
+ }
1322
+ }
1323
+ for (const [taskId] of this.taskContexts) {
1324
+ if (!excludeSet.has(taskId)) {
1325
+ this.taskContexts.delete(taskId);
1326
+ }
1327
+ }
1328
+ return results;
1329
+ }
1330
+ /**
1331
+ * Get all results (mainly for backward compatibility)
1332
+ */
1333
+ getResults() {
1334
+ return this.extractSyncResults([]);
1335
+ }
1336
+ }
1337
+ const logger$3 = new Logger("AsyncActions", LogLevel.INFO);
1338
+ class AsyncActions {
1339
+ constructor(messageQueue, actions, task) {
1340
+ this.messageQueue = messageQueue;
1341
+ this.actions = actions;
1342
+ this.taskId = tId(task);
1343
+ }
1344
+ /**
1345
+ * Called when the async promise completes to execute the collected actions
1346
+ */
1347
+ async onPromiseFulfilled() {
1348
+ const results = this.actions.extractTaskActions(this.taskId);
1349
+ const hasCompletion = results.successTasks.length > 0 || results.failedTasks.length > 0;
1350
+ if (!hasCompletion) {
1351
+ throw new Error(`Async task ${this.taskId} completed without calling success() or fail()`);
1352
+ }
1353
+ logger$3.info(`[AsyncActions] Processing results for async task ${this.taskId}: ${results.successTasks.length} success, ${results.failedTasks.length} failed, ${results.newTasks.length} new tasks`);
1354
+ if (results.failedTasks.length > 0) {
1355
+ try {
1356
+ const failedTaskIds = results.failedTasks.map((task) => task._id);
1357
+ await TaskStore.markTasksAsFailed(failedTaskIds);
1358
+ logger$3.info(`[AsyncActions] Marked ${results.failedTasks.length} tasks as failed in database`);
1359
+ } catch (err) {
1360
+ logger$3.error(`[AsyncActions] Failed to mark tasks as failed:`, err);
1361
+ throw err;
1362
+ }
1363
+ }
1364
+ if (results.successTasks.length > 0) {
1365
+ try {
1366
+ await TaskStore.markTasksAsSuccess(results.successTasks);
1367
+ logger$3.info(`[AsyncActions] Marked ${results.successTasks.length} tasks as success in database`);
1368
+ } catch (err) {
1369
+ logger$3.error(`[AsyncActions] Failed to mark tasks as success:`, err);
1370
+ throw err;
1371
+ }
1372
+ }
1373
+ if (results.newTasks.length > 0) {
1374
+ logger$3.info(`[AsyncActions] Scheduling ${results.newTasks.length} new tasks`);
1375
+ await this.scheduleNewTasks(results.newTasks);
1376
+ }
1377
+ }
1378
+ /**
1379
+ * Schedule new tasks - replicates the logic from task-handler's addTasks
1380
+ */
1381
+ async scheduleNewTasks(tasks) {
1382
+ const now = /* @__PURE__ */ new Date();
1383
+ const immediate = {};
1384
+ const future = [];
1385
+ for (const task of tasks) {
1386
+ const timeDiff = (task.execute_at.getTime() - now.getTime()) / 1e3 / 60;
1387
+ if (timeDiff > 2) {
1388
+ future.push(task);
1389
+ } else {
1390
+ const queue = task.queue_id;
1391
+ if (!immediate[queue]) {
1392
+ immediate[queue] = [];
1393
+ }
1394
+ immediate[queue].push(task);
1395
+ }
1396
+ }
1397
+ const iQueues = Object.keys(immediate);
1398
+ for (const queue of iQueues) {
1399
+ const queueTasks = immediate[queue].map((task) => {
1400
+ const executor = taskQueue.getExecutor(task.queue_id, task.type);
1401
+ const shouldStoreOnFailure = executor?.store_on_failure ?? false;
1402
+ const id = shouldStoreOnFailure ? { _id: new mongodb.ObjectId() } : {};
1403
+ return { ...id, ...task };
1404
+ });
1405
+ try {
1406
+ await this.messageQueue.addTasks(queue, queueTasks);
1407
+ logger$3.info(`[AsyncActions] Added ${queueTasks.length} immediate tasks to queue ${queue}`);
1408
+ } catch (err) {
1409
+ logger$3.error(`[AsyncActions] Failed to add tasks to queue ${queue}:`, err);
1410
+ throw err;
1411
+ }
1412
+ }
1413
+ if (future.length > 0) {
1414
+ const futureTasks = future.map((task) => {
1415
+ const executor = taskQueue.getExecutor(task.queue_id, task.type);
1416
+ const shouldStoreOnFailure = executor?.store_on_failure ?? false;
1417
+ const id = shouldStoreOnFailure ? { _id: new mongodb.ObjectId() } : {};
1418
+ return { ...id, ...task };
1419
+ });
1420
+ try {
1421
+ await TaskStore.addTasksToScheduled(futureTasks);
1422
+ logger$3.info(`[AsyncActions] Added ${futureTasks.length} future tasks to database`);
1423
+ } catch (err) {
1424
+ logger$3.error(`[AsyncActions] Failed to add tasks to database:`, err);
1425
+ throw err;
1426
+ }
1427
+ }
1428
+ }
1429
+ }
1430
+ const logger$2 = new Logger("TaskRunner", LogLevel.INFO);
1431
+ const lock$1 = new LockManager(cacheProvider, { prefix: "task_lock_", defaultTimeout: 30 * 60 });
1432
+ async function taskRunner(messageQueue, taskRunnerId, tasksRaw, asyncTaskManager2) {
1433
+ logger$2.info(`[${taskRunnerId}] Starting task runner`);
1434
+ logger$2.info(`[${taskRunnerId}] Processing ${tasksRaw.length} provided tasks`);
1435
+ const tasks = await lock$1.filterLocked(tasksRaw, tId);
1436
+ logger$2.info(`[${taskRunnerId}] Found ${tasks.length} not locked tasks to process`);
1437
+ await Promise.all(tasks.map((t) => lock$1.acquire(tId(t))));
1438
+ const groupedTasksObject = tasks.reduce((acc, task) => {
1439
+ acc[task.type] = acc[task.type] || [];
1440
+ acc[task.type].push(task);
1441
+ return acc;
1442
+ }, {});
1443
+ const groupedTasksArray = Object.keys(groupedTasksObject).reduce((acc, type) => {
1444
+ acc.push({ type, tasks: groupedTasksObject[type] });
1445
+ return acc;
1446
+ }, []);
1447
+ logger$2.info(`[${taskRunnerId}] Task groups: ${groupedTasksArray.map((g) => `${g.type}: ${g.tasks.length}`).join(", ")}`);
1448
+ const actions = new Actions(taskRunnerId);
1449
+ const asyncTasks = [];
1450
+ for (let i = 0; i < groupedTasksArray.length; i++) {
1451
+ const taskGroup = groupedTasksArray[i];
1452
+ const firstTask = taskGroup.tasks[0];
1453
+ if (!firstTask) {
1454
+ logger$2.warn(`[${taskRunnerId}] No tasks found for type: ${taskGroup.type}`);
1455
+ continue;
1456
+ }
1457
+ const executor = taskQueue.getExecutor(firstTask.queue_id, taskGroup.type);
1458
+ if (!executor) {
1459
+ logger$2.warn(`[${taskRunnerId}] No executor found for type: ${taskGroup.type} in queue ${firstTask.queue_id}`);
1460
+ for (const task of taskGroup.tasks) {
1461
+ const taskWithId = task._id ? task : {
1462
+ ...task,
1463
+ _id: ""
1464
+ /*generate random id*/
1465
+ };
1466
+ actions.addIgnoredTask(taskWithId);
1467
+ }
1468
+ continue;
1469
+ }
1470
+ if (executor.asyncConfig?.handoffTimeout && asyncTaskManager2 && !asyncTaskManager2.canAcceptTask()) {
1471
+ logger$2.warn(`[${taskRunnerId}] Async queue full, rescheduling ${taskGroup.tasks.length} ${taskGroup.type} tasks for 3 min later`);
1472
+ const rescheduledTasks = taskGroup.tasks.map((task) => ({
1473
+ ...task,
1474
+ execute_at: new Date(Date.now() + 18e4),
1475
+ // 3 minutes
1476
+ status: "scheduled"
1477
+ }));
1478
+ await TaskStore.updateTasksForRetry(rescheduledTasks);
1479
+ continue;
1480
+ }
1481
+ logger$2.info(`[${taskRunnerId}] Processing ${taskGroup.tasks.length} tasks of type: ${taskGroup.type}`);
1482
+ if (executor.multiple) {
1483
+ await executor.onTasks(taskGroup.tasks, actions).catch((err) => logger$2.error(`[${taskRunnerId}] executor.onTasks failed: ${err}`));
1484
+ } else {
1485
+ if (executor.parallel) {
1486
+ const chunks = chunk(taskGroup.tasks, executor.chunkSize);
1487
+ logger$2.info(`[${taskRunnerId}] Processing in parallel chunks of ${executor.chunkSize}`);
1488
+ for (const chunk2 of chunks) {
1489
+ const chunkTasks = [];
1490
+ for (let j = 0; j < chunk2.length; j++) {
1491
+ const taskActions = actions.forkForTask(chunk2[j]);
1492
+ chunkTasks.push(executor.onTask(chunk2[j], taskActions).catch((err) => logger$2.error(`[${taskRunnerId}] executor.onTask failed: ${err}`)));
1493
+ }
1494
+ await Promise.all(chunkTasks);
1495
+ }
1496
+ } else {
1497
+ const timeoutMs = executor.asyncConfig?.handoffTimeout;
1498
+ for (let j = 0; j < taskGroup.tasks.length; j++) {
1499
+ const task = taskGroup.tasks[j];
1500
+ if (!timeoutMs) {
1501
+ const taskActions = actions.forkForTask(task);
1502
+ await executor.onTask(task, taskActions).catch((err) => logger$2.error(`[${taskRunnerId}] executor.onTask failed: ${err}`));
1503
+ } else {
1504
+ const startTime = Date.now();
1505
+ const taskActions = actions.forkForTask(task);
1506
+ const taskPromise = executor.onTask(task, taskActions).catch((err) => {
1507
+ logger$2.error(`[${taskRunnerId}] executor.onTask failed: ${err}`);
1508
+ });
1509
+ const timeoutPromise = new Promise(
1510
+ (resolve) => setTimeout(() => {
1511
+ resolve("~~~timeout");
1512
+ }, timeoutMs)
1513
+ );
1514
+ const result = await Promise.race([taskPromise, timeoutPromise]);
1515
+ if (result === "~~~timeout") {
1516
+ logger$2.info(`[${taskRunnerId}] Task ${tId(task)} (${task.type}) exceeded ${timeoutMs}ms, marking for async handoff`);
1517
+ if (!asyncTaskManager2) {
1518
+ throw new Error(`Task ${task.type} exceeded timeout but AsyncTaskManager not initialized!`);
1519
+ }
1520
+ if (!task._id) {
1521
+ logger$2.error(`[${taskRunnerId}] Cannot hand off task without _id (type: ${task.type}). Task will continue but won't be tracked.`);
1522
+ } else {
1523
+ const asyncActions = new AsyncActions(messageQueue, actions, task);
1524
+ const asyncPromise = taskPromise.finally(async () => {
1525
+ try {
1526
+ await asyncActions.onPromiseFulfilled();
1527
+ } catch (err) {
1528
+ logger$2.error(`[${taskRunnerId}] Failed to execute async actions for task ${tId(task)}:`, err);
1529
+ }
1530
+ });
1531
+ asyncTasks.push({
1532
+ task,
1533
+ promise: asyncPromise,
1534
+ startTime,
1535
+ actions: asyncActions
1536
+ });
1537
+ }
1538
+ }
1539
+ }
1540
+ }
1541
+ }
1542
+ }
1543
+ }
1544
+ const asyncTaskIds = asyncTasks.map((at) => tId(at.task));
1545
+ const results = actions.extractSyncResults(asyncTaskIds);
1546
+ logger$2.info(`[${taskRunnerId}] Completing run - Success: ${results.successTasks.length}, Failed: ${results.failedTasks.length}, New: ${results.newTasks.length}, Async: ${asyncTasks.length}, Ignored: ${results.ignoredTasks.length}`);
1547
+ await Promise.all(tasks.map((t) => lock$1.release(tId(t))));
1548
+ return { ...results, asyncTasks };
1549
+ }
1550
+ function getEnabledQueues() {
1551
+ let enabledQueues = process.env.ENABLED_QUEUES ? JSON.parse(process.env.ENABLED_QUEUES) : ["queue-all"];
1552
+ if (enabledQueues.length === 0) throw new Error("No queues enabled");
1553
+ enabledQueues = enabledQueues.map(mq.getEnvironmentQueueName);
1554
+ const queues = taskQueue.getQueues().filter((queue) => enabledQueues.includes(queue));
1555
+ return queues.map(mq.getEnvironmentQueueName);
1556
+ }
1557
+ const METRICS_KEY_PREFIX = "task_metrics:";
1558
+ const DISCARDED_TASKS_KEY = `${METRICS_KEY_PREFIX}discarded_tasks`;
1559
+ const queueStats = /* @__PURE__ */ new Map();
1560
+ const STATS_THRESHOLD = parseInt(process.env.TQ_STATS_THRESHOLD || "1000");
1561
+ const FAILURE_THRESHOLD = parseInt(process.env.TQ_STATS_FAILURE_THRESHOLD || "100");
1562
+ const INSTANCE_ID = process.env.INSTANCE_ID || "unknown";
1563
+ const logger$1 = new Logger("TaskHandler", LogLevel.INFO);
1564
+ const lock = new LockManager(cacheProvider, {
1565
+ prefix: "mature_task_lock_",
1566
+ defaultTimeout: 20
1567
+ });
1568
+ let asyncTaskManager = null;
1569
+ async function trackDiscardedTasks(count) {
1570
+ try {
1571
+ const now = moment.utc();
1572
+ const hourKey = `${DISCARDED_TASKS_KEY}:${now.format("YYYY-MM-DD-HH")}`;
1573
+ const currentHourCountStr = await cacheProvider.get(hourKey) || "0";
1574
+ const currentHourCount = parseInt(currentHourCountStr, 10);
1575
+ const newCount = currentHourCount + count;
1576
+ await cacheProvider.set(hourKey, newCount.toString(), 25 * 3600);
1577
+ let total = 0;
1578
+ try {
1579
+ if (Math.random() < 0.1) {
1580
+ for (let i = 0; i < 24; i++) {
1581
+ const hourOffset = moment.utc().subtract(i, "hours");
1582
+ const pastHourKey = `${DISCARDED_TASKS_KEY}:${hourOffset.format("YYYY-MM-DD-HH")}`;
1583
+ const pastHourCountStr = await cacheProvider.get(pastHourKey) || "0";
1584
+ total += parseInt(pastHourCountStr, 10);
1585
+ }
1586
+ logger$1.info(`Added ${count} discarded tasks to metrics. Last 24h total: ${total}`);
1587
+ } else {
1588
+ logger$1.info(`Added ${count} discarded tasks to current hour metrics.`);
1589
+ }
1590
+ } catch (error) {
1591
+ logger$1.info(`Added ${count} discarded tasks to current hour metrics.`);
1592
+ }
1593
+ } catch (error) {
1594
+ logger$1.error(`Failed to track discarded tasks: ${error}`);
1595
+ }
1596
+ }
1597
+ let matureTaskTimer = null;
1598
+ const getRetryCount = (task) => {
1599
+ if (typeof task.retries === "number") return task.retries;
1600
+ const executor = taskQueue.getExecutor(task.queue_id, task.type);
1601
+ return executor?.default_retries ?? 3;
1602
+ };
1603
+ async function addTasks(messageQueue, tasks) {
1604
+ const diffedItems = tasks.reduce(
1605
+ (acc, { force_store, ...task }) => {
1606
+ const currentTime = /* @__PURE__ */ new Date();
1607
+ const executeTime = task.execute_at;
1608
+ const timeDifference = (executeTime.getTime() - currentTime.getTime()) / 1e3 / 60;
1609
+ const queue = task.queue_id;
1610
+ if (timeDifference > 2 || force_store) {
1611
+ acc.future[queue] = acc.future[queue] || [];
1612
+ acc.future[queue].push(task);
1613
+ } else {
1614
+ acc.immediate[queue] = acc.immediate[queue] || [];
1615
+ acc.immediate[queue].push(task);
1616
+ }
1617
+ return acc;
1618
+ },
1619
+ {
1620
+ future: {},
1621
+ immediate: {}
1622
+ }
1623
+ );
1624
+ const iQueues = Object.keys(diffedItems.immediate);
1625
+ for (let i = 0; i < iQueues.length; i++) {
1626
+ const queue = iQueues[i];
1627
+ const tasks2 = diffedItems.immediate[queue].map((task) => {
1628
+ const executor = taskQueue.getExecutor(task.queue_id, task.type);
1629
+ const shouldStoreOnFailure = executor?.store_on_failure ?? false;
1630
+ const id = shouldStoreOnFailure ? { _id: new mongodb.ObjectId() } : {};
1631
+ return { ...id, ...task };
1632
+ });
1633
+ await messageQueue.addTasks(queue, tasks2);
1634
+ }
1635
+ const fQueues = Object.keys(diffedItems.future);
1636
+ for (let i = 0; i < fQueues.length; i++) {
1637
+ const queue = fQueues[i];
1638
+ const tasks2 = diffedItems.future[queue].map((task) => {
1639
+ const executor = taskQueue.getExecutor(task.queue_id, task.type);
1640
+ const shouldStoreOnFailure = executor?.store_on_failure ?? false;
1641
+ const id = shouldStoreOnFailure ? { _id: new mongodb.ObjectId() } : {};
1642
+ return { ...id, ...task };
1643
+ });
1644
+ await TaskStore.addTasksToScheduled(tasks2);
1645
+ }
1646
+ }
1647
+ async function postProcessTasks(messageQueue, {
1648
+ failedTasks: failedTasksRaw,
1649
+ newTasks,
1650
+ successTasks
1651
+ }) {
1652
+ const tasksToRetry = [];
1653
+ const finalFailedTasks = [];
1654
+ let discardedTasksCount = 0;
1655
+ for (const task of failedTasksRaw) {
1656
+ const taskRetryCount = task.execution_stats && typeof task.execution_stats.retry_count === "number" ? task.execution_stats.retry_count : 0;
1657
+ const taskRetryAfter = task.retry_after || 2e3;
1658
+ const retryAfter = taskRetryAfter * Math.pow(taskRetryCount + 1, 2);
1659
+ const executeAt = Date.now() + retryAfter;
1660
+ const maxRetries = getRetryCount(task);
1661
+ if (task._id && taskRetryCount < maxRetries) {
1662
+ tasksToRetry.push({
1663
+ ...task,
1664
+ status: "scheduled",
1665
+ execute_at: new Date(executeAt),
1666
+ execution_stats: {
1667
+ ...task.execution_stats || {},
1668
+ retry_count: taskRetryCount + 1
1669
+ }
1670
+ });
1671
+ } else if (task._id) {
1672
+ finalFailedTasks.push(task);
1673
+ } else if (taskRetryCount < maxRetries) {
1674
+ const shouldStoreOnFailure = taskQueue.getExecutor(task.queue_id, task.type)?.store_on_failure;
1675
+ if (shouldStoreOnFailure) {
1676
+ tasksToRetry.push({
1677
+ ...task,
1678
+ _id: new mongodb.ObjectId(),
1679
+ status: "scheduled",
1680
+ execute_at: new Date(executeAt),
1681
+ execution_stats: {
1682
+ ...task.execution_stats || {},
1683
+ retry_count: taskRetryCount + 1
1684
+ }
1685
+ });
1686
+ } else {
1687
+ await addTasks(messageQueue, [{
1688
+ ...task,
1689
+ status: "scheduled",
1690
+ execute_at: new Date(executeAt),
1691
+ execution_stats: {
1692
+ ...task.execution_stats || {},
1693
+ retry_count: taskRetryCount + 1
1694
+ }
1695
+ }]);
1696
+ }
1697
+ } else {
1698
+ discardedTasksCount++;
1699
+ logger$1.info(`Discarding task of type ${task.type} after ${taskRetryCount} retries`);
1700
+ }
1701
+ }
1702
+ if (discardedTasksCount > 0) {
1703
+ await trackDiscardedTasks(discardedTasksCount);
1704
+ }
1705
+ if (tasksToRetry.length > 0) {
1706
+ await TaskStore.updateTasksForRetry(tasksToRetry);
1707
+ }
1708
+ if (newTasks.length > 0) {
1709
+ await addTasks(messageQueue, newTasks);
1710
+ }
1711
+ if (finalFailedTasks.length > 0) {
1712
+ const taskIds = finalFailedTasks.map((task) => task._id);
1713
+ await TaskStore.markTasksAsFailed(taskIds);
1714
+ }
1715
+ if (successTasks.length > 0) {
1716
+ await TaskStore.markTasksAsSuccess(successTasks);
1717
+ }
1718
+ }
1719
+ async function reportQueueStats(queueName, forceSend = false) {
1720
+ const stats = queueStats.get(queueName);
1721
+ if (!stats) return;
1722
+ const total = stats.success + stats.failed + stats.async + stats.ignored;
1723
+ if (total === 0) return;
1724
+ if (!forceSend && total < STATS_THRESHOLD && stats.failed < FAILURE_THRESHOLD) return;
1725
+ `[${INSTANCE_ID}] TQ Stats for ${queueName}:
1726
+ ✅ Success: ${stats.success}
1727
+ ❌ Failed: ${stats.failed}
1728
+ ⏳ Async: ${stats.async}
1729
+ 🚫 Ignored: ${stats.ignored}`;
1730
+ try {
1731
+ logger$1.info(`Sent stats for ${queueName}`);
1732
+ } catch (err) {
1733
+ logger$1.error(`Failed to send stats: ${err}`);
1734
+ }
1735
+ if (!forceSend) {
1736
+ stats.success = 0;
1737
+ stats.failed = 0;
1738
+ stats.async = 0;
1739
+ stats.ignored = 0;
1740
+ }
1741
+ }
1742
+ function startConsumingTasks(messageQueue, streamName) {
1743
+ return messageQueue.consumeTasks(streamName, async (id, tasks) => {
1744
+ logger$1.debug(`Processing ${tasks.length} tasks for stream ${streamName}`);
1745
+ const {
1746
+ failedTasks,
1747
+ newTasks,
1748
+ successTasks,
1749
+ asyncTasks,
1750
+ ignoredTasks
1751
+ } = await taskRunner(messageQueue, id, tasks, asyncTaskManager || void 0).catch((err) => {
1752
+ logger$1.error("Failed to execute tasks?", err);
1753
+ return { failedTasks: [], newTasks: [], successTasks: [], asyncTasks: [], ignoredTasks: [] };
1754
+ });
1755
+ if (asyncTasks.length > 0 && !asyncTaskManager) {
1756
+ throw new Error("Async tasks detected but AsyncTaskManager not initialized!");
1757
+ }
1758
+ if (asyncTasks.length > 0) {
1759
+ logger$1.info(`Handling ${asyncTasks.length} async tasks for stream ${streamName}`);
1760
+ for (const asyncTask of asyncTasks) {
1761
+ const accepted = asyncTaskManager.handoffTask(asyncTask.task, asyncTask.promise);
1762
+ if (!accepted) {
1763
+ logger$1.warn(`Async queue full, requeueing task ${asyncTask.task._id} with 30s delay`);
1764
+ await addTasks(messageQueue, [{
1765
+ ...asyncTask.task,
1766
+ execute_at: new Date(Date.now() + 3e4)
1767
+ // 30 second delay
1768
+ }]);
1769
+ }
1770
+ }
1771
+ }
1772
+ if (ignoredTasks.length > 0) {
1773
+ logger$1.warn(`Storing ${ignoredTasks.length} ignored tasks with no executor for stream ${streamName}`);
1774
+ await TaskStore.markTasksAsIgnored(ignoredTasks).catch((err) => {
1775
+ logger$1.error("Failed to mark tasks as ignored", err);
1776
+ });
1777
+ }
1778
+ await postProcessTasks(messageQueue, { failedTasks, newTasks, successTasks }).catch((err) => {
1779
+ logger$1.error("Failed to postProcessTasks", err);
1780
+ });
1781
+ if (!queueStats.has(streamName)) {
1782
+ queueStats.set(streamName, {
1783
+ success: 0,
1784
+ failed: 0,
1785
+ async: 0,
1786
+ ignored: 0
1787
+ });
1788
+ }
1789
+ const stats = queueStats.get(streamName);
1790
+ stats.success += successTasks.length;
1791
+ stats.failed += failedTasks.length;
1792
+ stats.async += asyncTasks.length;
1793
+ stats.ignored += ignoredTasks.length;
1794
+ await reportQueueStats(streamName);
1795
+ logger$1.debug(`Completed processing for stream ${streamName}: ${successTasks.length} succeeded, ${failedTasks.length} failed, ${newTasks.length} new tasks, ${ignoredTasks.length} ignored`);
1796
+ return { failedTasks, newTasks, successTasks };
1797
+ });
1798
+ }
1799
+ function processMatureTasks(messageQueue) {
1800
+ const LOCK_ID = "task_processor";
1801
+ if (matureTaskTimer) clearInterval(matureTaskTimer);
1802
+ matureTaskTimer = setInterval(async () => {
1803
+ if (await lock.isLocked(LOCK_ID)) {
1804
+ logger$1.info("Mature task runner locked");
1805
+ return;
1806
+ }
1807
+ try {
1808
+ await lock.acquire(LOCK_ID);
1809
+ const matureTasks = await TaskStore.getMatureTasks(Date.now());
1810
+ logger$1.debug(`Found ${matureTasks.length} mature tasks to process`);
1811
+ await addTasks(messageQueue, matureTasks);
1812
+ } catch (error) {
1813
+ logger$1.error(`Error processing tasks: ${error}`);
1814
+ } finally {
1815
+ await lock.release(LOCK_ID);
1816
+ }
1817
+ }, 5e3);
1818
+ }
1819
+ function taskProcessServer(messageQueue) {
1820
+ const queues = getEnabledQueues();
1821
+ for (let i = 0; i < queues.length; i++) {
1822
+ logger$1.info(`Starting consumer for queue: ${queues[i]}`);
1823
+ startConsumingTasks(messageQueue, queues[i]);
1824
+ }
1825
+ logger$1.info("Starting mature tasks processor");
1826
+ processMatureTasks(messageQueue);
1827
+ }
1828
+ function processBatch(messageQueue, queueId, processor, limit) {
1829
+ return messageQueue.processBatch(queueId, processor, limit);
1830
+ }
1831
+ function setAsyncTaskManager(manager) {
1832
+ asyncTaskManager = manager;
1833
+ logger$1.info("Async task manager set");
1834
+ }
1835
+ const taskHandler = {
1836
+ processBatch,
1837
+ processMatureTasks,
1838
+ startConsumingTasks,
1839
+ postProcessTasks,
1840
+ addTasks,
1841
+ taskProcessServer,
1842
+ setAsyncTaskManager
1843
+ };
1844
+ const logger = new Logger("AsyncTaskManager", LogLevel.INFO);
1845
+ class AsyncTaskManager {
1846
+ constructor(maxTasks = 100) {
1847
+ this.asyncTasks = /* @__PURE__ */ new Map();
1848
+ this.handedOffTaskIds = /* @__PURE__ */ new Set();
1849
+ this.totalHandedOff = 0;
1850
+ this.maxTasks = maxTasks;
1851
+ logger.info(`AsyncTaskManager initialized with max ${maxTasks} concurrent tasks`);
1852
+ }
1853
+ handoffTask(task, runningPromise) {
1854
+ if (!task._id) {
1855
+ logger.error(`Cannot hand off task without _id (type: ${task.type})`);
1856
+ return false;
1857
+ }
1858
+ const taskId = task._id.toString();
1859
+ if (this.asyncTasks.size >= this.maxTasks) {
1860
+ logger.warn(`Async queue full (${this.asyncTasks.size}/${this.maxTasks}), rejecting task ${taskId}`);
1861
+ return false;
1862
+ }
1863
+ const entry = {
1864
+ task,
1865
+ promise: runningPromise,
1866
+ startTime: Date.now()
1867
+ };
1868
+ this.asyncTasks.set(taskId, entry);
1869
+ this.handedOffTaskIds.add(taskId);
1870
+ this.totalHandedOff++;
1871
+ logger.info(`Task ${taskId} (${task.type}) handed off to async processing (queue: ${this.asyncTasks.size}/${this.maxTasks})`);
1872
+ runningPromise.then(() => {
1873
+ const duration = Date.now() - entry.startTime;
1874
+ logger.info(`Async task ${taskId} completed after ${duration}ms`);
1875
+ }).catch((error) => {
1876
+ const duration = Date.now() - entry.startTime;
1877
+ logger.error(`Async task ${taskId} errored after ${duration}ms:`, error);
1878
+ }).finally(() => {
1879
+ this.asyncTasks.delete(taskId);
1880
+ this.handedOffTaskIds.delete(taskId);
1881
+ logger.debug(`Task ${taskId} removed from async queue (remaining: ${this.asyncTasks.size})`);
1882
+ });
1883
+ return true;
1884
+ }
1885
+ async shutdown() {
1886
+ logger.info(`Shutting down AsyncTaskManager with ${this.asyncTasks.size} tasks still running`);
1887
+ const gracePeriod = 1e4;
1888
+ logger.info(`Waiting ${gracePeriod}ms for tasks to complete...`);
1889
+ await new Promise((resolve) => setTimeout(resolve, gracePeriod));
1890
+ if (this.asyncTasks.size > 0) {
1891
+ logger.warn(`${this.asyncTasks.size} tasks still running after grace period, they will continue in background`);
1892
+ for (const [taskId, entry] of this.asyncTasks) {
1893
+ const runtime = Date.now() - entry.startTime;
1894
+ logger.info(`Task ${taskId} (${entry.task.type}) has been running for ${runtime}ms`);
1895
+ }
1896
+ }
1897
+ logger.info("AsyncTaskManager shutdown complete");
1898
+ }
1899
+ getMetrics() {
1900
+ return {
1901
+ activeTaskCount: this.asyncTasks.size,
1902
+ totalHandedOff: this.totalHandedOff,
1903
+ maxTasks: this.maxTasks,
1904
+ utilizationPercent: this.asyncTasks.size / this.maxTasks * 100
1905
+ };
1906
+ }
1907
+ isHandedOff(taskId) {
1908
+ return this.handedOffTaskIds.has(taskId);
1909
+ }
1910
+ canAcceptTask() {
1911
+ return this.asyncTasks.size < this.maxTasks;
1912
+ }
1913
+ }
1914
+ class TaskQueue {
1915
+ constructor() {
1916
+ this.queueTaskExecutorMap = /* @__PURE__ */ new Map();
1917
+ }
1918
+ /**
1919
+ * Registers a task executor with a message queue and queue name
1920
+ * @param messageQueue The message queue to register with
1921
+ * @param queueName The name of the queue
1922
+ * @param taskType The type of task
1923
+ * @param executor The executor for the task
1924
+ */
1925
+ register(messageQueue, queueName, taskType, executor) {
1926
+ queueName = mq.getEnvironmentQueueName(queueName);
1927
+ messageQueue.register(queueName);
1928
+ if (!this.queueTaskExecutorMap.has(queueName)) {
1929
+ this.queueTaskExecutorMap.set(queueName, /* @__PURE__ */ new Map());
1930
+ }
1931
+ const queueMap = this.queueTaskExecutorMap.get(queueName);
1932
+ queueMap.set(taskType, executor);
1933
+ console.log(`Registered task executor for ${taskType} on queue ${queueName}`);
1934
+ }
1935
+ /**
1936
+ * Gets the task executor for a specific queue and task type
1937
+ * @param queueName The name of the queue
1938
+ * @param taskType The type of task
1939
+ * @returns The executor for the task
1940
+ */
1941
+ getExecutor(queueName, taskType) {
1942
+ queueName = mq.getEnvironmentQueueName(queueName);
1943
+ const queueMap = this.queueTaskExecutorMap.get(queueName);
1944
+ if (!queueMap) {
1945
+ return void 0;
1946
+ }
1947
+ return queueMap.get(taskType);
1948
+ }
1949
+ /**
1950
+ * Gets all registered queues
1951
+ * @returns Array of queue names
1952
+ */
1953
+ getQueues() {
1954
+ return Array.from(this.queueTaskExecutorMap.keys());
1955
+ }
1956
+ /**
1957
+ * Gets all task types for a specific queue
1958
+ * @param queueName The name of the queue
1959
+ * @returns Array of task types
1960
+ */
1961
+ getTasksForQueue(queueName) {
1962
+ queueName = mq.getEnvironmentQueueName(queueName);
1963
+ const queueMap = this.queueTaskExecutorMap.get(queueName);
1964
+ if (!queueMap) {
1965
+ return [];
1966
+ }
1967
+ return Array.from(queueMap.keys());
1968
+ }
1969
+ }
1970
+ const taskQueue = new TaskQueue();
1971
+ exports.CronTaskType = types.CronTaskType;
1972
+ exports.Actions = Actions;
1973
+ exports.AsyncActions = AsyncActions;
1974
+ exports.AsyncTaskManager = AsyncTaskManager;
1975
+ exports.MemoryCronTasksAdapter = MemoryCronTasksAdapter;
1976
+ exports.MongoDbAdapter = MongoDbAdapter;
1977
+ exports.TaskQueue = TaskQueue;
1978
+ exports.TaskStore = TaskStore;
1979
+ exports.databaseAdapter = databaseAdapter;
1980
+ exports.default = taskQueue;
1981
+ exports.getEnabledQueues = getEnabledQueues;
1982
+ exports.tId = tId;
1983
+ exports.taskHandler = taskHandler;
1984
+ exports.taskRunner = taskRunner;
1985
+ //# sourceMappingURL=index.js.map