@orieljs/queue 0.1.0-alpha.14 → 0.1.0-alpha.16

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 CHANGED
@@ -348,6 +348,56 @@ function decodePayload(raw) {
348
348
 
349
349
  // jobs/BaseJob.ts
350
350
  import { FailedJobProvider } from "@orieljs/contracts";
351
+
352
+ // events.ts
353
+ import { EventDispatcher } from "@orieljs/contracts";
354
+ var JobQueued = class {
355
+ constructor(connectionName, queue, id, job, payload, delay) {
356
+ this.connectionName = connectionName;
357
+ this.queue = queue;
358
+ this.id = id;
359
+ this.job = job;
360
+ this.payload = payload;
361
+ this.delay = delay;
362
+ }
363
+ connectionName;
364
+ queue;
365
+ id;
366
+ job;
367
+ payload;
368
+ delay;
369
+ };
370
+ var JobProcessing = class {
371
+ constructor(connectionName, job) {
372
+ this.connectionName = connectionName;
373
+ this.job = job;
374
+ }
375
+ connectionName;
376
+ job;
377
+ };
378
+ var JobProcessed = class {
379
+ constructor(connectionName, job) {
380
+ this.connectionName = connectionName;
381
+ this.job = job;
382
+ }
383
+ connectionName;
384
+ job;
385
+ };
386
+ var JobFailed = class {
387
+ constructor(connectionName, job, exception) {
388
+ this.connectionName = connectionName;
389
+ this.job = job;
390
+ this.exception = exception;
391
+ }
392
+ connectionName;
393
+ job;
394
+ exception;
395
+ };
396
+ async function dispatchQueueEvent(container, event) {
397
+ if (container.bound(EventDispatcher)) await container.make(EventDispatcher).dispatch(event);
398
+ }
399
+
400
+ // jobs/BaseJob.ts
351
401
  var BaseJob = class {
352
402
  constructor(context, queue) {
353
403
  this.context = context;
@@ -416,7 +466,8 @@ var BaseJob = class {
416
466
  }
417
467
  /**
418
468
  * Marks the job as failed, deletes it, runs the handler's failure bookkeeping (unique lock, batch, chain catch,
419
- * the job's failed() hook) and stores it with the FailedJobProvider. A job that was already deleted is ignored.
469
+ * the job's failed() hook), stores it with the FailedJobProvider and dispatches JobFailed. A job that was already
470
+ * deleted is ignored.
420
471
  */
421
472
  async fail(error) {
422
473
  this.markAsFailed();
@@ -427,8 +478,12 @@ var BaseJob = class {
427
478
  await this.context.handler.failed(this, reason);
428
479
  } finally {
429
480
  const { container } = this.context;
430
- if (container.bound(FailedJobProvider)) {
431
- await container.make(FailedJobProvider).log(this.getConnectionName(), this.getQueue(), this.payload(), reason);
481
+ try {
482
+ if (container.bound(FailedJobProvider)) {
483
+ await container.make(FailedJobProvider).log(this.getConnectionName(), this.getQueue(), this.payload(), reason);
484
+ }
485
+ } finally {
486
+ await dispatchQueueEvent(container, new JobFailed(this.getConnectionName(), this, reason));
432
487
  }
433
488
  }
434
489
  }
@@ -504,13 +559,19 @@ var CallQueuedHandler = class {
504
559
  if (payload.batchId !== void 0 && payload.batchCallback !== true && this.container.bound(BatchRepository)) {
505
560
  await this.container.make(BatchRepository).recordFailedJob(payload.batchId, payload.uuid, error);
506
561
  }
562
+ const chain = { connection: payload.chainConnection ?? job.getConnectionName(), queue: payload.chainQueue };
507
563
  for (const callback of payload.chainCatch ?? []) {
508
- await this.dispatchCallback(await restoreJob(callback, this.container.make(ClassRegistry)));
564
+ await this.dispatchCallback(await restoreJob(callback, this.container.make(ClassRegistry)), chain);
509
565
  }
510
566
  if (instance && typeof instance.failed === "function") await instance.failed(error);
511
567
  }
512
- /** Dispatches a callback job (chain catch, batch then/catch/finally) through the Bus, or runs it inline. */
513
- async dispatchCallback(callback) {
568
+ /**
569
+ * Dispatches a callback job (chain catch, batch then/catch/finally) through the Bus, or runs it inline. It goes to
570
+ * `target`'s connection and queue (the chain's or the batch's) unless it names its own.
571
+ */
572
+ async dispatchCallback(callback, target = {}) {
573
+ if (!callback.connection && target.connection) callback.connection = target.connection;
574
+ if (!callback.queue && target.queue) callback.queue = target.queue;
514
575
  if (this.container.bound(BusDispatcher)) await this.container.make(BusDispatcher).dispatch(callback);
515
576
  else await callback.handle();
516
577
  }
@@ -548,13 +609,15 @@ var CallQueuedHandler = class {
548
609
  await this.container.make(BatchRepository).recordSuccessfulJob(payload.batchId, payload.uuid);
549
610
  }
550
611
  async releaseUniqueLock(payload) {
551
- const lock = payload.uniqueLock;
552
- if (!lock || !this.container.bound(CacheManager)) return;
553
- const cache = this.container.make(CacheManager);
554
- const store = lock.store !== void 0 ? cache.store(lock.store) : cache;
555
- await store.lock(lock.key).forceRelease();
612
+ await releaseUniqueLock(this.container, payload.uniqueLock);
556
613
  }
557
614
  };
615
+ async function releaseUniqueLock(container, lock) {
616
+ if (!lock || !container.bound(CacheManager)) return;
617
+ const cache = container.make(CacheManager);
618
+ const store = lock.store !== void 0 ? cache.store(lock.store) : cache;
619
+ await store.lock(lock.key).forceRelease();
620
+ }
558
621
 
559
622
  // middleware/WithoutOverlapping.ts
560
623
  import { CacheManager as CacheManager2 } from "@orieljs/contracts";
@@ -611,7 +674,104 @@ var WithoutOverlapping = class {
611
674
 
612
675
  // queues/QueueBase.ts
613
676
  import { randomUUID as randomUUID2 } from "crypto";
614
- import { ClassRegistry as ClassRegistry2, ExceptionHandler, FailedJobProvider as FailedJobProvider2 } from "@orieljs/contracts";
677
+ import {
678
+ ClassRegistry as ClassRegistry2,
679
+ DatabaseManager,
680
+ ExceptionHandler,
681
+ FailedJobProvider as FailedJobProvider2
682
+ } from "@orieljs/contracts";
683
+
684
+ // console/discoverJobs.ts
685
+ import { existsSync, readdirSync, statSync } from "fs";
686
+ import { dirname, join, relative, sep } from "path";
687
+ import { pathToFileURL } from "url";
688
+ import { Application, ClassRegistry as ClassRegistryToken } from "@orieljs/contracts";
689
+ var EXTENSIONS = [".ts", ".js", ".mts", ".mjs"];
690
+ function files(directory) {
691
+ const found = [];
692
+ for (const entry of readdirSync(directory).sort()) {
693
+ const path = join(directory, entry);
694
+ if (statSync(path).isDirectory()) found.push(...files(path));
695
+ else if (EXTENSIONS.some((extension) => entry.endsWith(extension)) && !entry.endsWith(".d.ts")) found.push(path);
696
+ }
697
+ return found;
698
+ }
699
+ var WORKER_DISCOVERY_DIRECTORIES = ["Events", "Listeners", "Mail", "Notifications"];
700
+ var isClass = (value) => typeof value === "function" && /^class[\s{]/.test(Function.prototype.toString.call(value));
701
+ var isJobClass = (value) => typeof value.prototype.handle === "function";
702
+ async function discoverClasses(directory, registry, filter = () => true) {
703
+ if (!existsSync(directory)) return [];
704
+ const names = [];
705
+ for (const file of files(directory)) {
706
+ const module = await import(pathToFileURL(file).href);
707
+ for (const exported of Object.values(module)) {
708
+ if (isClass(exported) && filter(exported)) names.push(classNameOf(registry, exported));
709
+ }
710
+ }
711
+ return names;
712
+ }
713
+ function discoverJobs(directory, registry) {
714
+ return discoverClasses(directory, registry, isJobClass);
715
+ }
716
+ var ready = /* @__PURE__ */ new WeakMap();
717
+ function registerAppClasses(appPath, registry) {
718
+ const running = discover(appPath, registry);
719
+ ready.set(registry, running);
720
+ return running;
721
+ }
722
+ async function discover(appPath, registry) {
723
+ const found = [];
724
+ const seen = /* @__PURE__ */ new Set();
725
+ for (const directory of ["Jobs", ...WORKER_DISCOVERY_DIRECTORIES]) {
726
+ const root = join(appPath, directory);
727
+ if (!existsSync(root)) continue;
728
+ for (const file of files(root)) {
729
+ let module;
730
+ try {
731
+ module = await import(pathToFileURL(file).href);
732
+ } catch (error) {
733
+ console.warn(`Oriel couldn't load ${relative(appPath, file)} to name its classes for the queue: ${error instanceof Error ? error.message : String(error)}`);
734
+ continue;
735
+ }
736
+ const folder = relative(appPath, dirname(file)).split(sep).join(".");
737
+ for (const exported of Object.values(module)) {
738
+ if (!isClass(exported) || seen.has(exported) || directory === "Jobs" && !isJobClass(exported)) continue;
739
+ seen.add(exported);
740
+ found.push({ cls: exported, folder });
741
+ }
742
+ }
743
+ }
744
+ const unnamed = found.filter(({ cls }) => registry.nameOf(cls) === void 0);
745
+ const sharing = /* @__PURE__ */ new Map();
746
+ for (const { cls } of unnamed) sharing.set(cls.name, (sharing.get(cls.name) ?? 0) + 1);
747
+ for (const { cls, folder } of unnamed) {
748
+ if ((sharing.get(cls.name) ?? 0) > 1) {
749
+ registry.register(cls, `${folder}.${cls.name}`);
750
+ continue;
751
+ }
752
+ try {
753
+ classNameOf(registry, cls);
754
+ } catch (error) {
755
+ if (!(error instanceof JobSerializationError)) throw error;
756
+ registry.register(cls, `${folder}.${cls.name}`);
757
+ }
758
+ }
759
+ }
760
+ async function ensureAppClasses(container) {
761
+ const registry = container.make(ClassRegistryToken);
762
+ let running = ready.get(registry);
763
+ if (running === void 0) {
764
+ running = container.bound(Application) ? registerAppClasses(container.make(Application).appPath(), registry) : Promise.resolve();
765
+ running = running.catch((error) => {
766
+ ready.delete(registry);
767
+ throw error;
768
+ });
769
+ ready.set(registry, running);
770
+ }
771
+ await running;
772
+ }
773
+
774
+ // queues/QueueBase.ts
615
775
  var QueueBase = class {
616
776
  constructor(container, defaultQueue = "default") {
617
777
  this.container = container;
@@ -621,6 +781,8 @@ var QueueBase = class {
621
781
  container;
622
782
  defaultQueue;
623
783
  connectionName = "default";
784
+ /** `queue.connections.<name>.after_commit`: work dispatched inside a transaction waits for its commit. */
785
+ dispatchAfterCommit = false;
624
786
  handler;
625
787
  setConnectionName(name) {
626
788
  this.connectionName = name;
@@ -629,6 +791,10 @@ var QueueBase = class {
629
791
  getConnectionName() {
630
792
  return this.connectionName;
631
793
  }
794
+ setDispatchAfterCommit(value) {
795
+ this.dispatchAfterCommit = value;
796
+ return this;
797
+ }
632
798
  /** The queue name to use: the given one, else the connection's default. */
633
799
  getQueue(queue) {
634
800
  return optionalString(queue) || this.defaultQueue;
@@ -636,11 +802,51 @@ var QueueBase = class {
636
802
  createPayload(job) {
637
803
  return createPayload(job, this.container.make(ClassRegistry2));
638
804
  }
639
- push(job, queue) {
640
- return this.pushRaw(this.createPayload(job), queue ?? (optionalString(job.queue) || void 0));
805
+ async push(job, queue) {
806
+ await ensureAppClasses(this.container);
807
+ const payload = this.createPayload(job);
808
+ const name = queue ?? (optionalString(job.queue) || void 0);
809
+ return this.enqueue(job, () => this.pushed(job, payload, name, void 0, this.pushRaw(payload, name)));
641
810
  }
642
- later(delaySeconds, job, queue) {
643
- return this.pushRaw(this.createPayload(job), queue ?? (optionalString(job.queue) || void 0), delaySeconds);
811
+ async later(delaySeconds, job, queue) {
812
+ await ensureAppClasses(this.container);
813
+ const payload = this.createPayload(job);
814
+ const name = queue ?? (optionalString(job.queue) || void 0);
815
+ return this.enqueue(job, () => this.pushed(job, payload, name, delaySeconds, this.pushRaw(payload, name, delaySeconds)));
816
+ }
817
+ /** Waits for the push, then dispatches JobQueued with its id. */
818
+ async pushed(job, payload, queue, delay, push) {
819
+ const id = await push;
820
+ await this.raiseJobQueued(this.getQueue(queue), id, job, payload, delay);
821
+ return id;
822
+ }
823
+ /** Laravel's raiseJobQueuedEvent(). */
824
+ async raiseJobQueued(queue, id, job, payload, delay) {
825
+ await dispatchQueueEvent(this.container, new JobQueued(this.connectionName, queue, id, job, payload, delay));
826
+ }
827
+ /** The job's own `afterCommit`, else the connection's `after_commit`. */
828
+ shouldDispatchAfterCommit(job) {
829
+ return typeof job.afterCommit === "boolean" ? job.afterCommit : this.dispatchAfterCommit;
830
+ }
831
+ /**
832
+ * Laravel's enqueueUsing(): pushes now, or, for a job that waits for the commit, once the database transaction open
833
+ * here commits (resolving '' meanwhile). The payload is made first, so a job that can't be queued fails at dispatch.
834
+ * A rollback drops the push and frees a unique job's lock, as does a push that fails after the commit.
835
+ */
836
+ async enqueue(job, push) {
837
+ if (!this.shouldDispatchAfterCommit(job) || !this.container.bound(DatabaseManager)) return push();
838
+ const lock = symbolValue(job, UNIQUE_LOCK);
839
+ const release = lock === void 0 ? void 0 : () => releaseUniqueLock(this.container, lock);
840
+ let id = "";
841
+ await this.container.make(DatabaseManager).afterCommit(async () => {
842
+ try {
843
+ id = await push();
844
+ } catch (error) {
845
+ await release?.();
846
+ throw error;
847
+ }
848
+ }, release);
849
+ return id;
644
850
  }
645
851
  /** Closes network connections (redis). No-op by default. */
646
852
  async disconnect() {
@@ -677,13 +883,18 @@ var SyncQueue = class extends QueueBase {
677
883
  async pushRaw(payload, queue) {
678
884
  const job = new SyncJob(this.jobContext(), payload, this.getQueue(queue));
679
885
  try {
886
+ await dispatchQueueEvent(this.container, new JobProcessing(this.connectionName, job));
680
887
  await job.fire();
888
+ await dispatchQueueEvent(this.container, new JobProcessed(this.connectionName, job));
681
889
  } catch (error) {
682
890
  if (!job.hasFailed()) await job.fail(error);
683
891
  throw error;
684
892
  }
685
893
  return payload.uuid;
686
894
  }
895
+ /** The job has run already: nothing was queued. */
896
+ async raiseJobQueued(_queue, _id, _job, _payload, _delay) {
897
+ }
687
898
  async pop() {
688
899
  return void 0;
689
900
  }
@@ -720,7 +931,8 @@ var NullQueue = class extends QueueBase {
720
931
  // QueueManager.ts
721
932
  import {
722
933
  ConfigRepository,
723
- DatabaseManager
934
+ DatabaseManager as DatabaseManager2,
935
+ EventDispatcher as EventDispatcher2
724
936
  } from "@orieljs/contracts";
725
937
 
726
938
  // jobs/DatabaseJob.ts
@@ -849,7 +1061,7 @@ var DatabaseQueue = class extends QueueBase {
849
1061
  };
850
1062
 
851
1063
  // queues/RedisQueue.ts
852
- import { Redis } from "ioredis";
1064
+ import { importOptional } from "@orieljs/support";
853
1065
 
854
1066
  // jobs/RedisJob.ts
855
1067
  var RedisJob = class extends BaseJob {
@@ -937,8 +1149,9 @@ return size
937
1149
 
938
1150
  // queues/RedisQueue.ts
939
1151
  var QUEUE_KEYS = ["driver", "connection", "queue", "retry_after", "block_for", "after_commit", "client", "url"];
940
- function makeRedisClient(config) {
1152
+ async function makeRedisClient(config) {
941
1153
  if (config.client) return config.client;
1154
+ const { Redis } = await importOptional("ioredis", "The redis queue connection", () => import("ioredis"));
942
1155
  const options = Object.fromEntries(
943
1156
  Object.entries(config).filter(([key, value]) => value !== void 0 && !QUEUE_KEYS.includes(key))
944
1157
  );
@@ -951,6 +1164,7 @@ function resolveRedisConfig(config, appConfig) {
951
1164
  return appConfig.get(`database.redis.${name}`) ?? config;
952
1165
  }
953
1166
  var RedisQueue = class extends QueueBase {
1167
+ /** `connect` gives the client (or a promise of it), at the queue's first command. */
954
1168
  constructor(container, connect, options = {}) {
955
1169
  super(container, options.queue ?? "default");
956
1170
  this.connect = connect;
@@ -960,7 +1174,7 @@ var RedisQueue = class extends QueueBase {
960
1174
  client;
961
1175
  retryAfter;
962
1176
  redis() {
963
- return this.client ??= this.connect();
1177
+ return this.client ??= Promise.resolve().then(() => this.connect());
964
1178
  }
965
1179
  /** The list key for a queue name: `queues:<name>`. */
966
1180
  key(queue) {
@@ -969,44 +1183,47 @@ var RedisQueue = class extends QueueBase {
969
1183
  async pushRaw(payload, queue, delaySeconds = 0) {
970
1184
  const key = this.key(queue);
971
1185
  const body = encodePayload({ ...payload, attempts: payload.attempts ?? 0 });
972
- if (delaySeconds > 0) await this.redis().zadd(`${key}:delayed`, this.now() + delaySeconds, body);
973
- else await this.redis().eval(PUSH, 2, key, `${key}:notify`, body);
1186
+ const redis = await this.redis();
1187
+ if (delaySeconds > 0) await redis.zadd(`${key}:delayed`, this.now() + delaySeconds, body);
1188
+ else await redis.eval(PUSH, 2, key, `${key}:notify`, body);
974
1189
  return payload.uuid;
975
1190
  }
976
1191
  async pop(queue) {
977
1192
  const key = this.key(queue);
978
1193
  const now = this.now();
979
- await this.redis().eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:delayed`, key, `${key}:notify`, now);
980
- await this.redis().eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:reserved`, key, `${key}:notify`, now);
1194
+ const redis = await this.redis();
1195
+ await redis.eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:delayed`, key, `${key}:notify`, now);
1196
+ await redis.eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:reserved`, key, `${key}:notify`, now);
981
1197
  for (; ; ) {
982
- const [job, reserved] = await this.redis().eval(POP, 3, key, `${key}:reserved`, `${key}:notify`, now + this.retryAfter);
1198
+ const [job, reserved] = await redis.eval(POP, 3, key, `${key}:reserved`, `${key}:notify`, now + this.retryAfter);
983
1199
  if (!job || !reserved) return void 0;
984
1200
  try {
985
1201
  return new RedisJob(this.jobContext(), this, job, reserved, this.getQueue(queue));
986
1202
  } catch (error) {
987
1203
  await this.failCorrupt(this.getQueue(queue), job, error);
988
- await this.redis().zrem(`${key}:reserved`, reserved);
1204
+ await redis.zrem(`${key}:reserved`, reserved);
989
1205
  }
990
1206
  }
991
1207
  }
992
1208
  async size(queue) {
993
1209
  const key = this.key(queue);
994
- return Number(await this.redis().eval(SIZE, 3, key, `${key}:delayed`, `${key}:reserved`));
1210
+ return Number(await (await this.redis()).eval(SIZE, 3, key, `${key}:delayed`, `${key}:reserved`));
995
1211
  }
996
1212
  async clear(queue) {
997
1213
  const key = this.key(queue);
998
- return Number(await this.redis().eval(CLEAR, 4, key, `${key}:delayed`, `${key}:reserved`, `${key}:notify`));
1214
+ return Number(await (await this.redis()).eval(CLEAR, 4, key, `${key}:delayed`, `${key}:reserved`, `${key}:notify`));
999
1215
  }
1000
1216
  async deleteReserved(queue, job) {
1001
- await this.redis().zrem(`${this.key(queue)}:reserved`, job.getReservedJob());
1217
+ await (await this.redis()).zrem(`${this.key(queue)}:reserved`, job.getReservedJob());
1002
1218
  }
1003
1219
  async deleteAndRelease(queue, job, delaySeconds) {
1004
1220
  const key = this.key(queue);
1005
- await this.redis().eval(RELEASE, 2, `${key}:delayed`, `${key}:reserved`, job.getReservedJob(), this.now() + Math.max(0, delaySeconds));
1221
+ await (await this.redis()).eval(RELEASE, 2, `${key}:delayed`, `${key}:reserved`, job.getReservedJob(), this.now() + Math.max(0, delaySeconds));
1006
1222
  }
1007
1223
  async disconnect() {
1008
- const client = this.client;
1224
+ const pending = this.client;
1009
1225
  this.client = void 0;
1226
+ const client = await pending?.catch(() => void 0);
1010
1227
  if (client && client.status !== "end") await client.quit();
1011
1228
  }
1012
1229
  /** Unix seconds, with milliseconds as the fraction (sorted-set scores). */
@@ -1024,7 +1241,7 @@ var QueueManager2 = class {
1024
1241
  this.drivers.set("null", (config) => new NullQueue(container, optionalString(config.queue) || "default"));
1025
1242
  this.drivers.set(
1026
1243
  "database",
1027
- (config) => new DatabaseQueue(container, () => container.make(DatabaseManager).connection(optionalString(config.connection) || void 0), {
1244
+ (config) => new DatabaseQueue(container, () => container.make(DatabaseManager2).connection(optionalString(config.connection) || void 0), {
1028
1245
  table: optionalString(config.table) || "jobs",
1029
1246
  queue: optionalString(config.queue) || "default",
1030
1247
  retryAfter: number(config.retry_after, 90)
@@ -1057,6 +1274,15 @@ var QueueManager2 = class {
1057
1274
  extend(driver, factory) {
1058
1275
  this.drivers.set(driver, factory);
1059
1276
  }
1277
+ before(callback) {
1278
+ this.container.make(EventDispatcher2).listen(JobProcessing, callback);
1279
+ }
1280
+ after(callback) {
1281
+ this.container.make(EventDispatcher2).listen(JobProcessed, callback);
1282
+ }
1283
+ failing(callback) {
1284
+ this.container.make(EventDispatcher2).listen(JobFailed, callback);
1285
+ }
1060
1286
  getDefaultDriver() {
1061
1287
  return optionalString(this.config().get("queue.default")) || "sync";
1062
1288
  }
@@ -1107,6 +1333,7 @@ var QueueManager2 = class {
1107
1333
  if (!driver) throw new UnknownQueueDriverError(driverName);
1108
1334
  const queue = driver(config, name);
1109
1335
  queue.setConnectionName?.(name);
1336
+ queue.setDispatchAfterCommit?.(config.after_commit === true);
1110
1337
  return queue;
1111
1338
  }
1112
1339
  config() {
@@ -1324,6 +1551,7 @@ var DatabaseBatchRepository = class {
1324
1551
  handler;
1325
1552
  async store(options) {
1326
1553
  const id = randomUUID3();
1554
+ await ensureAppClasses(this.container);
1327
1555
  const registry = this.container.make(ClassRegistry3);
1328
1556
  const payloads = (jobs) => jobs.map((job) => createPayload(job, registry));
1329
1557
  const stored = {
@@ -1412,7 +1640,7 @@ var DatabaseBatchRepository = class {
1412
1640
  const job = await restoreJob(payload, registry);
1413
1641
  job.batchId = batch.id;
1414
1642
  setSymbolValue(job, BATCH_CALLBACK, true);
1415
- await this.handler.dispatchCallback(job);
1643
+ await this.handler.dispatchCallback(job, { connection: batch.options.connection, queue: batch.options.queue });
1416
1644
  }
1417
1645
  }
1418
1646
  toBatch(row) {
@@ -1543,12 +1771,16 @@ var Worker = class _Worker {
1543
1771
  process.on("unhandledRejection", onUnhandledRejection);
1544
1772
  return () => process.off("unhandledRejection", onUnhandledRejection);
1545
1773
  }
1546
- /** Processes one job: max-attempts check, fire (with timeout), and failure handling. `_connectionName` is unused (kept for Laravel's signature). */
1547
- async process(_connectionName, job, options) {
1774
+ /**
1775
+ * Processes one job: max-attempts check, fire (with timeout), and failure handling. Dispatches JobProcessing first
1776
+ * and JobProcessed once the job has run without failing (BaseJob.fail() dispatches JobFailed).
1777
+ */
1778
+ async process(connectionName, job, options) {
1548
1779
  const workable = job;
1549
1780
  const started = Date.now();
1550
1781
  try {
1551
1782
  this.listener.processing?.(job);
1783
+ await dispatchQueueEvent(this.container, new JobProcessing(connectionName, job));
1552
1784
  await this.markJobAsFailedIfAlreadyExceedsMaxAttempts(workable, options.maxTries);
1553
1785
  if (job.isDeleted()) return;
1554
1786
  await this.fireWithTimeout(workable, options);
@@ -1557,7 +1789,10 @@ var Worker = class _Worker {
1557
1789
  this.pendingRejection = void 0;
1558
1790
  await pending;
1559
1791
  }
1560
- if (!workable.hasFailed()) this.listener.processed?.(job, Date.now() - started);
1792
+ if (!workable.hasFailed()) {
1793
+ this.listener.processed?.(job, Date.now() - started);
1794
+ await dispatchQueueEvent(this.container, new JobProcessed(connectionName, job));
1795
+ }
1561
1796
  } catch (error) {
1562
1797
  await this.handleJobException(workable, options, error);
1563
1798
  }
@@ -1869,38 +2104,6 @@ var Listener = class _Listener {
1869
2104
  }
1870
2105
  };
1871
2106
 
1872
- // console/discoverJobs.ts
1873
- import { existsSync, readdirSync, statSync } from "fs";
1874
- import { join } from "path";
1875
- import { pathToFileURL } from "url";
1876
- var EXTENSIONS = [".ts", ".js", ".mts", ".mjs"];
1877
- function files(directory) {
1878
- const found = [];
1879
- for (const entry of readdirSync(directory).sort()) {
1880
- const path = join(directory, entry);
1881
- if (statSync(path).isDirectory()) found.push(...files(path));
1882
- else if (EXTENSIONS.some((extension) => entry.endsWith(extension)) && !entry.endsWith(".d.ts")) found.push(path);
1883
- }
1884
- return found;
1885
- }
1886
- var WORKER_DISCOVERY_DIRECTORIES = ["Events", "Listeners", "Mail", "Notifications"];
1887
- var isClass = (value) => typeof value === "function" && /^class[\s{]/.test(Function.prototype.toString.call(value));
1888
- var isJobClass = (value) => typeof value.prototype.handle === "function";
1889
- async function discoverClasses(directory, registry, filter = () => true) {
1890
- if (!existsSync(directory)) return [];
1891
- const names = [];
1892
- for (const file of files(directory)) {
1893
- const module = await import(pathToFileURL(file).href);
1894
- for (const exported of Object.values(module)) {
1895
- if (isClass(exported) && filter(exported)) names.push(classNameOf(registry, exported));
1896
- }
1897
- }
1898
- return names;
1899
- }
1900
- function discoverJobs(directory, registry) {
1901
- return discoverClasses(directory, registry, isJobClass);
1902
- }
1903
-
1904
2107
  // console/commands.ts
1905
2108
  import {
1906
2109
  CacheManager as CacheManager4,
@@ -1973,8 +2176,7 @@ function registerQueueCommands(kernel, context) {
1973
2176
  const connection = text(out.argument("connection")) ?? defaultConnection();
1974
2177
  const queue = text(out.option("queue")) ?? defaultQueue(connection);
1975
2178
  const registry = container.make(ClassRegistry4);
1976
- await discoverJobs(context.app.appPath("Jobs"), registry);
1977
- for (const directory of WORKER_DISCOVERY_DIRECTORIES) await discoverClasses(context.app.appPath(directory), registry);
2179
+ await registerAppClasses(context.app.appPath(), registry);
1978
2180
  const name = (job) => job.payload().displayName;
1979
2181
  const worker = new Worker(container.make(QueueManager3), container, {
1980
2182
  processing: (job) => out.line(` ${localTimestamp()} ${name(job)} RUNNING`),
@@ -2126,7 +2328,7 @@ import {
2126
2328
  BatchRepository as BatchRepository2,
2127
2329
  ConfigRepository as ConfigRepository3,
2128
2330
  ConsoleKernel,
2129
- DatabaseManager as DatabaseManager2,
2331
+ DatabaseManager as DatabaseManager3,
2130
2332
  FailedJobProvider as FailedJobProvider4,
2131
2333
  QueueManager as QueueManagerToken
2132
2334
  } from "@orieljs/contracts";
@@ -2136,10 +2338,10 @@ function makeFailedJobProvider(container) {
2136
2338
  const driver = String(config.get("queue.failed.driver", "database-uuids"));
2137
2339
  if (driver === "null") return new NullFailedJobProvider();
2138
2340
  if (driver !== "database-uuids" && driver !== "database") throw new UnknownQueueDriverError(driver);
2139
- if (!container.bound(DatabaseManager2)) return new NullFailedJobProvider();
2341
+ if (!container.bound(DatabaseManager3)) return new NullFailedJobProvider();
2140
2342
  const database = optionalString(config.get("queue.failed.database")) || void 0;
2141
2343
  const table = String(config.get("queue.failed.table", "failed_jobs"));
2142
- return new DatabaseFailedJobProvider(() => container.make(DatabaseManager2).connection(database), table);
2344
+ return new DatabaseFailedJobProvider(() => container.make(DatabaseManager3).connection(database), table);
2143
2345
  }
2144
2346
  var QueueServiceProvider = class extends ServiceProvider {
2145
2347
  register() {
@@ -2151,12 +2353,12 @@ var QueueServiceProvider = class extends ServiceProvider {
2151
2353
  if (!this.app.resolved(QueueManagerToken)) return;
2152
2354
  await this.app.make(QueueManagerToken).disconnectAll?.();
2153
2355
  });
2154
- if (this.app.bound(DatabaseManager2)) {
2356
+ if (this.app.bound(DatabaseManager3)) {
2155
2357
  this.app.singleton(BatchRepository2, (container) => {
2156
2358
  const config = container.make(ConfigRepository3);
2157
2359
  const database = optionalString(config.get("queue.batching.database")) || void 0;
2158
2360
  const table = String(config.get("queue.batching.table", "job_batches"));
2159
- return new DatabaseBatchRepository(container, () => container.make(DatabaseManager2).connection(database), table);
2361
+ return new DatabaseBatchRepository(container, () => container.make(DatabaseManager3).connection(database), table);
2160
2362
  });
2161
2363
  }
2162
2364
  }
@@ -2175,6 +2377,10 @@ export {
2175
2377
  DatabaseQueue,
2176
2378
  JOBS_TABLE_MIGRATION,
2177
2379
  JobClassNotFoundError,
2380
+ JobFailed,
2381
+ JobProcessed,
2382
+ JobProcessing,
2383
+ JobQueued,
2178
2384
  JobSerializationError,
2179
2385
  Listener,
2180
2386
  ManuallyFailedError,
@@ -2209,6 +2415,7 @@ export {
2209
2415
  discoverClasses,
2210
2416
  discoverJobs,
2211
2417
  encodePayload,
2418
+ ensureAppClasses,
2212
2419
  formatTimestamp,
2213
2420
  isModel,
2214
2421
  listenerOptionsFrom,
@@ -2216,6 +2423,7 @@ export {
2216
2423
  makeRedisClient,
2217
2424
  normalizeBackoff,
2218
2425
  queueConfigDefaults,
2426
+ registerAppClasses,
2219
2427
  registerQueueCommands,
2220
2428
  resolveRedisConfig,
2221
2429
  restoreJob,