@checkstack/queue-memory-backend 0.3.18 → 0.4.0
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 +127 -0
- package/package.json +2 -2
- package/src/memory-queue.test.ts +188 -0
- package/src/memory-queue.ts +207 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,132 @@
|
|
|
1
1
|
# @checkstack/queue-memory-backend
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- aa89bc5: Replace the bespoke `registerInfrastructureTab()` registry with a standard
|
|
8
|
+
slot-extension contract (`InfrastructureTabsSlot` from
|
|
9
|
+
`@checkstack/infrastructure-common`). Plugins now contribute infrastructure
|
|
10
|
+
tabs via `createSlotExtension`, depending only on the slot owner.
|
|
11
|
+
|
|
12
|
+
The slot system in `@checkstack/frontend-api` gains a second type parameter
|
|
13
|
+
on `createSlot<TContext, TMetadata>` so extensions can declare typed static
|
|
14
|
+
metadata at registration time (label, icon, access rules, ordering for the
|
|
15
|
+
infrastructure tab bar). A new `useSlotExtensions(slot)` hook returns typed
|
|
16
|
+
extensions and subscribes to plugin lifecycle changes.
|
|
17
|
+
|
|
18
|
+
Each tab body now stacks a **Runtime** sub-section (live state, read-only)
|
|
19
|
+
on top of a **Configuration** sub-section (settings, gated by `canUpdate`).
|
|
20
|
+
|
|
21
|
+
**Queue runtime panel.** Surfaces aggregated counts (pending / processing /
|
|
22
|
+
completed / failed) plus three sub-tabs of recent jobs: **Active**, **Recent
|
|
23
|
+
failed** (with the failure message), and **Recent completed** (with
|
|
24
|
+
duration). Job payloads are deliberately not surfaced — they may carry
|
|
25
|
+
secrets and need a separate manage-access gate to be shown.
|
|
26
|
+
|
|
27
|
+
To support this, `Queue<T>` gains a required `listJobs(opts)` method
|
|
28
|
+
returning `JobSummary[]` (no payloads), and `QueueStats` gains a
|
|
29
|
+
`scope: "instance" | "cluster"` field. The in-memory queue keeps rolling
|
|
30
|
+
ring buffers (200 entries) for completed/failed history and tracks active
|
|
31
|
+
jobs by id; BullMQ uses native `getJobs`. `QueueManager.listJobs` aggregates
|
|
32
|
+
across queues and sorts (most-recent-first for terminal states, FIFO for
|
|
33
|
+
active/waiting/delayed).
|
|
34
|
+
|
|
35
|
+
**Cache runtime panel.** Lists the top N entries by size (or by recency) so
|
|
36
|
+
operators can debug a cache filling up. Values are deliberately omitted —
|
|
37
|
+
PII / secret risk. Backends opt in via an optional `listEntries?` method on
|
|
38
|
+
`CacheProvider`; non-supporting backends return `{ supported: false }` and
|
|
39
|
+
the UI renders a "not supported by this backend" hint. The in-memory cache
|
|
40
|
+
implements it using its existing per-entry byte tracking.
|
|
41
|
+
|
|
42
|
+
`CacheStats` also gains `scope: "instance" | "cluster"`.
|
|
43
|
+
|
|
44
|
+
**Multi-instance scope warning.** A new `<InstanceScopeBanner>` component in
|
|
45
|
+
`@checkstack/ui` renders a yellow banner above any runtime panel whose
|
|
46
|
+
backend reports `scope: "instance"` — i.e. in-memory queue or cache running
|
|
47
|
+
in a horizontally scaled deployment. The banner explains the metrics are
|
|
48
|
+
local to the responding replica and recommends switching to a clustered
|
|
49
|
+
backend (Redis-backed queue / cache) for cluster-wide visibility.
|
|
50
|
+
|
|
51
|
+
**Bug fix — stable cache provider proxy.** `CacheManagerImpl.getProvider()`
|
|
52
|
+
now returns a single stable proxy that delegates to whatever provider is
|
|
53
|
+
currently active. Previously, consumers of `createCachedScope` (and any
|
|
54
|
+
direct `cacheManager.getProvider()` caller) captured the active provider
|
|
55
|
+
reference at plugin-init time. After any `setActiveBackend` call — including
|
|
56
|
+
saving the same memory config in the new Cache tab, which reconstructs the
|
|
57
|
+
in-memory cache — those scopes wrote to an orphaned old provider while the
|
|
58
|
+
runtime panel read stats from the new (empty) one, making the runtime panel
|
|
59
|
+
appear to report 0 keys. With the proxy, all consumers share a single stable
|
|
60
|
+
identity and writes always land in the active provider.
|
|
61
|
+
|
|
62
|
+
**Bytes tracking on the in-memory cache.** `InMemoryCache.getStats().sizeBytes`
|
|
63
|
+
now returns a running approximation (UTF-8 bytes of the key plus
|
|
64
|
+
`v8.serialize(value).byteLength`, with a JSON fallback) that's kept in sync
|
|
65
|
+
across all eviction paths. Treat the number as a sanity gauge; it doesn't
|
|
66
|
+
include `Map` per-entry overhead.
|
|
67
|
+
|
|
68
|
+
**Pagination.** Both `Queue<T>.listJobs` and `CacheProvider.listEntries?`
|
|
69
|
+
are offset-paginated. Inputs gain an `offset: number`; outputs change to
|
|
70
|
+
`{ items, total: number | null, hasMore: boolean }`. `total` is nullable
|
|
71
|
+
so backends that can't compute it cheaply still paginate via `hasMore`.
|
|
72
|
+
The UI uses the existing `<Pagination>` component with a 25-row default
|
|
73
|
+
page size. `QueueManager.listJobs` aggregates by over-fetching
|
|
74
|
+
`[0, offset+limit)` per queue, merge-sorting, then slicing the window —
|
|
75
|
+
optimal for the single-queue case, acceptable for the multi-queue case
|
|
76
|
+
within the UI's reasonable page-depth bounds. BullMQ uses native offset
|
|
77
|
+
ranges via `getJobs(types, start, end)` plus `getJobCounts` for `total`.
|
|
78
|
+
|
|
79
|
+
**Pending tab.** The Queue runtime panel exposes a virtual `"pending"`
|
|
80
|
+
state (waiting ∪ delayed, FIFO). It's now the default sub-tab, since
|
|
81
|
+
"what's queued up?" is the most common question. Per-row state is shown
|
|
82
|
+
when viewing the combined list.
|
|
83
|
+
|
|
84
|
+
**Recurring schedules visible under Pending.** Cron- and interval-based
|
|
85
|
+
recurring jobs (e.g. healthchecks) are surfaced under Pending/Delayed
|
|
86
|
+
between fires, with a `nextRunAt` countdown column and a "(recurring)"
|
|
87
|
+
label. `JobSummary` gains optional `nextRunAt: Date` and `recurring:
|
|
88
|
+
boolean` fields. The in-memory queue synthesises these rows from its
|
|
89
|
+
`recurringJobs` registry; BullMQ already materialises the next fire of
|
|
90
|
+
each scheduler as a delayed job and we now surface its trigger time and
|
|
91
|
+
the `repeatJobKey`-derived `recurring` flag.
|
|
92
|
+
|
|
93
|
+
**Bug fix — drop hook emits with no listeners.** `EventBus.emit` no
|
|
94
|
+
longer enqueues a job when zero listeners (distributed or instance-local)
|
|
95
|
+
are registered for the hook. Previously, hooks like
|
|
96
|
+
`core.plugin.initialized` — emitted on every plugin init but subscribed
|
|
97
|
+
to by nothing in the core repo — accumulated one waiting job per emit
|
|
98
|
+
forever. The in-memory queue's `processNext` short-circuits when there
|
|
99
|
+
are zero consumer groups, so its post-loop cleanup never ran for these
|
|
100
|
+
orphaned jobs. The fix drops the emit at the source and logs a debug
|
|
101
|
+
line. Note: in distributed deployments using a Redis-backed queue, this
|
|
102
|
+
means a subscriber on another replica won't receive an event if no
|
|
103
|
+
replica that emits it has a local listener. Plugins needing cross-process
|
|
104
|
+
delivery must register their listener on every replica that should
|
|
105
|
+
receive the hook.
|
|
106
|
+
|
|
107
|
+
**Breaking notes (treated as minor under beta semantics)**:
|
|
108
|
+
|
|
109
|
+
- `@checkstack/infrastructure-common` removes `registerInfrastructureTab`
|
|
110
|
+
and `getInfrastructureTabs`; former callers must register an extension
|
|
111
|
+
into `InfrastructureTabsSlot`.
|
|
112
|
+
- `@checkstack/queue-api`'s `Queue<T>` interface requires the new
|
|
113
|
+
`listJobs(opts)` method returning `ListJobsResult` (paginated). Both
|
|
114
|
+
bundled queue backends (memory, BullMQ) are updated; out-of-tree
|
|
115
|
+
implementations will need to add it.
|
|
116
|
+
- `QueueStats` and `CacheStats` add a required `scope` field.
|
|
117
|
+
- `CacheProvider.listEntries?` (when implemented) now returns
|
|
118
|
+
`ListEntriesResult` instead of `CacheEntrySummary[]`.
|
|
119
|
+
- `JobState` adds a `"pending"` variant.
|
|
120
|
+
|
|
121
|
+
### Patch Changes
|
|
122
|
+
|
|
123
|
+
- Updated dependencies [42abfff]
|
|
124
|
+
- Updated dependencies [aa89bc5]
|
|
125
|
+
- @checkstack/common@0.9.0
|
|
126
|
+
- @checkstack/queue-api@0.3.0
|
|
127
|
+
- @checkstack/backend-api@0.15.1
|
|
128
|
+
- @checkstack/queue-memory-common@0.1.12
|
|
129
|
+
|
|
3
130
|
## 0.3.18
|
|
4
131
|
|
|
5
132
|
### Patch Changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@checkstack/queue-memory-backend",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "src/index.ts",
|
|
6
6
|
"checkstack": {
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@types/bun": "latest",
|
|
29
29
|
"@checkstack/tsconfig": "0.0.7",
|
|
30
|
-
"@checkstack/scripts": "0.
|
|
30
|
+
"@checkstack/scripts": "0.3.0"
|
|
31
31
|
},
|
|
32
32
|
"description": "Checkstack queue-memory-backend plugin",
|
|
33
33
|
"author": {
|
package/src/memory-queue.test.ts
CHANGED
|
@@ -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
|
});
|
package/src/memory-queue.ts
CHANGED
|
@@ -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
|
|