@checkstack/cache-memory-backend 0.2.4 → 0.3.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 +137 -0
- package/package.json +6 -6
- package/src/memory-cache.test.ts +205 -0
- package/src/memory-cache.ts +116 -17
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,142 @@
|
|
|
1
1
|
# @checkstack/cache-memory-backend
|
|
2
2
|
|
|
3
|
+
## 0.3.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/cache-memory-common@0.2.3
|
|
11
|
+
- @checkstack/cache-api@0.3.1
|
|
12
|
+
|
|
13
|
+
## 0.3.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/cache-api@0.3.0
|
|
137
|
+
- @checkstack/backend-api@0.15.1
|
|
138
|
+
- @checkstack/cache-memory-common@0.2.2
|
|
139
|
+
|
|
3
140
|
## 0.2.4
|
|
4
141
|
|
|
5
142
|
### Patch Changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@checkstack/cache-memory-backend",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "src/index.ts",
|
|
6
6
|
"checkstack": {
|
|
@@ -17,16 +17,16 @@
|
|
|
17
17
|
"pack": "bunx @checkstack/scripts plugin-pack"
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@checkstack/backend-api": "0.15.
|
|
21
|
-
"@checkstack/cache-api": "0.
|
|
22
|
-
"@checkstack/cache-memory-common": "0.2.
|
|
23
|
-
"@checkstack/common": "0.
|
|
20
|
+
"@checkstack/backend-api": "0.15.1",
|
|
21
|
+
"@checkstack/cache-api": "0.3.0",
|
|
22
|
+
"@checkstack/cache-memory-common": "0.2.2",
|
|
23
|
+
"@checkstack/common": "0.9.0",
|
|
24
24
|
"zod": "^4.2.1"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/bun": "latest",
|
|
28
28
|
"@checkstack/tsconfig": "0.0.7",
|
|
29
|
-
"@checkstack/scripts": "0.
|
|
29
|
+
"@checkstack/scripts": "0.3.1"
|
|
30
30
|
},
|
|
31
31
|
"description": "Checkstack cache-memory-backend plugin",
|
|
32
32
|
"author": {
|
package/src/memory-cache.test.ts
CHANGED
|
@@ -216,4 +216,209 @@ describe("InMemoryCache", () => {
|
|
|
216
216
|
// Entry may or may not be expired (passive eviction), but no crash
|
|
217
217
|
});
|
|
218
218
|
});
|
|
219
|
+
|
|
220
|
+
describe("getStats — byte tracking", () => {
|
|
221
|
+
it("starts at zero bytes", async () => {
|
|
222
|
+
const cache = createCache();
|
|
223
|
+
const stats = await cache.getStats();
|
|
224
|
+
expect(stats.sizeBytes).toBe(0);
|
|
225
|
+
expect(stats.keyCount).toBe(0);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("grows on set and shrinks on delete", async () => {
|
|
229
|
+
const cache = createCache();
|
|
230
|
+
await cache.set("k", "small");
|
|
231
|
+
const afterSet = await cache.getStats();
|
|
232
|
+
expect(afterSet.sizeBytes).toBeGreaterThan(0);
|
|
233
|
+
|
|
234
|
+
await cache.delete("k");
|
|
235
|
+
const afterDelete = await cache.getStats();
|
|
236
|
+
expect(afterDelete.sizeBytes).toBe(0);
|
|
237
|
+
expect(afterDelete.keyCount).toBe(0);
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it("scales with payload size", async () => {
|
|
241
|
+
const small = createCache();
|
|
242
|
+
const big = createCache();
|
|
243
|
+
await small.set("k", "x");
|
|
244
|
+
await big.set("k", "x".repeat(10_000));
|
|
245
|
+
const smallStats = await small.getStats();
|
|
246
|
+
const bigStats = await big.getStats();
|
|
247
|
+
expect(bigStats.sizeBytes!).toBeGreaterThan(smallStats.sizeBytes! * 100);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it("replaces (not double-counts) on overwrite", async () => {
|
|
251
|
+
const cache = createCache();
|
|
252
|
+
await cache.set("k", "first");
|
|
253
|
+
const first = (await cache.getStats()).sizeBytes!;
|
|
254
|
+
await cache.set("k", "second-but-longer-value");
|
|
255
|
+
const second = (await cache.getStats()).sizeBytes!;
|
|
256
|
+
expect(second).toBeGreaterThan(first);
|
|
257
|
+
expect((await cache.getStats()).keyCount).toBe(1);
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("returns to zero after deleteByPrefix", async () => {
|
|
261
|
+
const cache = createCache();
|
|
262
|
+
await cache.set("p:a", "1");
|
|
263
|
+
await cache.set("p:b", "2");
|
|
264
|
+
await cache.set("other", "3");
|
|
265
|
+
const removed = await cache.deleteByPrefix("p:");
|
|
266
|
+
expect(removed).toBe(2);
|
|
267
|
+
const stats = await cache.getStats();
|
|
268
|
+
expect(stats.keyCount).toBe(1);
|
|
269
|
+
expect(stats.sizeBytes!).toBeGreaterThan(0);
|
|
270
|
+
|
|
271
|
+
await cache.delete("other");
|
|
272
|
+
const empty = await cache.getStats();
|
|
273
|
+
expect(empty.sizeBytes).toBe(0);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("decrements on TTL expiry via get", async () => {
|
|
277
|
+
const cache = createCache();
|
|
278
|
+
await cache.set("k", "value", 10);
|
|
279
|
+
expect((await cache.getStats()).sizeBytes!).toBeGreaterThan(0);
|
|
280
|
+
await new Promise((resolve) => setTimeout(resolve, 30));
|
|
281
|
+
// Passive eviction via get
|
|
282
|
+
expect(await cache.get("k")).toBeUndefined();
|
|
283
|
+
expect((await cache.getStats()).sizeBytes).toBe(0);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
it("decrements on LRU eviction at capacity", async () => {
|
|
287
|
+
const cache = createCache({ maxEntries: 2 });
|
|
288
|
+
await cache.set("a", "x".repeat(100));
|
|
289
|
+
await cache.set("b", "y".repeat(100));
|
|
290
|
+
const before = (await cache.getStats()).sizeBytes!;
|
|
291
|
+
await cache.set("c", "z");
|
|
292
|
+
// "a" should have been evicted; size went down by ~100 bytes plus a key,
|
|
293
|
+
// up by tiny amount for "c" — net should be lower than `before`.
|
|
294
|
+
const after = (await cache.getStats()).sizeBytes!;
|
|
295
|
+
expect(after).toBeLessThan(before);
|
|
296
|
+
expect((await cache.getStats()).keyCount).toBe(2);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it("counts non-JSON-safe values via v8.serialize", async () => {
|
|
300
|
+
const cache = createCache();
|
|
301
|
+
await cache.set("date", new Date());
|
|
302
|
+
await cache.set("map", new Map([["k", "v"]]));
|
|
303
|
+
const stats = await cache.getStats();
|
|
304
|
+
expect(stats.sizeBytes!).toBeGreaterThan(0);
|
|
305
|
+
expect(stats.keyCount).toBe(2);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
it("reports scope=instance", async () => {
|
|
309
|
+
const cache = createCache();
|
|
310
|
+
const stats = await cache.getStats();
|
|
311
|
+
expect(stats.scope).toBe("instance");
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
describe("listEntries", () => {
|
|
316
|
+
it("returns empty when cache is empty", async () => {
|
|
317
|
+
const cache = createCache();
|
|
318
|
+
const result = await cache.listEntries({
|
|
319
|
+
offset: 0,
|
|
320
|
+
limit: 10,
|
|
321
|
+
sortBy: "biggest",
|
|
322
|
+
});
|
|
323
|
+
expect(result.items).toEqual([]);
|
|
324
|
+
expect(result.total).toBe(0);
|
|
325
|
+
expect(result.hasMore).toBe(false);
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
it("sorts by size descending when sortBy=biggest", async () => {
|
|
329
|
+
const cache = createCache();
|
|
330
|
+
await cache.set("small", "x");
|
|
331
|
+
await cache.set("big", "x".repeat(5000));
|
|
332
|
+
await cache.set("medium", "x".repeat(500));
|
|
333
|
+
|
|
334
|
+
const { items, total } = await cache.listEntries({
|
|
335
|
+
offset: 0,
|
|
336
|
+
limit: 10,
|
|
337
|
+
sortBy: "biggest",
|
|
338
|
+
});
|
|
339
|
+
expect(items.map((e) => e.key)).toEqual(["big", "medium", "small"]);
|
|
340
|
+
expect(total).toBe(3);
|
|
341
|
+
for (let i = 1; i < items.length; i++) {
|
|
342
|
+
expect(items[i - 1].byteSize).toBeGreaterThanOrEqual(
|
|
343
|
+
items[i].byteSize,
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
it("sorts by insertion recency when sortBy=newest", async () => {
|
|
349
|
+
const cache = createCache();
|
|
350
|
+
await cache.set("first", "a");
|
|
351
|
+
await cache.set("second", "b");
|
|
352
|
+
await cache.set("third", "c");
|
|
353
|
+
|
|
354
|
+
const { items } = await cache.listEntries({
|
|
355
|
+
offset: 0,
|
|
356
|
+
limit: 10,
|
|
357
|
+
sortBy: "newest",
|
|
358
|
+
});
|
|
359
|
+
expect(items.map((e) => e.key)).toEqual(["third", "second", "first"]);
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it("paginates with offset/limit and reports total/hasMore", async () => {
|
|
363
|
+
const cache = createCache();
|
|
364
|
+
for (let i = 0; i < 30; i++) {
|
|
365
|
+
await cache.set(`k-${i}`, "x".repeat(i));
|
|
366
|
+
}
|
|
367
|
+
const page1 = await cache.listEntries({
|
|
368
|
+
offset: 0,
|
|
369
|
+
limit: 5,
|
|
370
|
+
sortBy: "biggest",
|
|
371
|
+
});
|
|
372
|
+
expect(page1.items).toHaveLength(5);
|
|
373
|
+
expect(page1.total).toBe(30);
|
|
374
|
+
expect(page1.hasMore).toBe(true);
|
|
375
|
+
|
|
376
|
+
const page2 = await cache.listEntries({
|
|
377
|
+
offset: 5,
|
|
378
|
+
limit: 5,
|
|
379
|
+
sortBy: "biggest",
|
|
380
|
+
});
|
|
381
|
+
expect(page2.items).toHaveLength(5);
|
|
382
|
+
expect(page2.items.map((e) => e.key)).not.toEqual(
|
|
383
|
+
page1.items.map((e) => e.key),
|
|
384
|
+
);
|
|
385
|
+
|
|
386
|
+
const lastPage = await cache.listEntries({
|
|
387
|
+
offset: 28,
|
|
388
|
+
limit: 5,
|
|
389
|
+
sortBy: "biggest",
|
|
390
|
+
});
|
|
391
|
+
expect(lastPage.items).toHaveLength(2);
|
|
392
|
+
expect(lastPage.hasMore).toBe(false);
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
it("does NOT include cached values in summaries", async () => {
|
|
396
|
+
const cache = createCache();
|
|
397
|
+
await cache.set("secret", { token: "very-private" });
|
|
398
|
+
const { items } = await cache.listEntries({
|
|
399
|
+
offset: 0,
|
|
400
|
+
limit: 10,
|
|
401
|
+
sortBy: "biggest",
|
|
402
|
+
});
|
|
403
|
+
expect(items[0].key).toBe("secret");
|
|
404
|
+
expect(Object.keys(items[0]).sort()).toEqual(
|
|
405
|
+
["byteSize", "expiresAt", "key"].sort(),
|
|
406
|
+
);
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
it("surfaces TTL as expiresAt Date or null", async () => {
|
|
410
|
+
const cache = createCache();
|
|
411
|
+
await cache.set("ephemeral", "x", 60_000);
|
|
412
|
+
await cache.set("forever", "y");
|
|
413
|
+
const { items } = await cache.listEntries({
|
|
414
|
+
offset: 0,
|
|
415
|
+
limit: 10,
|
|
416
|
+
sortBy: "newest",
|
|
417
|
+
});
|
|
418
|
+
const ephemeral = items.find((e) => e.key === "ephemeral")!;
|
|
419
|
+
const forever = items.find((e) => e.key === "forever")!;
|
|
420
|
+
expect(ephemeral.expiresAt).toBeInstanceOf(Date);
|
|
421
|
+
expect(forever.expiresAt).toBeNull();
|
|
422
|
+
});
|
|
423
|
+
});
|
|
219
424
|
});
|
package/src/memory-cache.ts
CHANGED
|
@@ -1,12 +1,27 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
CacheProvider,
|
|
3
|
+
CacheStats,
|
|
4
|
+
CacheEntrySummary,
|
|
5
|
+
ListEntriesOptions,
|
|
6
|
+
ListEntriesResult,
|
|
7
|
+
} from "@checkstack/cache-api";
|
|
2
8
|
|
|
3
9
|
/**
|
|
4
10
|
* Internal cache entry with optional expiration tracking.
|
|
11
|
+
*
|
|
12
|
+
* `byteSize` is an approximation of the entry's footprint computed at
|
|
13
|
+
* `set` time (UTF-8 byte length of the key plus a `v8.serialize`-based
|
|
14
|
+
* snapshot of the value, with a JSON fallback). It does not include the
|
|
15
|
+
* `Map` per-entry overhead and is intended for the Infrastructure runtime
|
|
16
|
+
* panel, not for memory-pressure decisions.
|
|
5
17
|
*/
|
|
6
18
|
interface CacheEntry {
|
|
7
19
|
value: unknown;
|
|
8
20
|
/** Absolute timestamp (ms since epoch) when this entry expires, or undefined for no expiry */
|
|
9
21
|
expiresAt: number | undefined;
|
|
22
|
+
byteSize: number;
|
|
23
|
+
/** Insertion order — used to sort by "newest" without keeping a separate index. */
|
|
24
|
+
insertionSeq: number;
|
|
10
25
|
}
|
|
11
26
|
|
|
12
27
|
/**
|
|
@@ -17,6 +32,30 @@ export interface InMemoryCacheConfig {
|
|
|
17
32
|
sweepIntervalMs: number;
|
|
18
33
|
}
|
|
19
34
|
|
|
35
|
+
/**
|
|
36
|
+
* Approximate the byte footprint of a cache entry.
|
|
37
|
+
*
|
|
38
|
+
* Tries `v8.serialize` first (handles Dates, Maps, typed arrays, etc.); if
|
|
39
|
+
* that throws — e.g. on functions — falls back to JSON. If both fail we
|
|
40
|
+
* count just the key. The number is an estimate; treat it as a sanity gauge.
|
|
41
|
+
*/
|
|
42
|
+
function estimateEntryBytes(key: string, value: unknown): number {
|
|
43
|
+
const keyBytes = Buffer.byteLength(key, "utf8");
|
|
44
|
+
try {
|
|
45
|
+
// Lazy require so the module stays runtime-portable.
|
|
46
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
47
|
+
const v8 = require("node:v8") as typeof import("node:v8");
|
|
48
|
+
return keyBytes + v8.serialize(value).byteLength;
|
|
49
|
+
} catch {
|
|
50
|
+
try {
|
|
51
|
+
const json = JSON.stringify(value) ?? "";
|
|
52
|
+
return keyBytes + Buffer.byteLength(json, "utf8");
|
|
53
|
+
} catch {
|
|
54
|
+
return keyBytes;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
20
59
|
/**
|
|
21
60
|
* In-memory CacheProvider implementation using a Map.
|
|
22
61
|
*
|
|
@@ -24,13 +63,17 @@ export interface InMemoryCacheConfig {
|
|
|
24
63
|
* - Passive TTL eviction: expired entries are detected on `get` and `has`
|
|
25
64
|
* - Active sweep: periodic background sweep removes expired entries
|
|
26
65
|
* - LRU-style eviction: oldest entries are evicted when maxEntries is reached
|
|
66
|
+
* - Approximate byte tracking for runtime stats
|
|
27
67
|
*/
|
|
28
68
|
export class InMemoryCache implements CacheProvider {
|
|
29
69
|
private store = new Map<string, CacheEntry>();
|
|
30
70
|
private sweepTimer: ReturnType<typeof setInterval> | undefined;
|
|
71
|
+
private hitCount = 0;
|
|
72
|
+
private missCount = 0;
|
|
73
|
+
private byteSize = 0;
|
|
74
|
+
private insertionCounter = 0;
|
|
31
75
|
|
|
32
76
|
constructor(private config: InMemoryCacheConfig) {
|
|
33
|
-
// Start periodic sweep if configured
|
|
34
77
|
if (config.sweepIntervalMs > 0) {
|
|
35
78
|
this.sweepTimer = setInterval(() => {
|
|
36
79
|
this.sweep();
|
|
@@ -38,43 +81,58 @@ export class InMemoryCache implements CacheProvider {
|
|
|
38
81
|
}
|
|
39
82
|
}
|
|
40
83
|
|
|
84
|
+
private removeEntry(key: string): void {
|
|
85
|
+
const entry = this.store.get(key);
|
|
86
|
+
if (entry) {
|
|
87
|
+
this.byteSize -= entry.byteSize;
|
|
88
|
+
this.store.delete(key);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
41
92
|
async get<T>(key: string): Promise<T | undefined> {
|
|
42
93
|
const entry = this.store.get(key);
|
|
43
|
-
if (!entry)
|
|
94
|
+
if (!entry) {
|
|
95
|
+
this.missCount++;
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
44
98
|
|
|
45
|
-
// Passive TTL eviction
|
|
46
99
|
if (entry.expiresAt !== undefined && Date.now() > entry.expiresAt) {
|
|
47
|
-
this.
|
|
100
|
+
this.removeEntry(key);
|
|
101
|
+
this.missCount++;
|
|
48
102
|
return undefined;
|
|
49
103
|
}
|
|
50
104
|
|
|
105
|
+
this.hitCount++;
|
|
51
106
|
return entry.value as T;
|
|
52
107
|
}
|
|
53
108
|
|
|
54
109
|
async set<T>(key: string, value: T, ttlMs?: number): Promise<void> {
|
|
55
|
-
//
|
|
56
|
-
|
|
110
|
+
// If replacing, drop the old entry's bytes first.
|
|
111
|
+
this.removeEntry(key);
|
|
112
|
+
|
|
113
|
+
if (this.store.size >= this.config.maxEntries) {
|
|
57
114
|
this.evictOldest();
|
|
58
115
|
}
|
|
59
116
|
|
|
60
|
-
|
|
61
|
-
this.store.delete(key);
|
|
62
|
-
|
|
117
|
+
const byteSize = estimateEntryBytes(key, value);
|
|
63
118
|
this.store.set(key, {
|
|
64
119
|
value,
|
|
65
120
|
expiresAt: ttlMs === undefined ? undefined : Date.now() + ttlMs,
|
|
121
|
+
byteSize,
|
|
122
|
+
insertionSeq: ++this.insertionCounter,
|
|
66
123
|
});
|
|
124
|
+
this.byteSize += byteSize;
|
|
67
125
|
}
|
|
68
126
|
|
|
69
127
|
async delete(key: string): Promise<void> {
|
|
70
|
-
this.
|
|
128
|
+
this.removeEntry(key);
|
|
71
129
|
}
|
|
72
130
|
|
|
73
131
|
async deleteByPrefix(prefix: string): Promise<number> {
|
|
74
132
|
let removed = 0;
|
|
75
133
|
for (const key of this.store.keys()) {
|
|
76
134
|
if (key.startsWith(prefix)) {
|
|
77
|
-
this.
|
|
135
|
+
this.removeEntry(key);
|
|
78
136
|
removed++;
|
|
79
137
|
}
|
|
80
138
|
}
|
|
@@ -85,9 +143,8 @@ export class InMemoryCache implements CacheProvider {
|
|
|
85
143
|
const entry = this.store.get(key);
|
|
86
144
|
if (!entry) return false;
|
|
87
145
|
|
|
88
|
-
// Passive TTL eviction
|
|
89
146
|
if (entry.expiresAt !== undefined && Date.now() > entry.expiresAt) {
|
|
90
|
-
this.
|
|
147
|
+
this.removeEntry(key);
|
|
91
148
|
return false;
|
|
92
149
|
}
|
|
93
150
|
|
|
@@ -102,19 +159,19 @@ export class InMemoryCache implements CacheProvider {
|
|
|
102
159
|
const now = Date.now();
|
|
103
160
|
for (const [key, entry] of this.store) {
|
|
104
161
|
if (entry.expiresAt !== undefined && now > entry.expiresAt) {
|
|
105
|
-
this.
|
|
162
|
+
this.removeEntry(key);
|
|
106
163
|
}
|
|
107
164
|
}
|
|
108
165
|
}
|
|
109
166
|
|
|
110
167
|
/**
|
|
111
168
|
* Evict the oldest entry (first in Map insertion order).
|
|
112
|
-
*
|
|
169
|
+
* Provides simple LRU-style eviction.
|
|
113
170
|
*/
|
|
114
171
|
private evictOldest(): void {
|
|
115
172
|
const firstKey = this.store.keys().next().value;
|
|
116
173
|
if (firstKey !== undefined) {
|
|
117
|
-
this.
|
|
174
|
+
this.removeEntry(firstKey);
|
|
118
175
|
}
|
|
119
176
|
}
|
|
120
177
|
|
|
@@ -134,4 +191,46 @@ export class InMemoryCache implements CacheProvider {
|
|
|
134
191
|
get size(): number {
|
|
135
192
|
return this.store.size;
|
|
136
193
|
}
|
|
194
|
+
|
|
195
|
+
async getStats(): Promise<CacheStats> {
|
|
196
|
+
return {
|
|
197
|
+
keyCount: this.store.size,
|
|
198
|
+
sizeBytes: this.byteSize,
|
|
199
|
+
hits: this.hitCount,
|
|
200
|
+
misses: this.missCount,
|
|
201
|
+
scope: "instance",
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async listEntries(opts: ListEntriesOptions): Promise<ListEntriesResult> {
|
|
206
|
+
const limit = Math.max(0, opts.limit);
|
|
207
|
+
const offset = Math.max(0, opts.offset);
|
|
208
|
+
const total = this.store.size;
|
|
209
|
+
if (limit === 0) {
|
|
210
|
+
return { items: [], total, hasMore: total > offset };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const all: Array<CacheEntrySummary & { insertionSeq: number }> = [];
|
|
214
|
+
for (const [key, entry] of this.store) {
|
|
215
|
+
all.push({
|
|
216
|
+
key,
|
|
217
|
+
byteSize: entry.byteSize,
|
|
218
|
+
expiresAt:
|
|
219
|
+
entry.expiresAt === undefined ? null : new Date(entry.expiresAt),
|
|
220
|
+
insertionSeq: entry.insertionSeq,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (opts.sortBy === "biggest") {
|
|
225
|
+
all.sort((a, b) => b.byteSize - a.byteSize);
|
|
226
|
+
} else {
|
|
227
|
+
// newest first
|
|
228
|
+
all.sort((a, b) => b.insertionSeq - a.insertionSeq);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const items = all
|
|
232
|
+
.slice(offset, offset + limit)
|
|
233
|
+
.map(({ key, byteSize, expiresAt }) => ({ key, byteSize, expiresAt }));
|
|
234
|
+
return { items, total, hasMore: offset + items.length < total };
|
|
235
|
+
}
|
|
137
236
|
}
|