@checkstack/cache-memory-backend 0.2.3 → 0.3.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 CHANGED
@@ -1,5 +1,142 @@
1
1
  # @checkstack/cache-memory-backend
2
2
 
3
+ ## 0.3.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/cache-api@0.3.0
127
+ - @checkstack/backend-api@0.15.1
128
+ - @checkstack/cache-memory-common@0.2.2
129
+
130
+ ## 0.2.4
131
+
132
+ ### Patch Changes
133
+
134
+ - Updated dependencies [50e5f5f]
135
+ - @checkstack/backend-api@0.15.0
136
+ - @checkstack/common@0.8.0
137
+ - @checkstack/cache-memory-common@0.2.1
138
+ - @checkstack/cache-api@0.2.4
139
+
3
140
  ## 0.2.3
4
141
 
5
142
  ### Patch Changes
package/package.json CHANGED
@@ -1,26 +1,36 @@
1
1
  {
2
2
  "name": "@checkstack/cache-memory-backend",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "checkstack": {
7
- "type": "backend"
7
+ "type": "backend",
8
+ "pluginId": "cache-memory",
9
+ "bundle": [
10
+ "@checkstack/cache-memory-common"
11
+ ]
8
12
  },
9
13
  "scripts": {
10
14
  "typecheck": "tsgo -b",
11
15
  "lint": "bun run lint:code",
12
- "lint:code": "eslint . --max-warnings 0"
16
+ "lint:code": "eslint . --max-warnings 0",
17
+ "pack": "bunx @checkstack/scripts plugin-pack"
13
18
  },
14
19
  "dependencies": {
15
- "@checkstack/backend-api": "0.14.0",
16
- "@checkstack/cache-api": "0.2.2",
17
- "@checkstack/cache-memory-common": "0.2.0",
18
- "@checkstack/common": "0.7.0",
20
+ "@checkstack/backend-api": "0.15.0",
21
+ "@checkstack/cache-api": "0.2.4",
22
+ "@checkstack/cache-memory-common": "0.2.1",
23
+ "@checkstack/common": "0.8.0",
19
24
  "zod": "^4.2.1"
20
25
  },
21
26
  "devDependencies": {
22
27
  "@types/bun": "latest",
23
- "@checkstack/tsconfig": "0.0.5",
24
- "@checkstack/scripts": "0.1.2"
25
- }
28
+ "@checkstack/tsconfig": "0.0.7",
29
+ "@checkstack/scripts": "0.3.0"
30
+ },
31
+ "description": "Checkstack cache-memory-backend plugin",
32
+ "author": {
33
+ "name": "Checkstack contributors"
34
+ },
35
+ "license": "Elastic-2.0"
26
36
  }
@@ -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
  });
@@ -1,12 +1,27 @@
1
- import type { CacheProvider } from "@checkstack/cache-api";
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) return undefined;
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.store.delete(key);
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
- // Evict oldest entries if at capacity (and key doesn't already exist)
56
- if (!this.store.has(key) && this.store.size >= this.config.maxEntries) {
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
- // Delete and re-insert to maintain insertion order for LRU
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.store.delete(key);
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.store.delete(key);
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.store.delete(key);
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.store.delete(key);
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
- * This provides simple LRU-style eviction.
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.store.delete(firstKey);
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
  }