@checkstack/cache-frontend 0.2.3 → 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 CHANGED
@@ -1,5 +1,148 @@
1
1
  # @checkstack/cache-frontend
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [9016526]
8
+ - @checkstack/common@0.10.0
9
+ - @checkstack/cache-common@0.4.0
10
+ - @checkstack/frontend-api@0.5.1
11
+ - @checkstack/infrastructure-common@0.3.1
12
+ - @checkstack/ui@1.8.1
13
+
14
+ ## 0.3.0
15
+
16
+ ### Minor Changes
17
+
18
+ - aa89bc5: Replace the bespoke `registerInfrastructureTab()` registry with a standard
19
+ slot-extension contract (`InfrastructureTabsSlot` from
20
+ `@checkstack/infrastructure-common`). Plugins now contribute infrastructure
21
+ tabs via `createSlotExtension`, depending only on the slot owner.
22
+
23
+ The slot system in `@checkstack/frontend-api` gains a second type parameter
24
+ on `createSlot<TContext, TMetadata>` so extensions can declare typed static
25
+ metadata at registration time (label, icon, access rules, ordering for the
26
+ infrastructure tab bar). A new `useSlotExtensions(slot)` hook returns typed
27
+ extensions and subscribes to plugin lifecycle changes.
28
+
29
+ Each tab body now stacks a **Runtime** sub-section (live state, read-only)
30
+ on top of a **Configuration** sub-section (settings, gated by `canUpdate`).
31
+
32
+ **Queue runtime panel.** Surfaces aggregated counts (pending / processing /
33
+ completed / failed) plus three sub-tabs of recent jobs: **Active**, **Recent
34
+ failed** (with the failure message), and **Recent completed** (with
35
+ duration). Job payloads are deliberately not surfaced — they may carry
36
+ secrets and need a separate manage-access gate to be shown.
37
+
38
+ To support this, `Queue<T>` gains a required `listJobs(opts)` method
39
+ returning `JobSummary[]` (no payloads), and `QueueStats` gains a
40
+ `scope: "instance" | "cluster"` field. The in-memory queue keeps rolling
41
+ ring buffers (200 entries) for completed/failed history and tracks active
42
+ jobs by id; BullMQ uses native `getJobs`. `QueueManager.listJobs` aggregates
43
+ across queues and sorts (most-recent-first for terminal states, FIFO for
44
+ active/waiting/delayed).
45
+
46
+ **Cache runtime panel.** Lists the top N entries by size (or by recency) so
47
+ operators can debug a cache filling up. Values are deliberately omitted —
48
+ PII / secret risk. Backends opt in via an optional `listEntries?` method on
49
+ `CacheProvider`; non-supporting backends return `{ supported: false }` and
50
+ the UI renders a "not supported by this backend" hint. The in-memory cache
51
+ implements it using its existing per-entry byte tracking.
52
+
53
+ `CacheStats` also gains `scope: "instance" | "cluster"`.
54
+
55
+ **Multi-instance scope warning.** A new `<InstanceScopeBanner>` component in
56
+ `@checkstack/ui` renders a yellow banner above any runtime panel whose
57
+ backend reports `scope: "instance"` — i.e. in-memory queue or cache running
58
+ in a horizontally scaled deployment. The banner explains the metrics are
59
+ local to the responding replica and recommends switching to a clustered
60
+ backend (Redis-backed queue / cache) for cluster-wide visibility.
61
+
62
+ **Bug fix — stable cache provider proxy.** `CacheManagerImpl.getProvider()`
63
+ now returns a single stable proxy that delegates to whatever provider is
64
+ currently active. Previously, consumers of `createCachedScope` (and any
65
+ direct `cacheManager.getProvider()` caller) captured the active provider
66
+ reference at plugin-init time. After any `setActiveBackend` call — including
67
+ saving the same memory config in the new Cache tab, which reconstructs the
68
+ in-memory cache — those scopes wrote to an orphaned old provider while the
69
+ runtime panel read stats from the new (empty) one, making the runtime panel
70
+ appear to report 0 keys. With the proxy, all consumers share a single stable
71
+ identity and writes always land in the active provider.
72
+
73
+ **Bytes tracking on the in-memory cache.** `InMemoryCache.getStats().sizeBytes`
74
+ now returns a running approximation (UTF-8 bytes of the key plus
75
+ `v8.serialize(value).byteLength`, with a JSON fallback) that's kept in sync
76
+ across all eviction paths. Treat the number as a sanity gauge; it doesn't
77
+ include `Map` per-entry overhead.
78
+
79
+ **Pagination.** Both `Queue<T>.listJobs` and `CacheProvider.listEntries?`
80
+ are offset-paginated. Inputs gain an `offset: number`; outputs change to
81
+ `{ items, total: number | null, hasMore: boolean }`. `total` is nullable
82
+ so backends that can't compute it cheaply still paginate via `hasMore`.
83
+ The UI uses the existing `<Pagination>` component with a 25-row default
84
+ page size. `QueueManager.listJobs` aggregates by over-fetching
85
+ `[0, offset+limit)` per queue, merge-sorting, then slicing the window —
86
+ optimal for the single-queue case, acceptable for the multi-queue case
87
+ within the UI's reasonable page-depth bounds. BullMQ uses native offset
88
+ ranges via `getJobs(types, start, end)` plus `getJobCounts` for `total`.
89
+
90
+ **Pending tab.** The Queue runtime panel exposes a virtual `"pending"`
91
+ state (waiting ∪ delayed, FIFO). It's now the default sub-tab, since
92
+ "what's queued up?" is the most common question. Per-row state is shown
93
+ when viewing the combined list.
94
+
95
+ **Recurring schedules visible under Pending.** Cron- and interval-based
96
+ recurring jobs (e.g. healthchecks) are surfaced under Pending/Delayed
97
+ between fires, with a `nextRunAt` countdown column and a "(recurring)"
98
+ label. `JobSummary` gains optional `nextRunAt: Date` and `recurring:
99
+ boolean` fields. The in-memory queue synthesises these rows from its
100
+ `recurringJobs` registry; BullMQ already materialises the next fire of
101
+ each scheduler as a delayed job and we now surface its trigger time and
102
+ the `repeatJobKey`-derived `recurring` flag.
103
+
104
+ **Bug fix — drop hook emits with no listeners.** `EventBus.emit` no
105
+ longer enqueues a job when zero listeners (distributed or instance-local)
106
+ are registered for the hook. Previously, hooks like
107
+ `core.plugin.initialized` — emitted on every plugin init but subscribed
108
+ to by nothing in the core repo — accumulated one waiting job per emit
109
+ forever. The in-memory queue's `processNext` short-circuits when there
110
+ are zero consumer groups, so its post-loop cleanup never ran for these
111
+ orphaned jobs. The fix drops the emit at the source and logs a debug
112
+ line. Note: in distributed deployments using a Redis-backed queue, this
113
+ means a subscriber on another replica won't receive an event if no
114
+ replica that emits it has a local listener. Plugins needing cross-process
115
+ delivery must register their listener on every replica that should
116
+ receive the hook.
117
+
118
+ **Breaking notes (treated as minor under beta semantics)**:
119
+
120
+ - `@checkstack/infrastructure-common` removes `registerInfrastructureTab`
121
+ and `getInfrastructureTabs`; former callers must register an extension
122
+ into `InfrastructureTabsSlot`.
123
+ - `@checkstack/queue-api`'s `Queue<T>` interface requires the new
124
+ `listJobs(opts)` method returning `ListJobsResult` (paginated). Both
125
+ bundled queue backends (memory, BullMQ) are updated; out-of-tree
126
+ implementations will need to add it.
127
+ - `QueueStats` and `CacheStats` add a required `scope` field.
128
+ - `CacheProvider.listEntries?` (when implemented) now returns
129
+ `ListEntriesResult` instead of `CacheEntrySummary[]`.
130
+ - `JobState` adds a `"pending"` variant.
131
+
132
+ ### Patch Changes
133
+
134
+ - Updated dependencies [42abfff]
135
+ - Updated dependencies [3547670]
136
+ - Updated dependencies [1ef2e79]
137
+ - Updated dependencies [aa89bc5]
138
+ - Updated dependencies [950d6ec]
139
+ - Updated dependencies [3547670]
140
+ - @checkstack/common@0.9.0
141
+ - @checkstack/ui@1.8.0
142
+ - @checkstack/frontend-api@0.5.0
143
+ - @checkstack/infrastructure-common@0.3.0
144
+ - @checkstack/cache-common@0.3.0
145
+
3
146
  ## 0.2.3
4
147
 
5
148
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checkstack/cache-frontend",
3
- "version": "0.2.3",
3
+ "version": "0.3.1",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,18 +21,18 @@
21
21
  "lint:code": "eslint . --max-warnings 0"
22
22
  },
23
23
  "dependencies": {
24
- "@checkstack/cache-common": "0.2.0",
25
- "@checkstack/common": "0.7.0",
26
- "@checkstack/frontend-api": "0.4.1",
27
- "@checkstack/infrastructure-common": "0.2.2",
28
- "@checkstack/ui": "1.7.0",
24
+ "@checkstack/cache-common": "0.3.0",
25
+ "@checkstack/common": "0.9.0",
26
+ "@checkstack/frontend-api": "0.5.0",
27
+ "@checkstack/infrastructure-common": "0.3.0",
28
+ "@checkstack/ui": "1.8.0",
29
29
  "lucide-react": "^0.468.0",
30
30
  "react": "^18.3.1"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/react": "^18.3.18",
34
34
  "typescript": "^5.7.2",
35
- "@checkstack/tsconfig": "0.0.6",
36
- "@checkstack/scripts": "0.1.2"
35
+ "@checkstack/tsconfig": "0.0.7",
36
+ "@checkstack/scripts": "0.3.1"
37
37
  }
38
38
  }
@@ -0,0 +1,21 @@
1
+ import type { InfrastructureTabContext } from "@checkstack/infrastructure-common";
2
+ import { CacheConfigTab } from "./CacheConfigTab";
3
+ import { CacheRuntimePanel } from "./CacheRuntimePanel";
4
+
5
+ /**
6
+ * Cache tab body for the Infrastructure Settings page.
7
+ *
8
+ * Stacks two sub-sections inside the same tab:
9
+ * - Runtime: live cache stats (read-only, always shown).
10
+ * - Configuration: provider selection (gated by `canUpdate`).
11
+ */
12
+ export const CacheInfrastructureTab = ({
13
+ canUpdate,
14
+ }: InfrastructureTabContext) => {
15
+ return (
16
+ <div className="space-y-6">
17
+ <CacheRuntimePanel />
18
+ <CacheConfigTab canUpdate={canUpdate} />
19
+ </div>
20
+ );
21
+ };
@@ -0,0 +1,274 @@
1
+ import { useState } from "react";
2
+ import { usePluginClient } from "@checkstack/frontend-api";
3
+ import { CacheApi } from "@checkstack/cache-common";
4
+ import {
5
+ Card,
6
+ CardContent,
7
+ CardDescription,
8
+ CardHeader,
9
+ CardTitle,
10
+ InstanceScopeBanner,
11
+ Pagination,
12
+ Table,
13
+ TableBody,
14
+ TableCell,
15
+ TableHead,
16
+ TableHeader,
17
+ TableRow,
18
+ Tabs,
19
+ TabPanel,
20
+ } from "@checkstack/ui";
21
+ import {
22
+ Activity,
23
+ CheckCircle2,
24
+ Database,
25
+ HardDrive,
26
+ ListOrdered,
27
+ XCircle,
28
+ } from "lucide-react";
29
+
30
+ const REFRESH_INTERVAL_MS = 5000;
31
+ const PAGE_SIZE = 25;
32
+
33
+ type SortBy = "biggest" | "newest";
34
+
35
+ const formatNumber = (n: number | null | undefined) =>
36
+ n === null || n === undefined
37
+ ? "—"
38
+ : n.toLocaleString(undefined, { maximumFractionDigits: 0 });
39
+
40
+ const formatBytes = (n: number | null | undefined) => {
41
+ if (n === null || n === undefined) return "—";
42
+ if (n < 1024) return `${n} B`;
43
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
44
+ if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MiB`;
45
+ return `${(n / 1024 / 1024 / 1024).toFixed(2)} GiB`;
46
+ };
47
+
48
+ const formatHitRate = (
49
+ hits: number | null | undefined,
50
+ misses: number | null | undefined,
51
+ ) => {
52
+ if (hits === null || hits === undefined) return "—";
53
+ if (misses === null || misses === undefined) return "—";
54
+ const total = hits + misses;
55
+ if (total === 0) return "—";
56
+ return `${((hits / total) * 100).toFixed(1)}%`;
57
+ };
58
+
59
+ const truncateMiddle = (s: string, head = 18, tail = 10) => {
60
+ if (s.length <= head + tail + 1) return s;
61
+ return `${s.slice(0, head)}…${s.slice(-tail)}`;
62
+ };
63
+
64
+ const formatTtl = (expiresAt: Date | null | undefined) => {
65
+ if (!expiresAt) return "—";
66
+ const ms = expiresAt.getTime() - Date.now();
67
+ if (ms <= 0) return "expired";
68
+ const sec = Math.round(ms / 1000);
69
+ if (sec < 60) return `${sec}s`;
70
+ const min = Math.round(sec / 60);
71
+ if (min < 60) return `${min}m`;
72
+ const hr = Math.round(min / 60);
73
+ if (hr < 24) return `${hr}h`;
74
+ return `${Math.round(hr / 24)}d`;
75
+ };
76
+
77
+ interface StatTileProps {
78
+ label: string;
79
+ value: string;
80
+ icon: React.ComponentType<{ className?: string }>;
81
+ }
82
+
83
+ const StatTile = ({ label, value, icon: Icon }: StatTileProps) => (
84
+ <div className="flex items-center gap-3 rounded-lg border bg-card px-4 py-3">
85
+ <Icon className="h-5 w-5 shrink-0 text-muted-foreground" />
86
+ <div className="min-w-0">
87
+ <div className="text-xs font-medium text-muted-foreground">{label}</div>
88
+ <div className="text-2xl font-semibold tabular-nums">{value}</div>
89
+ </div>
90
+ </div>
91
+ );
92
+
93
+ const EntriesTable = ({ sortBy }: { sortBy: SortBy }) => {
94
+ const cacheClient = usePluginClient(CacheApi);
95
+ const [page, setPage] = useState(1);
96
+ const offset = (page - 1) * PAGE_SIZE;
97
+
98
+ const { data, isLoading, error } = cacheClient.listEntries.useQuery(
99
+ { offset, limit: PAGE_SIZE, sortBy },
100
+ { refetchInterval: REFRESH_INTERVAL_MS },
101
+ );
102
+
103
+ if (error) {
104
+ return (
105
+ <p className="text-sm text-destructive">Failed to load cache entries.</p>
106
+ );
107
+ }
108
+ if (isLoading) {
109
+ return <p className="text-sm text-muted-foreground">Loading…</p>;
110
+ }
111
+ if (data && !data.supported) {
112
+ return (
113
+ <p className="text-sm text-muted-foreground">
114
+ Listing not supported by this cache backend.
115
+ </p>
116
+ );
117
+ }
118
+ if (!data || data.items.length === 0) {
119
+ return <p className="text-sm text-muted-foreground">No cache entries.</p>;
120
+ }
121
+
122
+ const totalPages =
123
+ data.total === null
124
+ ? data.hasMore
125
+ ? page + 1
126
+ : page
127
+ : Math.max(1, Math.ceil(data.total / PAGE_SIZE));
128
+
129
+ return (
130
+ <div className="space-y-3">
131
+ <Table>
132
+ <TableHeader>
133
+ <TableRow>
134
+ <TableHead>Key</TableHead>
135
+ <TableHead className="text-right">Size</TableHead>
136
+ <TableHead className="text-right">TTL</TableHead>
137
+ </TableRow>
138
+ </TableHeader>
139
+ <TableBody>
140
+ {data.items.map((entry) => (
141
+ <TableRow key={entry.key}>
142
+ <TableCell
143
+ className="font-mono text-xs whitespace-nowrap"
144
+ title={entry.key}
145
+ >
146
+ {truncateMiddle(entry.key)}
147
+ </TableCell>
148
+ <TableCell className="text-right tabular-nums">
149
+ {formatBytes(entry.byteSize)}
150
+ </TableCell>
151
+ <TableCell className="text-right tabular-nums">
152
+ {formatTtl(entry.expiresAt)}
153
+ </TableCell>
154
+ </TableRow>
155
+ ))}
156
+ </TableBody>
157
+ </Table>
158
+ <Pagination
159
+ page={page}
160
+ totalPages={totalPages}
161
+ onPageChange={setPage}
162
+ total={data.total ?? undefined}
163
+ showTotal={data.total !== null}
164
+ />
165
+ </div>
166
+ );
167
+ };
168
+
169
+ const SUB_TABS = [
170
+ {
171
+ id: "biggest",
172
+ label: "Biggest",
173
+ icon: <ListOrdered className="h-4 w-4" />,
174
+ },
175
+ {
176
+ id: "newest",
177
+ label: "Newest",
178
+ icon: <ListOrdered className="h-4 w-4" />,
179
+ },
180
+ ] as const;
181
+
182
+ /**
183
+ * Cache Runtime panel. Counts on top, then a paginated table of keys
184
+ * sorted by size or recency. Values never returned (PII risk).
185
+ */
186
+ export const CacheRuntimePanel = () => {
187
+ const cacheClient = usePluginClient(CacheApi);
188
+ const { data, isLoading, error } = cacheClient.getRuntimeStats.useQuery(
189
+ undefined,
190
+ { refetchInterval: REFRESH_INTERVAL_MS },
191
+ );
192
+ const [sortBy, setSortBy] = useState<SortBy>("biggest");
193
+
194
+ return (
195
+ <div className="space-y-4">
196
+ <InstanceScopeBanner
197
+ scope={data?.scope ?? "instance"}
198
+ subject="Cache"
199
+ recommendation="Switch to a clustered cache (e.g. Redis) for cluster-wide visibility."
200
+ />
201
+
202
+ <Card>
203
+ <CardHeader>
204
+ <CardTitle className="flex items-center gap-2">
205
+ <Activity className="h-5 w-5" />
206
+ Cache Runtime
207
+ </CardTitle>
208
+ <CardDescription>
209
+ {data?.pluginId ? (
210
+ <>
211
+ Active provider:{" "}
212
+ <code className="text-xs">{data.pluginId}</code>. Refreshes
213
+ every {REFRESH_INTERVAL_MS / 1000}s. Backends that can&apos;t
214
+ report a metric cheaply show &quot;—&quot;.
215
+ </>
216
+ ) : (
217
+ <>Refreshes every {REFRESH_INTERVAL_MS / 1000}s.</>
218
+ )}
219
+ </CardDescription>
220
+ </CardHeader>
221
+ <CardContent className="space-y-6">
222
+ {error ? (
223
+ <div className="text-sm text-destructive">
224
+ Failed to load cache stats.
225
+ </div>
226
+ ) : (
227
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
228
+ <StatTile
229
+ label="Keys"
230
+ value={isLoading ? "…" : formatNumber(data?.keyCount)}
231
+ icon={Database}
232
+ />
233
+ <StatTile
234
+ label="Memory"
235
+ value={isLoading ? "…" : formatBytes(data?.sizeBytes)}
236
+ icon={HardDrive}
237
+ />
238
+ <StatTile
239
+ label="Hits"
240
+ value={isLoading ? "…" : formatNumber(data?.hits)}
241
+ icon={CheckCircle2}
242
+ />
243
+ <StatTile
244
+ label="Hit rate"
245
+ value={
246
+ isLoading ? "…" : formatHitRate(data?.hits, data?.misses)
247
+ }
248
+ icon={XCircle}
249
+ />
250
+ </div>
251
+ )}
252
+
253
+ <div className="space-y-3">
254
+ <Tabs
255
+ items={SUB_TABS.map((t) => ({
256
+ id: t.id,
257
+ label: t.label,
258
+ icon: t.icon,
259
+ }))}
260
+ activeTab={sortBy}
261
+ onTabChange={(id) => setSortBy(id as SortBy)}
262
+ />
263
+ <TabPanel id="biggest" activeTab={sortBy}>
264
+ <EntriesTable sortBy="biggest" />
265
+ </TabPanel>
266
+ <TabPanel id="newest" activeTab={sortBy}>
267
+ <EntriesTable sortBy="newest" />
268
+ </TabPanel>
269
+ </div>
270
+ </CardContent>
271
+ </Card>
272
+ </div>
273
+ );
274
+ };
package/src/index.tsx CHANGED
@@ -1,22 +1,26 @@
1
- import { createFrontendPlugin } from "@checkstack/frontend-api";
2
- import { registerInfrastructureTab } from "@checkstack/infrastructure-common";
1
+ import {
2
+ createFrontendPlugin,
3
+ createSlotExtension,
4
+ } from "@checkstack/frontend-api";
5
+ import { InfrastructureTabsSlot } from "@checkstack/infrastructure-common";
3
6
  import { pluginMetadata, cacheAccess } from "@checkstack/cache-common";
4
- import { CacheConfigTab } from "./components/CacheConfigTab";
7
+ import { CacheInfrastructureTab } from "./components/CacheInfrastructureTab";
5
8
  import { HardDrive } from "lucide-react";
6
9
 
7
- // Register cache tab into the Infrastructure Configuration page
8
- registerInfrastructureTab({
9
- id: "cache",
10
- pluginId: pluginMetadata.pluginId,
11
- label: "Cache",
12
- icon: HardDrive,
13
- component: CacheConfigTab,
14
- readAccess: cacheAccess.settings.read,
15
- manageAccess: cacheAccess.settings.manage,
16
- order: 20, // After queue (10)
17
- });
18
-
19
10
  export const cachePlugin = createFrontendPlugin({
20
11
  metadata: pluginMetadata,
21
- // No routes — the cache tab lives inside the infrastructure page
12
+ // No routes — the cache tab lives inside the infrastructure page.
13
+ extensions: [
14
+ createSlotExtension(InfrastructureTabsSlot, {
15
+ id: "cache.infrastructure.tab",
16
+ component: CacheInfrastructureTab,
17
+ metadata: {
18
+ label: "Cache",
19
+ icon: HardDrive,
20
+ readAccess: cacheAccess.settings.read,
21
+ manageAccess: cacheAccess.settings.manage,
22
+ order: 20,
23
+ },
24
+ }),
25
+ ],
22
26
  });