@nicnocquee/dataqueue 1.25.0 → 1.26.0-beta.20260223195940

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/ai/build-docs-content.ts +96 -0
  2. package/ai/build-llms-full.ts +42 -0
  3. package/ai/docs-content.json +278 -0
  4. package/ai/rules/advanced.md +132 -0
  5. package/ai/rules/basic.md +159 -0
  6. package/ai/rules/react-dashboard.md +83 -0
  7. package/ai/skills/dataqueue-advanced/SKILL.md +320 -0
  8. package/ai/skills/dataqueue-core/SKILL.md +234 -0
  9. package/ai/skills/dataqueue-react/SKILL.md +189 -0
  10. package/dist/cli.cjs +1149 -14
  11. package/dist/cli.cjs.map +1 -1
  12. package/dist/cli.d.cts +66 -1
  13. package/dist/cli.d.ts +66 -1
  14. package/dist/cli.js +1146 -13
  15. package/dist/cli.js.map +1 -1
  16. package/dist/index.cjs +3157 -1237
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +613 -23
  19. package/dist/index.d.ts +613 -23
  20. package/dist/index.js +3156 -1238
  21. package/dist/index.js.map +1 -1
  22. package/dist/mcp-server.cjs +186 -0
  23. package/dist/mcp-server.cjs.map +1 -0
  24. package/dist/mcp-server.d.cts +32 -0
  25. package/dist/mcp-server.d.ts +32 -0
  26. package/dist/mcp-server.js +175 -0
  27. package/dist/mcp-server.js.map +1 -0
  28. package/migrations/1781200000004_create_cron_schedules_table.sql +33 -0
  29. package/migrations/1781200000005_add_retry_config_to_job_queue.sql +17 -0
  30. package/package.json +24 -21
  31. package/src/backend.ts +170 -5
  32. package/src/backends/postgres.ts +992 -63
  33. package/src/backends/redis-scripts.ts +358 -26
  34. package/src/backends/redis.test.ts +1363 -0
  35. package/src/backends/redis.ts +993 -35
  36. package/src/cli.test.ts +82 -6
  37. package/src/cli.ts +73 -10
  38. package/src/cron.test.ts +126 -0
  39. package/src/cron.ts +40 -0
  40. package/src/db-util.ts +1 -1
  41. package/src/index.test.ts +682 -0
  42. package/src/index.ts +209 -34
  43. package/src/init-command.test.ts +449 -0
  44. package/src/init-command.ts +709 -0
  45. package/src/install-mcp-command.test.ts +216 -0
  46. package/src/install-mcp-command.ts +185 -0
  47. package/src/install-rules-command.test.ts +218 -0
  48. package/src/install-rules-command.ts +233 -0
  49. package/src/install-skills-command.test.ts +176 -0
  50. package/src/install-skills-command.ts +124 -0
  51. package/src/mcp-server.test.ts +162 -0
  52. package/src/mcp-server.ts +231 -0
  53. package/src/processor.ts +36 -97
  54. package/src/queue.test.ts +465 -0
  55. package/src/queue.ts +34 -252
  56. package/src/supervisor.test.ts +340 -0
  57. package/src/supervisor.ts +162 -0
  58. package/src/types.ts +388 -12
  59. package/LICENSE +0 -21
package/dist/index.d.ts CHANGED
@@ -1,7 +1,33 @@
1
1
  import * as pg from 'pg';
2
2
  import { Pool } from 'pg';
3
+ import { Cron } from 'croner';
3
4
 
4
5
  type JobType<PayloadMap> = keyof PayloadMap & string;
6
+ /**
7
+ * Abstract database client interface for transactional job creation.
8
+ * Compatible with `pg.Pool`, `pg.PoolClient`, `pg.Client`, or any object
9
+ * that exposes a `.query()` method matching the `pg` signature.
10
+ */
11
+ interface DatabaseClient {
12
+ query(text: string, values?: any[]): Promise<{
13
+ rows: any[];
14
+ rowCount: number | null;
15
+ }>;
16
+ }
17
+ /**
18
+ * Options for `addJob()` beyond the job itself.
19
+ * Use `db` to insert the job within an existing database transaction.
20
+ */
21
+ interface AddJobOptions {
22
+ /**
23
+ * An external database client (e.g., a `pg.PoolClient` inside a transaction).
24
+ * When provided, the INSERT runs on this client instead of the internal pool,
25
+ * so the job is part of the caller's transaction.
26
+ *
27
+ * **PostgreSQL only.** Throws if used with the Redis backend.
28
+ */
29
+ db?: DatabaseClient;
30
+ }
5
31
  interface JobOptions<PayloadMap, T extends JobType<PayloadMap>> {
6
32
  jobType: T;
7
33
  payload: PayloadMap[T];
@@ -74,6 +100,26 @@ interface JobOptions<PayloadMap, T extends JobType<PayloadMap>> {
74
100
  * Once a key exists, it cannot be reused until the job is cleaned up (via `cleanupOldJobs`).
75
101
  */
76
102
  idempotencyKey?: string;
103
+ /**
104
+ * Base delay between retries in seconds. When `retryBackoff` is true (the default),
105
+ * this is the base for exponential backoff: `retryDelay * 2^attempts`.
106
+ * When `retryBackoff` is false, retries use this fixed delay.
107
+ * @default 60
108
+ */
109
+ retryDelay?: number;
110
+ /**
111
+ * Whether to use exponential backoff for retries. When true, delay doubles
112
+ * with each attempt and includes jitter to prevent thundering herd.
113
+ * When false, a fixed `retryDelay` is used between every retry.
114
+ * @default true
115
+ */
116
+ retryBackoff?: boolean;
117
+ /**
118
+ * Maximum delay between retries in seconds. Caps the exponential backoff
119
+ * so retries never wait longer than this value. Only meaningful when
120
+ * `retryBackoff` is true. No limit when omitted.
121
+ */
122
+ retryDelayMax?: number;
77
123
  }
78
124
  /**
79
125
  * Options for editing a pending job.
@@ -186,6 +232,18 @@ interface JobRecord<PayloadMap, T extends JobType<PayloadMap>> {
186
232
  * Updated by the handler via `ctx.setProgress(percent)`.
187
233
  */
188
234
  progress?: number | null;
235
+ /**
236
+ * Base delay between retries in seconds, or null if using legacy default.
237
+ */
238
+ retryDelay?: number | null;
239
+ /**
240
+ * Whether exponential backoff is enabled for retries, or null if using legacy default.
241
+ */
242
+ retryBackoff?: boolean | null;
243
+ /**
244
+ * Maximum delay cap for retries in seconds, or null if no cap.
245
+ */
246
+ retryDelayMax?: number | null;
189
247
  }
190
248
  /**
191
249
  * Callback registered via `onTimeout`. Invoked when the timeout fires, before the AbortSignal is triggered.
@@ -416,6 +474,88 @@ interface Processor {
416
474
  */
417
475
  start: () => Promise<number>;
418
476
  }
477
+ interface SupervisorOptions {
478
+ /**
479
+ * How often the maintenance loop runs, in milliseconds.
480
+ * @default 60000 (1 minute)
481
+ */
482
+ intervalMs?: number;
483
+ /**
484
+ * Reclaim jobs stuck in `processing` longer than this many minutes.
485
+ * @default 10
486
+ */
487
+ stuckJobsTimeoutMinutes?: number;
488
+ /**
489
+ * Auto-delete completed jobs older than this many days. Set to 0 to disable.
490
+ * @default 30
491
+ */
492
+ cleanupJobsDaysToKeep?: number;
493
+ /**
494
+ * Auto-delete job events older than this many days. Set to 0 to disable.
495
+ * @default 30
496
+ */
497
+ cleanupEventsDaysToKeep?: number;
498
+ /**
499
+ * Batch size for cleanup deletions.
500
+ * @default 1000
501
+ */
502
+ cleanupBatchSize?: number;
503
+ /**
504
+ * Whether to reclaim stuck jobs each cycle.
505
+ * @default true
506
+ */
507
+ reclaimStuckJobs?: boolean;
508
+ /**
509
+ * Whether to expire timed-out waitpoint tokens each cycle.
510
+ * @default true
511
+ */
512
+ expireTimedOutTokens?: boolean;
513
+ /**
514
+ * Called when a maintenance task throws. One failure does not block other tasks.
515
+ * @default console.error
516
+ */
517
+ onError?: (error: Error) => void;
518
+ /** Enable verbose logging. */
519
+ verbose?: boolean;
520
+ }
521
+ interface SupervisorRunResult {
522
+ /** Number of stuck jobs reclaimed back to pending. */
523
+ reclaimedJobs: number;
524
+ /** Number of old completed jobs deleted. */
525
+ cleanedUpJobs: number;
526
+ /** Number of old job events deleted. */
527
+ cleanedUpEvents: number;
528
+ /** Number of timed-out waitpoint tokens expired. */
529
+ expiredTokens: number;
530
+ }
531
+ interface Supervisor {
532
+ /**
533
+ * Run all maintenance tasks once and return the results.
534
+ * Ideal for serverless or cron-triggered invocations.
535
+ */
536
+ start: () => Promise<SupervisorRunResult>;
537
+ /**
538
+ * Start the maintenance loop in the background.
539
+ * Runs every `intervalMs` milliseconds (default: 60 000).
540
+ * Call `stop()` or `stopAndDrain()` to halt the loop.
541
+ */
542
+ startInBackground: () => void;
543
+ /**
544
+ * Stop the background maintenance loop immediately.
545
+ * Does not wait for an in-flight maintenance run to complete.
546
+ */
547
+ stop: () => void;
548
+ /**
549
+ * Stop the background loop and wait for the current maintenance run
550
+ * (if any) to finish before resolving.
551
+ *
552
+ * @param timeoutMs - Maximum time to wait (default: 30 000 ms).
553
+ * If the run does not finish within this time the promise resolves anyway.
554
+ */
555
+ stopAndDrain: (timeoutMs?: number) => Promise<void>;
556
+ /** Whether the background maintenance loop is currently running. */
557
+ isRunning: () => boolean;
558
+ }
419
559
  interface DatabaseSSLConfig {
420
560
  /**
421
561
  * CA certificate as PEM string or file path. If the value starts with 'file://', it will be loaded from file, otherwise treated as PEM string.
@@ -437,10 +577,13 @@ interface DatabaseSSLConfig {
437
577
  /**
438
578
  * Configuration for PostgreSQL backend (default).
439
579
  * Backward-compatible: omitting `backend` defaults to 'postgres'.
580
+ *
581
+ * Provide either `databaseConfig` (the library creates a pool) or `pool`
582
+ * (bring your own `pg.Pool`). At least one must be set.
440
583
  */
441
584
  interface PostgresJobQueueConfig {
442
585
  backend?: 'postgres';
443
- databaseConfig: {
586
+ databaseConfig?: {
444
587
  connectionString?: string;
445
588
  host?: string;
446
589
  port?: number;
@@ -448,7 +591,29 @@ interface PostgresJobQueueConfig {
448
591
  user?: string;
449
592
  password?: string;
450
593
  ssl?: DatabaseSSLConfig;
594
+ /**
595
+ * Maximum number of clients in the pool (default: 10).
596
+ * Increase when running multiple processors in the same process.
597
+ */
598
+ max?: number;
599
+ /**
600
+ * Minimum number of idle clients in the pool (default: 0).
601
+ */
602
+ min?: number;
603
+ /**
604
+ * Milliseconds a client must sit idle before being closed (default: 10000).
605
+ */
606
+ idleTimeoutMillis?: number;
607
+ /**
608
+ * Milliseconds to wait for a connection before throwing (default: 0, no timeout).
609
+ */
610
+ connectionTimeoutMillis?: number;
451
611
  };
612
+ /**
613
+ * Bring your own `pg.Pool` instance. When provided, `databaseConfig` is
614
+ * ignored and the library will not close the pool on shutdown.
615
+ */
616
+ pool?: pg.Pool;
452
617
  verbose?: boolean;
453
618
  }
454
619
  /**
@@ -462,10 +627,13 @@ interface RedisTLSConfig {
462
627
  }
463
628
  /**
464
629
  * Configuration for Redis backend.
630
+ *
631
+ * Provide either `redisConfig` (the library creates an ioredis client) or
632
+ * `client` (bring your own ioredis instance). At least one must be set.
465
633
  */
466
634
  interface RedisJobQueueConfig {
467
635
  backend: 'redis';
468
- redisConfig: {
636
+ redisConfig?: {
469
637
  /** Redis URL (e.g. redis://localhost:6379) */
470
638
  url?: string;
471
639
  host?: string;
@@ -480,6 +648,17 @@ interface RedisJobQueueConfig {
480
648
  */
481
649
  keyPrefix?: string;
482
650
  };
651
+ /**
652
+ * Bring your own ioredis client instance. When provided, `redisConfig` is
653
+ * ignored and the library will not close the client on shutdown.
654
+ * Use `keyPrefix` to set the key namespace (default: 'dq:').
655
+ */
656
+ client?: unknown;
657
+ /**
658
+ * Key prefix when using an external `client`. Ignored when `redisConfig` is used
659
+ * (set `redisConfig.keyPrefix` instead). Default: 'dq:'.
660
+ */
661
+ keyPrefix?: string;
483
662
  verbose?: boolean;
484
663
  }
485
664
  /**
@@ -490,11 +669,118 @@ type JobQueueConfig = PostgresJobQueueConfig | RedisJobQueueConfig;
490
669
  /** @deprecated Use JobQueueConfig instead. Alias kept for backward compat. */
491
670
  type JobQueueConfigLegacy = PostgresJobQueueConfig;
492
671
  type TagQueryMode = 'exact' | 'all' | 'any' | 'none';
672
+ /**
673
+ * Status of a cron schedule.
674
+ */
675
+ type CronScheduleStatus = 'active' | 'paused';
676
+ /**
677
+ * Options for creating a recurring cron schedule.
678
+ * Each schedule defines a recurring job that is automatically enqueued
679
+ * when its cron expression matches.
680
+ */
681
+ interface CronScheduleOptions<PayloadMap, T extends JobType<PayloadMap>> {
682
+ /** Unique human-readable name for the schedule. */
683
+ scheduleName: string;
684
+ /** Standard cron expression (5 fields, e.g. "0 * * * *"). */
685
+ cronExpression: string;
686
+ /** Job type from the PayloadMap. */
687
+ jobType: T;
688
+ /** Payload for each job instance. */
689
+ payload: PayloadMap[T];
690
+ /** Maximum retry attempts for each job instance (default: 3). */
691
+ maxAttempts?: number;
692
+ /** Priority for each job instance (default: 0). */
693
+ priority?: number;
694
+ /** Timeout in milliseconds for each job instance. */
695
+ timeoutMs?: number;
696
+ /** Whether to force-kill the job on timeout (default: false). */
697
+ forceKillOnTimeout?: boolean;
698
+ /** Tags for each job instance. */
699
+ tags?: string[];
700
+ /** IANA timezone string for cron evaluation (default: "UTC"). */
701
+ timezone?: string;
702
+ /**
703
+ * Whether to allow overlapping job instances (default: false).
704
+ * When false, a new job will not be enqueued if the previous instance
705
+ * is still pending, processing, or waiting.
706
+ */
707
+ allowOverlap?: boolean;
708
+ /** Base delay between retries in seconds for each job instance (default: 60). */
709
+ retryDelay?: number;
710
+ /** Whether to use exponential backoff for retries (default: true). */
711
+ retryBackoff?: boolean;
712
+ /** Maximum delay cap for retries in seconds. */
713
+ retryDelayMax?: number;
714
+ }
715
+ /**
716
+ * A persisted cron schedule record.
717
+ */
718
+ interface CronScheduleRecord {
719
+ id: number;
720
+ scheduleName: string;
721
+ cronExpression: string;
722
+ jobType: string;
723
+ payload: any;
724
+ maxAttempts: number;
725
+ priority: number;
726
+ timeoutMs: number | null;
727
+ forceKillOnTimeout: boolean;
728
+ tags: string[] | undefined;
729
+ timezone: string;
730
+ allowOverlap: boolean;
731
+ status: CronScheduleStatus;
732
+ lastEnqueuedAt: Date | null;
733
+ lastJobId: number | null;
734
+ nextRunAt: Date | null;
735
+ createdAt: Date;
736
+ updatedAt: Date;
737
+ retryDelay: number | null;
738
+ retryBackoff: boolean | null;
739
+ retryDelayMax: number | null;
740
+ }
741
+ /**
742
+ * Options for editing an existing cron schedule.
743
+ * All fields are optional; only provided fields are updated.
744
+ */
745
+ interface EditCronScheduleOptions {
746
+ cronExpression?: string;
747
+ payload?: any;
748
+ maxAttempts?: number;
749
+ priority?: number;
750
+ timeoutMs?: number | null;
751
+ forceKillOnTimeout?: boolean;
752
+ tags?: string[] | null;
753
+ timezone?: string;
754
+ allowOverlap?: boolean;
755
+ retryDelay?: number | null;
756
+ retryBackoff?: boolean | null;
757
+ retryDelayMax?: number | null;
758
+ }
493
759
  interface JobQueue<PayloadMap> {
494
760
  /**
495
761
  * Add a job to the job queue.
762
+ *
763
+ * @param job - The job to enqueue.
764
+ * @param options - Optional. Pass `{ db }` with an external database client
765
+ * to insert the job within an existing transaction (PostgreSQL only).
766
+ */
767
+ addJob: <T extends JobType<PayloadMap>>(job: JobOptions<PayloadMap, T>, options?: AddJobOptions) => Promise<number>;
768
+ /**
769
+ * Add multiple jobs to the queue in a single operation.
770
+ *
771
+ * More efficient than calling `addJob` in a loop because it batches the
772
+ * INSERT into a single database round-trip (PostgreSQL) or a single
773
+ * atomic Lua script (Redis).
774
+ *
775
+ * Returns an array of job IDs in the same order as the input array.
776
+ * Each job may independently have an `idempotencyKey`; duplicates
777
+ * resolve to the existing job's ID without creating a new row.
778
+ *
779
+ * @param jobs - Array of jobs to enqueue.
780
+ * @param options - Optional. Pass `{ db }` with an external database client
781
+ * to insert the jobs within an existing transaction (PostgreSQL only).
496
782
  */
497
- addJob: <T extends JobType<PayloadMap>>(job: JobOptions<PayloadMap, T>) => Promise<number>;
783
+ addJobs: <T extends JobType<PayloadMap>>(jobs: JobOptions<PayloadMap, T>[], options?: AddJobOptions) => Promise<number[]>;
498
784
  /**
499
785
  * Get a job by its ID.
500
786
  */
@@ -550,12 +836,18 @@ interface JobQueue<PayloadMap> {
550
836
  retryJob: (jobId: number) => Promise<void>;
551
837
  /**
552
838
  * Cleanup jobs that are older than the specified number of days.
839
+ * Deletes in batches for scale safety.
840
+ * @param daysToKeep - Number of days to retain completed jobs (default 30).
841
+ * @param batchSize - Number of rows to delete per batch (default 1000 for PostgreSQL, 200 for Redis).
553
842
  */
554
- cleanupOldJobs: (daysToKeep?: number) => Promise<number>;
843
+ cleanupOldJobs: (daysToKeep?: number, batchSize?: number) => Promise<number>;
555
844
  /**
556
845
  * Cleanup job events that are older than the specified number of days.
846
+ * Deletes in batches for scale safety.
847
+ * @param daysToKeep - Number of days to retain events (default 30).
848
+ * @param batchSize - Number of rows to delete per batch (default 1000).
557
849
  */
558
- cleanupOldJobEvents: (daysToKeep?: number) => Promise<number>;
850
+ cleanupOldJobEvents: (daysToKeep?: number, batchSize?: number) => Promise<number>;
559
851
  /**
560
852
  * Cancel a job given its ID.
561
853
  * - This will set the job status to 'cancelled' and clear the locked_at and locked_by.
@@ -633,6 +925,12 @@ interface JobQueue<PayloadMap> {
633
925
  * Create a job processor. Handlers must be provided per-processor.
634
926
  */
635
927
  createProcessor: (handlers: JobHandlers<PayloadMap>, options?: ProcessorOptions) => Processor;
928
+ /**
929
+ * Create a background supervisor that automatically reclaims stuck jobs,
930
+ * cleans up old completed jobs/events, and expires timed-out waitpoint
931
+ * tokens on a configurable interval.
932
+ */
933
+ createSupervisor: (options?: SupervisorOptions) => Supervisor;
636
934
  /**
637
935
  * Get the job events for a job.
638
936
  */
@@ -642,8 +940,6 @@ interface JobQueue<PayloadMap> {
642
940
  * Tokens can be completed externally to resume a waiting job.
643
941
  * Can be called outside of handlers (e.g., from an API route).
644
942
  *
645
- * **PostgreSQL backend only.** Throws if the backend is Redis.
646
- *
647
943
  * @param options - Optional token configuration (timeout, tags).
648
944
  * @returns A token object with `id`.
649
945
  */
@@ -652,8 +948,6 @@ interface JobQueue<PayloadMap> {
652
948
  * Complete a waitpoint token, resuming the associated waiting job.
653
949
  * Can be called from anywhere (API routes, external services, etc.).
654
950
  *
655
- * **PostgreSQL backend only.** Throws if the backend is Redis.
656
- *
657
951
  * @param tokenId - The ID of the token to complete.
658
952
  * @param data - Optional data to pass to the waiting handler.
659
953
  */
@@ -661,8 +955,6 @@ interface JobQueue<PayloadMap> {
661
955
  /**
662
956
  * Retrieve a waitpoint token by its ID.
663
957
  *
664
- * **PostgreSQL backend only.** Throws if the backend is Redis.
665
- *
666
958
  * @param tokenId - The ID of the token to retrieve.
667
959
  * @returns The token record, or null if not found.
668
960
  */
@@ -671,11 +963,59 @@ interface JobQueue<PayloadMap> {
671
963
  * Expire timed-out waitpoint tokens and resume their associated jobs.
672
964
  * Call this periodically (e.g., alongside `reclaimStuckJobs`).
673
965
  *
674
- * **PostgreSQL backend only.** Throws if the backend is Redis.
675
- *
676
966
  * @returns The number of tokens that were expired.
677
967
  */
678
968
  expireTimedOutTokens: () => Promise<number>;
969
+ /**
970
+ * Add a recurring cron schedule. The processor automatically enqueues
971
+ * due cron jobs before each batch, so no manual triggering is needed.
972
+ *
973
+ * @returns The ID of the created schedule.
974
+ * @throws If the cron expression is invalid or the schedule name is already taken.
975
+ */
976
+ addCronJob: <T extends JobType<PayloadMap>>(options: CronScheduleOptions<PayloadMap, T>) => Promise<number>;
977
+ /**
978
+ * Get a cron schedule by its ID.
979
+ */
980
+ getCronJob: (id: number) => Promise<CronScheduleRecord | null>;
981
+ /**
982
+ * Get a cron schedule by its unique name.
983
+ */
984
+ getCronJobByName: (name: string) => Promise<CronScheduleRecord | null>;
985
+ /**
986
+ * List all cron schedules, optionally filtered by status.
987
+ */
988
+ listCronJobs: (status?: CronScheduleStatus) => Promise<CronScheduleRecord[]>;
989
+ /**
990
+ * Remove a cron schedule by its ID. Does not cancel any already-enqueued jobs.
991
+ */
992
+ removeCronJob: (id: number) => Promise<void>;
993
+ /**
994
+ * Pause a cron schedule. Paused schedules are skipped by `enqueueDueCronJobs()`.
995
+ */
996
+ pauseCronJob: (id: number) => Promise<void>;
997
+ /**
998
+ * Resume a paused cron schedule.
999
+ */
1000
+ resumeCronJob: (id: number) => Promise<void>;
1001
+ /**
1002
+ * Edit an existing cron schedule. Only provided fields are updated.
1003
+ * If `cronExpression` or `timezone` changes, `nextRunAt` is recalculated.
1004
+ */
1005
+ editCronJob: (id: number, updates: EditCronScheduleOptions) => Promise<void>;
1006
+ /**
1007
+ * Check all active cron schedules and enqueue jobs for any whose
1008
+ * `nextRunAt` has passed. When `allowOverlap` is false (the default),
1009
+ * a new job is not enqueued if the previous instance is still
1010
+ * pending, processing, or waiting.
1011
+ *
1012
+ * **Note:** The processor calls this automatically before each batch,
1013
+ * so you typically do not need to call it yourself. It is exposed for
1014
+ * manual use in tests or one-off scripts.
1015
+ *
1016
+ * @returns The number of jobs that were enqueued.
1017
+ */
1018
+ enqueueDueCronJobs: () => Promise<number>;
679
1019
  /**
680
1020
  * Get the PostgreSQL database pool.
681
1021
  * Throws if the backend is not PostgreSQL.
@@ -722,6 +1062,30 @@ interface JobUpdates {
722
1062
  runAt?: Date | null;
723
1063
  timeoutMs?: number | null;
724
1064
  tags?: string[] | null;
1065
+ retryDelay?: number | null;
1066
+ retryBackoff?: boolean | null;
1067
+ retryDelayMax?: number | null;
1068
+ }
1069
+ /**
1070
+ * Input shape for creating a cron schedule in the backend.
1071
+ * This is the backend-level version of CronScheduleOptions.
1072
+ */
1073
+ interface CronScheduleInput {
1074
+ scheduleName: string;
1075
+ cronExpression: string;
1076
+ jobType: string;
1077
+ payload: any;
1078
+ maxAttempts: number;
1079
+ priority: number;
1080
+ timeoutMs: number | null;
1081
+ forceKillOnTimeout: boolean;
1082
+ tags: string[] | undefined;
1083
+ timezone: string;
1084
+ allowOverlap: boolean;
1085
+ nextRunAt: Date | null;
1086
+ retryDelay: number | null;
1087
+ retryBackoff: boolean | null;
1088
+ retryDelayMax: number | null;
725
1089
  }
726
1090
  /**
727
1091
  * Abstract backend interface that both PostgreSQL and Redis implement.
@@ -729,8 +1093,26 @@ interface JobUpdates {
729
1093
  * and public API are backend-agnostic.
730
1094
  */
731
1095
  interface QueueBackend {
732
- /** Add a job and return its numeric ID. */
733
- addJob<PayloadMap, T extends JobType<PayloadMap>>(job: JobOptions<PayloadMap, T>): Promise<number>;
1096
+ /**
1097
+ * Add a job and return its numeric ID.
1098
+ *
1099
+ * @param job - Job configuration.
1100
+ * @param options - Optional. Pass `{ db }` to run the INSERT on an external
1101
+ * client (e.g., inside a transaction). PostgreSQL only.
1102
+ */
1103
+ addJob<PayloadMap, T extends JobType<PayloadMap>>(job: JobOptions<PayloadMap, T>, options?: AddJobOptions): Promise<number>;
1104
+ /**
1105
+ * Add multiple jobs in a single operation and return their IDs.
1106
+ *
1107
+ * IDs are returned in the same order as the input array.
1108
+ * Each job may independently have an `idempotencyKey`; duplicates
1109
+ * resolve to the existing job's ID without creating a new row.
1110
+ *
1111
+ * @param jobs - Array of job configurations.
1112
+ * @param options - Optional. Pass `{ db }` to run the INSERTs on an external
1113
+ * client (e.g., inside a transaction). PostgreSQL only.
1114
+ */
1115
+ addJobs<PayloadMap, T extends JobType<PayloadMap>>(jobs: JobOptions<PayloadMap, T>[], options?: AddJobOptions): Promise<number[]>;
734
1116
  /** Get a single job by ID, or null if not found. */
735
1117
  getJob<PayloadMap, T extends JobType<PayloadMap>>(id: number): Promise<JobRecord<PayloadMap, T> | null>;
736
1118
  /** Get jobs filtered by status, ordered by createdAt DESC. */
@@ -762,10 +1144,10 @@ interface QueueBackend {
762
1144
  editJob(jobId: number, updates: JobUpdates): Promise<void>;
763
1145
  /** Edit all pending jobs matching filters. Returns count. */
764
1146
  editAllPendingJobs(filters: JobFilters | undefined, updates: JobUpdates): Promise<number>;
765
- /** Delete completed jobs older than N days. Returns count deleted. */
766
- cleanupOldJobs(daysToKeep?: number): Promise<number>;
767
- /** Delete job events older than N days. Returns count deleted. */
768
- cleanupOldJobEvents(daysToKeep?: number): Promise<number>;
1147
+ /** Delete completed jobs older than N days. Deletes in batches for scale safety. Returns count deleted. */
1148
+ cleanupOldJobs(daysToKeep?: number, batchSize?: number): Promise<number>;
1149
+ /** Delete job events older than N days. Deletes in batches for scale safety. Returns count deleted. */
1150
+ cleanupOldJobEvents(daysToKeep?: number, batchSize?: number): Promise<number>;
769
1151
  /** Reclaim jobs stuck in 'processing' for too long. Returns count. */
770
1152
  reclaimStuckJobs(maxProcessingTimeMinutes?: number): Promise<number>;
771
1153
  /** Update the progress percentage (0-100) for a job. */
@@ -774,6 +1156,84 @@ interface QueueBackend {
774
1156
  recordJobEvent(jobId: number, eventType: JobEventType, metadata?: any): Promise<void>;
775
1157
  /** Get all events for a job, ordered by createdAt ASC. */
776
1158
  getJobEvents(jobId: number): Promise<JobEvent[]>;
1159
+ /** Create a cron schedule and return its ID. */
1160
+ addCronSchedule(input: CronScheduleInput): Promise<number>;
1161
+ /** Get a cron schedule by ID, or null if not found. */
1162
+ getCronSchedule(id: number): Promise<CronScheduleRecord | null>;
1163
+ /** Get a cron schedule by its unique name, or null if not found. */
1164
+ getCronScheduleByName(name: string): Promise<CronScheduleRecord | null>;
1165
+ /** List cron schedules, optionally filtered by status. */
1166
+ listCronSchedules(status?: CronScheduleStatus): Promise<CronScheduleRecord[]>;
1167
+ /** Delete a cron schedule by ID. */
1168
+ removeCronSchedule(id: number): Promise<void>;
1169
+ /** Pause a cron schedule. */
1170
+ pauseCronSchedule(id: number): Promise<void>;
1171
+ /** Resume a cron schedule. */
1172
+ resumeCronSchedule(id: number): Promise<void>;
1173
+ /** Edit a cron schedule. */
1174
+ editCronSchedule(id: number, updates: EditCronScheduleOptions, nextRunAt?: Date | null): Promise<void>;
1175
+ /**
1176
+ * Atomically fetch all active cron schedules whose nextRunAt <= now.
1177
+ * In PostgreSQL this uses FOR UPDATE SKIP LOCKED to prevent duplicate enqueuing.
1178
+ */
1179
+ getDueCronSchedules(): Promise<CronScheduleRecord[]>;
1180
+ /**
1181
+ * Update a cron schedule after a job has been enqueued.
1182
+ * Sets lastEnqueuedAt, lastJobId, and advances nextRunAt.
1183
+ */
1184
+ updateCronScheduleAfterEnqueue(id: number, lastEnqueuedAt: Date, lastJobId: number, nextRunAt: Date | null): Promise<void>;
1185
+ /**
1186
+ * Transition a job from 'processing' to 'waiting' status.
1187
+ * Persists step data so the handler can resume from where it left off.
1188
+ *
1189
+ * @param jobId - The job to pause.
1190
+ * @param options - Wait configuration including optional waitUntil date, token ID, and step data.
1191
+ */
1192
+ waitJob(jobId: number, options: {
1193
+ waitUntil?: Date;
1194
+ waitTokenId?: string;
1195
+ stepData: Record<string, any>;
1196
+ }): Promise<void>;
1197
+ /**
1198
+ * Persist step data for a job. Called after each `ctx.run()` step completes
1199
+ * to save intermediate progress. Best-effort: should not throw.
1200
+ *
1201
+ * @param jobId - The job to update.
1202
+ * @param stepData - The step data to persist.
1203
+ */
1204
+ updateStepData(jobId: number, stepData: Record<string, any>): Promise<void>;
1205
+ /**
1206
+ * Create a waitpoint token that can pause a job until an external signal completes it.
1207
+ *
1208
+ * @param jobId - The job ID to associate with the token (null if created outside a handler).
1209
+ * @param options - Optional timeout string (e.g. '10m', '1h') and tags.
1210
+ * @returns The created waitpoint with its unique ID.
1211
+ */
1212
+ createWaitpoint(jobId: number | null, options?: CreateTokenOptions): Promise<{
1213
+ id: string;
1214
+ }>;
1215
+ /**
1216
+ * Complete a waitpoint token, optionally providing output data.
1217
+ * Moves the associated job from 'waiting' back to 'pending' so it gets picked up.
1218
+ *
1219
+ * @param tokenId - The waitpoint token ID to complete.
1220
+ * @param data - Optional data to pass to the waiting handler.
1221
+ */
1222
+ completeWaitpoint(tokenId: string, data?: any): Promise<void>;
1223
+ /**
1224
+ * Retrieve a waitpoint token by its ID.
1225
+ *
1226
+ * @param tokenId - The waitpoint token ID to look up.
1227
+ * @returns The waitpoint record, or null if not found.
1228
+ */
1229
+ getWaitpoint(tokenId: string): Promise<WaitpointRecord | null>;
1230
+ /**
1231
+ * Expire timed-out waitpoint tokens and move their associated jobs back to 'pending'.
1232
+ * Should be called periodically (e.g., alongside reclaimStuckJobs).
1233
+ *
1234
+ * @returns The number of tokens that were expired.
1235
+ */
1236
+ expireTimedOutWaitpoints(): Promise<number>;
777
1237
  /** Set a pending reason for unpicked jobs of a given type. */
778
1238
  setPendingReasonForUnpickedJobs(reason: string, jobType?: string | string[]): Promise<void>;
779
1239
  }
@@ -785,7 +1245,22 @@ declare class PostgresBackend implements QueueBackend {
785
1245
  getPool(): Pool;
786
1246
  recordJobEvent(jobId: number, eventType: JobEventType, metadata?: any): Promise<void>;
787
1247
  getJobEvents(jobId: number): Promise<JobEvent[]>;
788
- addJob<PayloadMap, T extends JobType<PayloadMap>>({ jobType, payload, maxAttempts, priority, runAt, timeoutMs, forceKillOnTimeout, tags, idempotencyKey, }: JobOptions<PayloadMap, T>): Promise<number>;
1248
+ /**
1249
+ * Add a job and return its numeric ID.
1250
+ *
1251
+ * @param job - Job configuration.
1252
+ * @param options - Optional. Pass `{ db }` to run the INSERT on an external
1253
+ * client (e.g., inside a transaction) so the job is part of the caller's
1254
+ * transaction. The event INSERT also uses the same client.
1255
+ */
1256
+ addJob<PayloadMap, T extends JobType<PayloadMap>>({ jobType, payload, maxAttempts, priority, runAt, timeoutMs, forceKillOnTimeout, tags, idempotencyKey, retryDelay, retryBackoff, retryDelayMax, }: JobOptions<PayloadMap, T>, options?: AddJobOptions): Promise<number>;
1257
+ /**
1258
+ * Insert multiple jobs in a single database round-trip.
1259
+ *
1260
+ * Uses a multi-row INSERT with ON CONFLICT handling for idempotency keys.
1261
+ * Returns IDs in the same order as the input array.
1262
+ */
1263
+ addJobs<PayloadMap, T extends JobType<PayloadMap>>(jobs: JobOptions<PayloadMap, T>[], options?: AddJobOptions): Promise<number[]>;
789
1264
  getJob<PayloadMap, T extends JobType<PayloadMap>>(id: number): Promise<JobRecord<PayloadMap, T> | null>;
790
1265
  getJobsByStatus<PayloadMap, T extends JobType<PayloadMap>>(status: string, limit?: number, offset?: number): Promise<JobRecord<PayloadMap, T>[]>;
791
1266
  getAllJobs<PayloadMap, T extends JobType<PayloadMap>>(limit?: number, offset?: number): Promise<JobRecord<PayloadMap, T>[]>;
@@ -801,14 +1276,108 @@ declare class PostgresBackend implements QueueBackend {
801
1276
  cancelAllUpcomingJobs(filters?: JobFilters): Promise<number>;
802
1277
  editJob(jobId: number, updates: JobUpdates): Promise<void>;
803
1278
  editAllPendingJobs(filters: JobFilters | undefined, updates: JobUpdates): Promise<number>;
804
- cleanupOldJobs(daysToKeep?: number): Promise<number>;
805
- cleanupOldJobEvents(daysToKeep?: number): Promise<number>;
1279
+ /**
1280
+ * Delete completed jobs older than the given number of days.
1281
+ * Deletes in batches of 1000 to avoid long-running transactions
1282
+ * and excessive WAL bloat at scale.
1283
+ *
1284
+ * @param daysToKeep - Number of days to retain completed jobs (default 30).
1285
+ * @param batchSize - Number of rows to delete per batch (default 1000).
1286
+ * @returns Total number of deleted jobs.
1287
+ */
1288
+ cleanupOldJobs(daysToKeep?: number, batchSize?: number): Promise<number>;
1289
+ /**
1290
+ * Delete job events older than the given number of days.
1291
+ * Deletes in batches of 1000 to avoid long-running transactions
1292
+ * and excessive WAL bloat at scale.
1293
+ *
1294
+ * @param daysToKeep - Number of days to retain events (default 30).
1295
+ * @param batchSize - Number of rows to delete per batch (default 1000).
1296
+ * @returns Total number of deleted events.
1297
+ */
1298
+ cleanupOldJobEvents(daysToKeep?: number, batchSize?: number): Promise<number>;
806
1299
  reclaimStuckJobs(maxProcessingTimeMinutes?: number): Promise<number>;
807
1300
  /**
808
1301
  * Batch-insert multiple job events in a single query.
809
1302
  * More efficient than individual recordJobEvent calls.
810
1303
  */
811
1304
  private recordJobEventsBatch;
1305
+ /** Create a cron schedule and return its ID. */
1306
+ addCronSchedule(input: CronScheduleInput): Promise<number>;
1307
+ /** Get a cron schedule by ID. */
1308
+ getCronSchedule(id: number): Promise<CronScheduleRecord | null>;
1309
+ /** Get a cron schedule by its unique name. */
1310
+ getCronScheduleByName(name: string): Promise<CronScheduleRecord | null>;
1311
+ /** List cron schedules, optionally filtered by status. */
1312
+ listCronSchedules(status?: CronScheduleStatus): Promise<CronScheduleRecord[]>;
1313
+ /** Delete a cron schedule by ID. */
1314
+ removeCronSchedule(id: number): Promise<void>;
1315
+ /** Pause a cron schedule. */
1316
+ pauseCronSchedule(id: number): Promise<void>;
1317
+ /** Resume a paused cron schedule. */
1318
+ resumeCronSchedule(id: number): Promise<void>;
1319
+ /** Edit a cron schedule. */
1320
+ editCronSchedule(id: number, updates: EditCronScheduleOptions, nextRunAt?: Date | null): Promise<void>;
1321
+ /**
1322
+ * Atomically fetch all active cron schedules whose nextRunAt <= NOW().
1323
+ * Uses FOR UPDATE SKIP LOCKED to prevent duplicate enqueuing across workers.
1324
+ */
1325
+ getDueCronSchedules(): Promise<CronScheduleRecord[]>;
1326
+ /**
1327
+ * Update a cron schedule after a job has been enqueued.
1328
+ * Sets lastEnqueuedAt, lastJobId, and advances nextRunAt.
1329
+ */
1330
+ updateCronScheduleAfterEnqueue(id: number, lastEnqueuedAt: Date, lastJobId: number, nextRunAt: Date | null): Promise<void>;
1331
+ /**
1332
+ * Transition a job from 'processing' to 'waiting' status.
1333
+ * Persists step data so the handler can resume from where it left off.
1334
+ *
1335
+ * @param jobId - The job to pause.
1336
+ * @param options - Wait configuration including optional waitUntil date, token ID, and step data.
1337
+ */
1338
+ waitJob(jobId: number, options: {
1339
+ waitUntil?: Date;
1340
+ waitTokenId?: string;
1341
+ stepData: Record<string, any>;
1342
+ }): Promise<void>;
1343
+ /**
1344
+ * Persist step data for a job. Called after each ctx.run() step completes.
1345
+ * Best-effort: does not throw to avoid killing the running handler.
1346
+ *
1347
+ * @param jobId - The job to update.
1348
+ * @param stepData - The step data to persist.
1349
+ */
1350
+ updateStepData(jobId: number, stepData: Record<string, any>): Promise<void>;
1351
+ /**
1352
+ * Create a waitpoint token in the database.
1353
+ *
1354
+ * @param jobId - The job ID to associate with the token (null if created outside a handler).
1355
+ * @param options - Optional timeout string (e.g. '10m', '1h') and tags.
1356
+ * @returns The created waitpoint with its unique ID.
1357
+ */
1358
+ createWaitpoint(jobId: number | null, options?: CreateTokenOptions): Promise<{
1359
+ id: string;
1360
+ }>;
1361
+ /**
1362
+ * Complete a waitpoint token and move the associated job back to 'pending'.
1363
+ *
1364
+ * @param tokenId - The waitpoint token ID to complete.
1365
+ * @param data - Optional data to pass to the waiting handler.
1366
+ */
1367
+ completeWaitpoint(tokenId: string, data?: any): Promise<void>;
1368
+ /**
1369
+ * Retrieve a waitpoint token by its ID.
1370
+ *
1371
+ * @param tokenId - The waitpoint token ID to look up.
1372
+ * @returns The waitpoint record, or null if not found.
1373
+ */
1374
+ getWaitpoint(tokenId: string): Promise<WaitpointRecord | null>;
1375
+ /**
1376
+ * Expire timed-out waitpoint tokens and move their associated jobs back to 'pending'.
1377
+ *
1378
+ * @returns The number of tokens that were expired.
1379
+ */
1380
+ expireTimedOutWaitpoints(): Promise<number>;
812
1381
  setPendingReasonForUnpickedJobs(reason: string, jobType?: string | string[]): Promise<void>;
813
1382
  }
814
1383
 
@@ -863,11 +1432,32 @@ declare function testHandlerSerialization<PayloadMap, T extends keyof PayloadMap
863
1432
  error?: string;
864
1433
  }>;
865
1434
 
1435
+ /**
1436
+ * Calculate the next occurrence of a cron expression after a given date.
1437
+ *
1438
+ * @param cronExpression - A standard cron expression (5 fields, e.g. "0 * * * *").
1439
+ * @param timezone - IANA timezone string (default: "UTC").
1440
+ * @param after - The reference date to compute the next run from (default: now).
1441
+ * @param CronImpl - Cron class for dependency injection (default: croner's Cron).
1442
+ * @returns The next occurrence as a Date, or null if the expression will never fire again.
1443
+ */
1444
+ declare function getNextCronOccurrence(cronExpression: string, timezone?: string, after?: Date, CronImpl?: typeof Cron): Date | null;
1445
+ /**
1446
+ * Validate whether a string is a syntactically correct cron expression.
1447
+ *
1448
+ * @param cronExpression - The cron expression to validate.
1449
+ * @param CronImpl - Cron class for dependency injection (default: croner's Cron).
1450
+ * @returns True if the expression is valid, false otherwise.
1451
+ */
1452
+ declare function validateCronExpression(cronExpression: string, CronImpl?: typeof Cron): boolean;
1453
+
866
1454
  /**
867
1455
  * Initialize the job queue system.
868
1456
  *
869
1457
  * Defaults to PostgreSQL when `backend` is omitted.
1458
+ * For PostgreSQL, provide either `databaseConfig` or `pool` (bring your own).
1459
+ * For Redis, provide either `redisConfig` or `client` (bring your own).
870
1460
  */
871
1461
  declare const initJobQueue: <PayloadMap = any>(config: JobQueueConfig) => JobQueue<PayloadMap>;
872
1462
 
873
- export { type CreateTokenOptions, type DatabaseSSLConfig, type EditJobOptions, FailureReason, type JobContext, type JobEvent, JobEventType, type JobHandler, type JobHandlers, type JobOptions, type JobQueue, type JobQueueConfig, type JobQueueConfigLegacy, type JobRecord, type JobStatus, type JobType, type OnTimeoutCallback, PostgresBackend, type PostgresJobQueueConfig, type Processor, type ProcessorOptions, type QueueBackend, type RedisJobQueueConfig, type RedisTLSConfig, type TagQueryMode, type WaitDuration, WaitSignal, type WaitToken, type WaitTokenResult, type WaitpointRecord, type WaitpointStatus, initJobQueue, testHandlerSerialization, validateHandlerSerializable };
1463
+ export { type AddJobOptions, type CreateTokenOptions, type CronScheduleInput, type CronScheduleOptions, type CronScheduleRecord, type CronScheduleStatus, type DatabaseClient, type DatabaseSSLConfig, type EditCronScheduleOptions, type EditJobOptions, FailureReason, type JobContext, type JobEvent, JobEventType, type JobHandler, type JobHandlers, type JobOptions, type JobQueue, type JobQueueConfig, type JobQueueConfigLegacy, type JobRecord, type JobStatus, type JobType, type OnTimeoutCallback, PostgresBackend, type PostgresJobQueueConfig, type Processor, type ProcessorOptions, type QueueBackend, type RedisJobQueueConfig, type RedisTLSConfig, type Supervisor, type SupervisorOptions, type SupervisorRunResult, type TagQueryMode, type WaitDuration, WaitSignal, type WaitToken, type WaitTokenResult, type WaitpointRecord, type WaitpointStatus, getNextCronOccurrence, initJobQueue, testHandlerSerialization, validateCronExpression, validateHandlerSerializable };