@checkstack/queue-memory-backend 0.3.18 → 0.4.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,142 @@
1
1
  # @checkstack/queue-memory-backend
2
2
 
3
+ ## 0.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [9016526]
8
+ - @checkstack/common@0.10.0
9
+ - @checkstack/backend-api@0.15.2
10
+ - @checkstack/queue-memory-common@0.1.13
11
+ - @checkstack/queue-api@0.3.1
12
+
13
+ ## 0.4.0
14
+
15
+ ### Minor Changes
16
+
17
+ - aa89bc5: Replace the bespoke `registerInfrastructureTab()` registry with a standard
18
+ slot-extension contract (`InfrastructureTabsSlot` from
19
+ `@checkstack/infrastructure-common`). Plugins now contribute infrastructure
20
+ tabs via `createSlotExtension`, depending only on the slot owner.
21
+
22
+ The slot system in `@checkstack/frontend-api` gains a second type parameter
23
+ on `createSlot<TContext, TMetadata>` so extensions can declare typed static
24
+ metadata at registration time (label, icon, access rules, ordering for the
25
+ infrastructure tab bar). A new `useSlotExtensions(slot)` hook returns typed
26
+ extensions and subscribes to plugin lifecycle changes.
27
+
28
+ Each tab body now stacks a **Runtime** sub-section (live state, read-only)
29
+ on top of a **Configuration** sub-section (settings, gated by `canUpdate`).
30
+
31
+ **Queue runtime panel.** Surfaces aggregated counts (pending / processing /
32
+ completed / failed) plus three sub-tabs of recent jobs: **Active**, **Recent
33
+ failed** (with the failure message), and **Recent completed** (with
34
+ duration). Job payloads are deliberately not surfaced — they may carry
35
+ secrets and need a separate manage-access gate to be shown.
36
+
37
+ To support this, `Queue<T>` gains a required `listJobs(opts)` method
38
+ returning `JobSummary[]` (no payloads), and `QueueStats` gains a
39
+ `scope: "instance" | "cluster"` field. The in-memory queue keeps rolling
40
+ ring buffers (200 entries) for completed/failed history and tracks active
41
+ jobs by id; BullMQ uses native `getJobs`. `QueueManager.listJobs` aggregates
42
+ across queues and sorts (most-recent-first for terminal states, FIFO for
43
+ active/waiting/delayed).
44
+
45
+ **Cache runtime panel.** Lists the top N entries by size (or by recency) so
46
+ operators can debug a cache filling up. Values are deliberately omitted —
47
+ PII / secret risk. Backends opt in via an optional `listEntries?` method on
48
+ `CacheProvider`; non-supporting backends return `{ supported: false }` and
49
+ the UI renders a "not supported by this backend" hint. The in-memory cache
50
+ implements it using its existing per-entry byte tracking.
51
+
52
+ `CacheStats` also gains `scope: "instance" | "cluster"`.
53
+
54
+ **Multi-instance scope warning.** A new `<InstanceScopeBanner>` component in
55
+ `@checkstack/ui` renders a yellow banner above any runtime panel whose
56
+ backend reports `scope: "instance"` — i.e. in-memory queue or cache running
57
+ in a horizontally scaled deployment. The banner explains the metrics are
58
+ local to the responding replica and recommends switching to a clustered
59
+ backend (Redis-backed queue / cache) for cluster-wide visibility.
60
+
61
+ **Bug fix — stable cache provider proxy.** `CacheManagerImpl.getProvider()`
62
+ now returns a single stable proxy that delegates to whatever provider is
63
+ currently active. Previously, consumers of `createCachedScope` (and any
64
+ direct `cacheManager.getProvider()` caller) captured the active provider
65
+ reference at plugin-init time. After any `setActiveBackend` call — including
66
+ saving the same memory config in the new Cache tab, which reconstructs the
67
+ in-memory cache — those scopes wrote to an orphaned old provider while the
68
+ runtime panel read stats from the new (empty) one, making the runtime panel
69
+ appear to report 0 keys. With the proxy, all consumers share a single stable
70
+ identity and writes always land in the active provider.
71
+
72
+ **Bytes tracking on the in-memory cache.** `InMemoryCache.getStats().sizeBytes`
73
+ now returns a running approximation (UTF-8 bytes of the key plus
74
+ `v8.serialize(value).byteLength`, with a JSON fallback) that's kept in sync
75
+ across all eviction paths. Treat the number as a sanity gauge; it doesn't
76
+ include `Map` per-entry overhead.
77
+
78
+ **Pagination.** Both `Queue<T>.listJobs` and `CacheProvider.listEntries?`
79
+ are offset-paginated. Inputs gain an `offset: number`; outputs change to
80
+ `{ items, total: number | null, hasMore: boolean }`. `total` is nullable
81
+ so backends that can't compute it cheaply still paginate via `hasMore`.
82
+ The UI uses the existing `<Pagination>` component with a 25-row default
83
+ page size. `QueueManager.listJobs` aggregates by over-fetching
84
+ `[0, offset+limit)` per queue, merge-sorting, then slicing the window —
85
+ optimal for the single-queue case, acceptable for the multi-queue case
86
+ within the UI's reasonable page-depth bounds. BullMQ uses native offset
87
+ ranges via `getJobs(types, start, end)` plus `getJobCounts` for `total`.
88
+
89
+ **Pending tab.** The Queue runtime panel exposes a virtual `"pending"`
90
+ state (waiting ∪ delayed, FIFO). It's now the default sub-tab, since
91
+ "what's queued up?" is the most common question. Per-row state is shown
92
+ when viewing the combined list.
93
+
94
+ **Recurring schedules visible under Pending.** Cron- and interval-based
95
+ recurring jobs (e.g. healthchecks) are surfaced under Pending/Delayed
96
+ between fires, with a `nextRunAt` countdown column and a "(recurring)"
97
+ label. `JobSummary` gains optional `nextRunAt: Date` and `recurring:
98
+ boolean` fields. The in-memory queue synthesises these rows from its
99
+ `recurringJobs` registry; BullMQ already materialises the next fire of
100
+ each scheduler as a delayed job and we now surface its trigger time and
101
+ the `repeatJobKey`-derived `recurring` flag.
102
+
103
+ **Bug fix — drop hook emits with no listeners.** `EventBus.emit` no
104
+ longer enqueues a job when zero listeners (distributed or instance-local)
105
+ are registered for the hook. Previously, hooks like
106
+ `core.plugin.initialized` — emitted on every plugin init but subscribed
107
+ to by nothing in the core repo — accumulated one waiting job per emit
108
+ forever. The in-memory queue's `processNext` short-circuits when there
109
+ are zero consumer groups, so its post-loop cleanup never ran for these
110
+ orphaned jobs. The fix drops the emit at the source and logs a debug
111
+ line. Note: in distributed deployments using a Redis-backed queue, this
112
+ means a subscriber on another replica won't receive an event if no
113
+ replica that emits it has a local listener. Plugins needing cross-process
114
+ delivery must register their listener on every replica that should
115
+ receive the hook.
116
+
117
+ **Breaking notes (treated as minor under beta semantics)**:
118
+
119
+ - `@checkstack/infrastructure-common` removes `registerInfrastructureTab`
120
+ and `getInfrastructureTabs`; former callers must register an extension
121
+ into `InfrastructureTabsSlot`.
122
+ - `@checkstack/queue-api`'s `Queue<T>` interface requires the new
123
+ `listJobs(opts)` method returning `ListJobsResult` (paginated). Both
124
+ bundled queue backends (memory, BullMQ) are updated; out-of-tree
125
+ implementations will need to add it.
126
+ - `QueueStats` and `CacheStats` add a required `scope` field.
127
+ - `CacheProvider.listEntries?` (when implemented) now returns
128
+ `ListEntriesResult` instead of `CacheEntrySummary[]`.
129
+ - `JobState` adds a `"pending"` variant.
130
+
131
+ ### Patch Changes
132
+
133
+ - Updated dependencies [42abfff]
134
+ - Updated dependencies [aa89bc5]
135
+ - @checkstack/common@0.9.0
136
+ - @checkstack/queue-api@0.3.0
137
+ - @checkstack/backend-api@0.15.1
138
+ - @checkstack/queue-memory-common@0.1.12
139
+
3
140
  ## 0.3.18
4
141
 
5
142
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checkstack/queue-memory-backend",
3
- "version": "0.3.18",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "checkstack": {
@@ -17,17 +17,17 @@
17
17
  "pack": "bunx @checkstack/scripts plugin-pack"
18
18
  },
19
19
  "dependencies": {
20
- "@checkstack/backend-api": "0.15.0",
21
- "@checkstack/queue-api": "0.2.18",
22
- "@checkstack/queue-memory-common": "0.1.11",
23
- "@checkstack/common": "0.8.0",
20
+ "@checkstack/backend-api": "0.15.1",
21
+ "@checkstack/queue-api": "0.3.0",
22
+ "@checkstack/queue-memory-common": "0.1.12",
23
+ "@checkstack/common": "0.9.0",
24
24
  "cron-parser": "^4.9.0",
25
25
  "zod": "^4.2.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/bun": "latest",
29
29
  "@checkstack/tsconfig": "0.0.7",
30
- "@checkstack/scripts": "0.2.0"
30
+ "@checkstack/scripts": "0.3.1"
31
31
  },
32
32
  "description": "Checkstack queue-memory-backend plugin",
33
33
  "author": {
@@ -505,4 +505,192 @@ describe("InMemoryQueue Consumer Groups", () => {
505
505
  });
506
506
 
507
507
  // NOTE: Recurring job tests are in recurring-jobs.test.ts
508
+
509
+ describe("listJobs + getStats scope", () => {
510
+ it("getStats reports scope=instance", async () => {
511
+ const stats = await queue.getStats();
512
+ expect(stats.scope).toBe("instance");
513
+ });
514
+
515
+ it("lists waiting jobs in FIFO order", async () => {
516
+ await queue.enqueue("a", { jobId: "j-a" });
517
+ await queue.enqueue("b", { jobId: "j-b" });
518
+ await queue.enqueue("c", { jobId: "j-c" });
519
+
520
+ const waiting = await queue.listJobs({
521
+ state: "waiting",
522
+ offset: 0,
523
+ limit: 10,
524
+ });
525
+ expect(waiting.items.map((j) => j.id)).toEqual(["j-a", "j-b", "j-c"]);
526
+ expect(waiting.items.every((j) => j.state === "waiting")).toBe(true);
527
+ expect(waiting.total).toBe(3);
528
+ expect(waiting.hasMore).toBe(false);
529
+ });
530
+
531
+ it("classifies delayed jobs separately from waiting", async () => {
532
+ // delayMultiplier=0.01 means startDelay=10s becomes 100ms; list before it elapses.
533
+ await queue.enqueue("now");
534
+ await queue.enqueue("later", { startDelay: 10 });
535
+
536
+ const waiting = await queue.listJobs({
537
+ state: "waiting",
538
+ offset: 0,
539
+ limit: 10,
540
+ });
541
+ const delayed = await queue.listJobs({
542
+ state: "delayed",
543
+ offset: 0,
544
+ limit: 10,
545
+ });
546
+ expect(waiting.items).toHaveLength(1);
547
+ expect(delayed.items).toHaveLength(1);
548
+ });
549
+
550
+ it("surfaces recurring (cron) schedules under pending with nextRunAt", async () => {
551
+ // Use cron pattern: every minute
552
+ await queue.scheduleRecurring("payload", {
553
+ jobId: "cron-job",
554
+ cronPattern: "*/1 * * * *",
555
+ });
556
+
557
+ const pending = await queue.listJobs({
558
+ state: "pending",
559
+ offset: 0,
560
+ limit: 10,
561
+ });
562
+ const cronRow = pending.items.find((j) => j.id === "cron-job");
563
+ expect(cronRow).toBeDefined();
564
+ expect(cronRow!.recurring).toBe(true);
565
+ expect(cronRow!.state).toBe("delayed");
566
+ expect(cronRow!.nextRunAt).toBeInstanceOf(Date);
567
+ expect(cronRow!.nextRunAt!.getTime()).toBeGreaterThan(Date.now());
568
+ });
569
+
570
+ it("surfaces recurring (interval) schedules under delayed with nextRunAt", async () => {
571
+ await queue.scheduleRecurring("payload", {
572
+ jobId: "interval-job",
573
+ intervalSeconds: 60,
574
+ });
575
+
576
+ const delayed = await queue.listJobs({
577
+ state: "delayed",
578
+ offset: 0,
579
+ limit: 10,
580
+ });
581
+ const row = delayed.items.find((j) => j.id === "interval-job");
582
+ expect(row).toBeDefined();
583
+ expect(row!.recurring).toBe(true);
584
+ expect(row!.nextRunAt).toBeInstanceOf(Date);
585
+ });
586
+
587
+ it("'pending' is the union of waiting and delayed, FIFO", async () => {
588
+ await queue.enqueue("now1", { jobId: "p-now-1" });
589
+ await queue.enqueue("later", { jobId: "p-later", startDelay: 10 });
590
+ await queue.enqueue("now2", { jobId: "p-now-2" });
591
+
592
+ const pending = await queue.listJobs({
593
+ state: "pending",
594
+ offset: 0,
595
+ limit: 10,
596
+ });
597
+ expect(pending.items.map((j) => j.id)).toEqual([
598
+ "p-now-1",
599
+ "p-later",
600
+ "p-now-2",
601
+ ]);
602
+ expect(pending.total).toBe(3);
603
+ // Per-job state classification preserved.
604
+ const states = Object.fromEntries(
605
+ pending.items.map((j) => [j.id, j.state]),
606
+ );
607
+ expect(states["p-now-1"]).toBe("waiting");
608
+ expect(states["p-later"]).toBe("delayed");
609
+ expect(states["p-now-2"]).toBe("waiting");
610
+ });
611
+
612
+ it("records completed jobs in history (most-recent first)", async () => {
613
+ await queue.consume(async () => {}, {
614
+ consumerGroup: "g1",
615
+ maxRetries: 0,
616
+ });
617
+
618
+ await queue.enqueue("x", { jobId: "ok-1" });
619
+ await queue.enqueue("y", { jobId: "ok-2" });
620
+ await new Promise((resolve) => setTimeout(resolve, 60));
621
+
622
+ const completed = await queue.listJobs({
623
+ state: "completed",
624
+ offset: 0,
625
+ limit: 10,
626
+ });
627
+ expect(completed.items.length).toBe(2);
628
+ expect(completed.total).toBe(2);
629
+ // Newest first
630
+ expect(
631
+ completed.items[0].finishedAt!.getTime(),
632
+ ).toBeGreaterThanOrEqual(completed.items[1].finishedAt!.getTime());
633
+ expect(completed.items[0].state).toBe("completed");
634
+ });
635
+
636
+ it("records failed jobs with the error message", async () => {
637
+ await queue.consume(
638
+ async () => {
639
+ throw new Error("boom");
640
+ },
641
+ { consumerGroup: "g1", maxRetries: 0 },
642
+ );
643
+
644
+ await queue.enqueue("z", { jobId: "bad-1" });
645
+ await new Promise((resolve) => setTimeout(resolve, 60));
646
+
647
+ const failed = await queue.listJobs({
648
+ state: "failed",
649
+ offset: 0,
650
+ limit: 10,
651
+ });
652
+ expect(failed.items.length).toBe(1);
653
+ expect(failed.items[0].state).toBe("failed");
654
+ expect(failed.items[0].failedReason).toBe("boom");
655
+ });
656
+
657
+ it("paginates with offset/limit", async () => {
658
+ await queue.consume(async () => {}, {
659
+ consumerGroup: "g1",
660
+ maxRetries: 0,
661
+ });
662
+ for (let i = 0; i < 10; i++) {
663
+ await queue.enqueue("v", { jobId: `id-${i}` });
664
+ }
665
+ await new Promise((resolve) => setTimeout(resolve, 80));
666
+
667
+ const page1 = await queue.listJobs({
668
+ state: "completed",
669
+ offset: 0,
670
+ limit: 3,
671
+ });
672
+ expect(page1.items).toHaveLength(3);
673
+ expect(page1.total).toBe(10);
674
+ expect(page1.hasMore).toBe(true);
675
+
676
+ const page2 = await queue.listJobs({
677
+ state: "completed",
678
+ offset: 3,
679
+ limit: 3,
680
+ });
681
+ expect(page2.items).toHaveLength(3);
682
+ // Different page should yield different ids
683
+ expect(page2.items.map((j) => j.id)).not.toEqual(
684
+ page1.items.map((j) => j.id),
685
+ );
686
+
687
+ const lastPage = await queue.listJobs({
688
+ state: "completed",
689
+ offset: 9,
690
+ limit: 3,
691
+ });
692
+ expect(lastPage.items).toHaveLength(1);
693
+ expect(lastPage.hasMore).toBe(false);
694
+ });
695
+ });
508
696
  });
@@ -6,8 +6,13 @@ import {
6
6
  ConsumeOptions,
7
7
  RecurringJobDetails,
8
8
  RecurringSchedule,
9
+ JobSummary,
10
+ ListJobsOptions,
11
+ ListJobsResult,
12
+ JobState,
9
13
  } from "@checkstack/queue-api";
10
14
  import type { Logger } from "@checkstack/backend-api";
15
+ import { extractErrorMessage } from "@checkstack/common";
11
16
  import { InMemoryQueueConfig } from "./plugin";
12
17
  import parser from "cron-parser";
13
18
 
@@ -79,6 +84,26 @@ type RecurringJobMetadata<T> = {
79
84
  timerId?: ReturnType<typeof setTimeout> | ReturnType<typeof setInterval>;
80
85
  } & RecurringSchedule;
81
86
 
87
+ /** Maximum history entries kept per terminal state (completed/failed). */
88
+ const HISTORY_CAP = 200;
89
+
90
+ interface ActiveJobInfo {
91
+ id: string;
92
+ enqueuedAt: Date;
93
+ startedAt: Date;
94
+ attempts: number;
95
+ }
96
+
97
+ interface TerminalJobInfo {
98
+ id: string;
99
+ state: "completed" | "failed";
100
+ enqueuedAt: Date;
101
+ startedAt: Date;
102
+ finishedAt: Date;
103
+ attempts: number;
104
+ failedReason?: string;
105
+ }
106
+
82
107
  /**
83
108
  * In-memory queue implementation with consumer group support
84
109
  */
@@ -94,6 +119,13 @@ export class InMemoryQueue<T> implements Queue<T> {
94
119
  failed: 0,
95
120
  };
96
121
 
122
+ /** Currently-processing jobs, keyed by job id. */
123
+ private activeJobs = new Map<string, ActiveJobInfo>();
124
+ /** Most-recent-first ring buffer of completed jobs (capped at {@link HISTORY_CAP}). */
125
+ private completedHistory: TerminalJobInfo[] = [];
126
+ /** Most-recent-first ring buffer of failed jobs (capped at {@link HISTORY_CAP}). */
127
+ private failedHistory: TerminalJobInfo[] = [];
128
+
97
129
  private logger: Logger;
98
130
  private heartbeatInterval: ReturnType<typeof setInterval> | undefined;
99
131
 
@@ -440,6 +472,13 @@ export class InMemoryQueue<T> implements Queue<T> {
440
472
  });
441
473
  }
442
474
 
475
+ private pushHistory(buf: TerminalJobInfo[], info: TerminalJobInfo): void {
476
+ buf.unshift(info);
477
+ if (buf.length > HISTORY_CAP) {
478
+ buf.length = HISTORY_CAP;
479
+ }
480
+ }
481
+
443
482
  private async processJob(
444
483
  job: InternalQueueJob<T>,
445
484
  consumer: ConsumerGroupState<T>["consumers"][0],
@@ -448,12 +487,27 @@ export class InMemoryQueue<T> implements Queue<T> {
448
487
  ): Promise<void> {
449
488
  await this.semaphore.acquire();
450
489
  this.processing++;
490
+ const startedAt = new Date();
491
+ this.activeJobs.set(job.id, {
492
+ id: job.id,
493
+ enqueuedAt: job.timestamp,
494
+ startedAt,
495
+ attempts: (job.attempts ?? 0) + 1,
496
+ });
451
497
 
452
498
  let isRetrying = false;
453
499
 
454
500
  try {
455
501
  await consumer.handler(job);
456
502
  this.stats.completed++;
503
+ this.pushHistory(this.completedHistory, {
504
+ id: job.id,
505
+ state: "completed",
506
+ enqueuedAt: job.timestamp,
507
+ startedAt,
508
+ finishedAt: new Date(),
509
+ attempts: (job.attempts ?? 0) + 1,
510
+ });
457
511
  } catch (error) {
458
512
  this.logger.error(
459
513
  `Job ${job.id} failed in group ${groupId} (attempt ${job.attempts}):`,
@@ -488,8 +542,18 @@ export class InMemoryQueue<T> implements Queue<T> {
488
542
  });
489
543
  } else {
490
544
  this.stats.failed++;
545
+ this.pushHistory(this.failedHistory, {
546
+ id: job.id,
547
+ state: "failed",
548
+ enqueuedAt: job.timestamp,
549
+ startedAt,
550
+ finishedAt: new Date(),
551
+ attempts: (job.attempts ?? 0) + 1,
552
+ failedReason: extractErrorMessage(error),
553
+ });
491
554
  }
492
555
  } finally {
556
+ this.activeJobs.delete(job.id);
493
557
  this.processing--;
494
558
  this.semaphore.release();
495
559
 
@@ -535,6 +599,149 @@ export class InMemoryQueue<T> implements Queue<T> {
535
599
  completed: this.stats.completed,
536
600
  failed: this.stats.failed,
537
601
  consumerGroups: this.consumerGroups.size,
602
+ scope: "instance",
603
+ };
604
+ }
605
+
606
+ /**
607
+ * Synthesise `JobSummary` rows for recurring schedules so the UI can
608
+ * surface them under Pending (and Delayed) between actual fires.
609
+ *
610
+ * The in-memory queue runs cron via `setTimeout` and intervals via
611
+ * `setInterval`; neither materialises the next execution as an entry
612
+ * in `this.jobs` until the timer fires. Without these synthetic rows,
613
+ * cron-scheduled work like healthchecks would be invisible to operators
614
+ * looking at the runtime panel.
615
+ */
616
+ private synthesizeRecurringSummaries(): JobSummary[] {
617
+ const out: JobSummary[] = [];
618
+ for (const meta of this.recurringJobs.values()) {
619
+ if (!meta.enabled) continue;
620
+ let nextRunAt: Date | undefined;
621
+ if ("cronPattern" in meta && meta.cronPattern) {
622
+ try {
623
+ nextRunAt = parser
624
+ .parseExpression(meta.cronPattern)
625
+ .next()
626
+ .toDate();
627
+ } catch {
628
+ nextRunAt = undefined;
629
+ }
630
+ } else if (meta.intervalSeconds) {
631
+ // Best-effort: assume "now + intervalMs". The exact next-tick of
632
+ // an active setInterval isn't observable from outside; this gives
633
+ // operators an upper bound on the wait.
634
+ const intervalMs =
635
+ meta.intervalSeconds * 1000 * (this.config.delayMultiplier ?? 1);
636
+ nextRunAt = new Date(Date.now() + intervalMs);
637
+ }
638
+ // For synthesised recurring rows, `enqueuedAt` represents "this
639
+ // schedule is currently active as of now" — not a future fire time.
640
+ // The future fire time goes in `nextRunAt`. Using a future date
641
+ // here would make the UI's "x ago" relative formatting report
642
+ // negative seconds.
643
+ out.push({
644
+ id: meta.jobId,
645
+ name: this.name,
646
+ state: "delayed",
647
+ enqueuedAt: new Date(),
648
+ attempts: 0,
649
+ nextRunAt,
650
+ recurring: true,
651
+ });
652
+ }
653
+ return out;
654
+ }
655
+
656
+ async listJobs(opts: ListJobsOptions): Promise<ListJobsResult> {
657
+ const limit = Math.max(0, opts.limit);
658
+ const offset = Math.max(0, opts.offset);
659
+ const state: JobState = opts.state;
660
+ const now = Date.now();
661
+
662
+ const slice = <X>(all: X[]): { items: X[]; total: number } => ({
663
+ items: all.slice(offset, offset + limit),
664
+ total: all.length,
665
+ });
666
+
667
+ let result: { items: JobSummary[]; total: number };
668
+
669
+ if (state === "completed" || state === "failed") {
670
+ const src =
671
+ state === "completed" ? this.completedHistory : this.failedHistory;
672
+ const { items, total } = slice(src);
673
+ result = {
674
+ total,
675
+ items: items.map((j) => ({
676
+ id: j.id,
677
+ name: this.name,
678
+ state,
679
+ enqueuedAt: j.enqueuedAt,
680
+ startedAt: j.startedAt,
681
+ finishedAt: j.finishedAt,
682
+ attempts: j.attempts,
683
+ failedReason: j.failedReason,
684
+ })),
685
+ };
686
+ } else if (state === "active") {
687
+ const sorted = [...this.activeJobs.values()].toSorted(
688
+ (a, b) => a.startedAt.getTime() - b.startedAt.getTime(),
689
+ );
690
+ const { items, total } = slice(sorted);
691
+ result = {
692
+ total,
693
+ items: items.map((j) => ({
694
+ id: j.id,
695
+ name: this.name,
696
+ state: "active",
697
+ enqueuedAt: j.enqueuedAt,
698
+ startedAt: j.startedAt,
699
+ attempts: j.attempts,
700
+ })),
701
+ };
702
+ } else {
703
+ // pending / waiting / delayed: derived from this.jobs PLUS synthetic
704
+ // entries for active recurring schedules (so cron jobs are visible
705
+ // between fires).
706
+ // - waiting: availableAt <= now
707
+ // - delayed: availableAt > now (real jobs) + recurring schedules
708
+ // - pending: union, sorted by enqueuedAt (FIFO)
709
+ const isDelayed = (job: InternalQueueJob<T>) =>
710
+ job.availableAt.getTime() > now;
711
+
712
+ const baseSummaries: JobSummary[] = this.jobs
713
+ .filter((j) =>
714
+ state === "pending"
715
+ ? true
716
+ : state === "delayed"
717
+ ? isDelayed(j)
718
+ : !isDelayed(j),
719
+ )
720
+ .map((j) => ({
721
+ id: j.id,
722
+ name: this.name,
723
+ state:
724
+ state === "pending"
725
+ ? isDelayed(j)
726
+ ? ("delayed" as const)
727
+ : ("waiting" as const)
728
+ : state,
729
+ enqueuedAt: j.timestamp,
730
+ attempts: j.attempts ?? 0,
731
+ }));
732
+
733
+ const recurringSummaries =
734
+ state === "waiting" ? [] : this.synthesizeRecurringSummaries();
735
+
736
+ const all = [...baseSummaries, ...recurringSummaries];
737
+ const { items, total } = slice(all);
738
+ result = { items, total };
739
+ }
740
+
741
+ return {
742
+ items: result.items,
743
+ total: result.total,
744
+ hasMore: offset + result.items.length < result.total,
538
745
  };
539
746
  }
540
747