@checkstack/cache-common 0.2.1 → 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 CHANGED
@@ -1,5 +1,185 @@
1
1
  # @checkstack/cache-common
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9016526: Add a `/rest/:pluginId/*` HTTP mount that serves every plugin's oRPC contract
8
+ through the REST/OpenAPI shape described by `/api/openapi.json`. Queries are
9
+ `GET` with query parameters, mutations are `POST` with the input as the raw
10
+ JSON body. The existing `/api/:pluginId/*` mount continues to serve oRPC's
11
+ native wire protocol unchanged, so existing clients are not affected.
12
+
13
+ The OpenAPI spec at `/api/openapi.json` now reflects the real mount: every
14
+ `paths` entry is prefixed with `/rest` instead of `/api`.
15
+
16
+ Also fixes a SPA-fallback bug: the backend's `/api-docs` route previously
17
+ returned 404 on production deployments because the static-file middleware
18
+ skipped any path starting with `/api`, capturing `/api-docs` along with real
19
+ API routes. The skip now requires a trailing slash (`/api/`, `/rest/`).
20
+
21
+ Required access rules are now visible in the API Docs UI. The OpenAPI spec
22
+ generator was reading a non-existent `accessRules` field on procedure
23
+ metadata; the real field is `access: AccessRule[]`. Each procedure's access
24
+ rules are now flattened to fully-qualified IDs (e.g. `catalog.system.read`)
25
+ and emitted under `x-orpc-meta.accessRules`, which the existing
26
+ `Required Access Rules` section in the docs UI already knew how to render.
27
+
28
+ The API Docs schema renderer now handles record types (zod `z.record`),
29
+ `$ref`s into `components.schemas`, `oneOf`/`anyOf`/`allOf`, nullable union
30
+ types (`type: ["string", "null"]`), and `format` qualifiers. Previously
31
+ record outputs like `{ statuses: object }` masked the actual value type;
32
+ they now render as `{ [key]: <ResolvedType> { ... } }` with the inner
33
+ schema expanded, capped at 12 levels with cycle detection.
34
+
35
+ **REST method conventions.** `proc()` now defaults to `GET` for queries and
36
+ `POST` for mutations on the `/rest` mount, using bracket-notation query
37
+ params (`?filter[status]=active&ids[0]=a`) for GET inputs. Existing
38
+ procedures were updated to follow REST semantics:
39
+
40
+ - `update*` mutations → `PATCH`
41
+ - `delete*` / `remove*` mutations → `DELETE`
42
+ - `getBulk*` queries and any query taking a large array input → `POST`
43
+ (because `@orpc/openapi@1.13.x` has no GET→POST URL-length fallback)
44
+
45
+ GET endpoints require an `object` input — bare scalars like
46
+ `.input(z.string())` are not valid on GET. `getSystemConfigurations` was
47
+ refactored from `.input(z.string())` to `.input(z.object({ systemId: ... }))`
48
+ to fit the GET shape; the only call-site update was the in-process router
49
+ unpacking `input.systemId` instead of passing `input` directly.
50
+
51
+ The API Docs UI now renders query parameters (path/query/header/cookie) in a
52
+ dedicated table for GET endpoints, and the fetch example shows them in the
53
+ URL with `<required>` / `<optional>` placeholders.
54
+
55
+ ### Patch Changes
56
+
57
+ - Updated dependencies [9016526]
58
+ - @checkstack/common@0.10.0
59
+
60
+ ## 0.3.0
61
+
62
+ ### Minor Changes
63
+
64
+ - aa89bc5: Replace the bespoke `registerInfrastructureTab()` registry with a standard
65
+ slot-extension contract (`InfrastructureTabsSlot` from
66
+ `@checkstack/infrastructure-common`). Plugins now contribute infrastructure
67
+ tabs via `createSlotExtension`, depending only on the slot owner.
68
+
69
+ The slot system in `@checkstack/frontend-api` gains a second type parameter
70
+ on `createSlot<TContext, TMetadata>` so extensions can declare typed static
71
+ metadata at registration time (label, icon, access rules, ordering for the
72
+ infrastructure tab bar). A new `useSlotExtensions(slot)` hook returns typed
73
+ extensions and subscribes to plugin lifecycle changes.
74
+
75
+ Each tab body now stacks a **Runtime** sub-section (live state, read-only)
76
+ on top of a **Configuration** sub-section (settings, gated by `canUpdate`).
77
+
78
+ **Queue runtime panel.** Surfaces aggregated counts (pending / processing /
79
+ completed / failed) plus three sub-tabs of recent jobs: **Active**, **Recent
80
+ failed** (with the failure message), and **Recent completed** (with
81
+ duration). Job payloads are deliberately not surfaced — they may carry
82
+ secrets and need a separate manage-access gate to be shown.
83
+
84
+ To support this, `Queue<T>` gains a required `listJobs(opts)` method
85
+ returning `JobSummary[]` (no payloads), and `QueueStats` gains a
86
+ `scope: "instance" | "cluster"` field. The in-memory queue keeps rolling
87
+ ring buffers (200 entries) for completed/failed history and tracks active
88
+ jobs by id; BullMQ uses native `getJobs`. `QueueManager.listJobs` aggregates
89
+ across queues and sorts (most-recent-first for terminal states, FIFO for
90
+ active/waiting/delayed).
91
+
92
+ **Cache runtime panel.** Lists the top N entries by size (or by recency) so
93
+ operators can debug a cache filling up. Values are deliberately omitted —
94
+ PII / secret risk. Backends opt in via an optional `listEntries?` method on
95
+ `CacheProvider`; non-supporting backends return `{ supported: false }` and
96
+ the UI renders a "not supported by this backend" hint. The in-memory cache
97
+ implements it using its existing per-entry byte tracking.
98
+
99
+ `CacheStats` also gains `scope: "instance" | "cluster"`.
100
+
101
+ **Multi-instance scope warning.** A new `<InstanceScopeBanner>` component in
102
+ `@checkstack/ui` renders a yellow banner above any runtime panel whose
103
+ backend reports `scope: "instance"` — i.e. in-memory queue or cache running
104
+ in a horizontally scaled deployment. The banner explains the metrics are
105
+ local to the responding replica and recommends switching to a clustered
106
+ backend (Redis-backed queue / cache) for cluster-wide visibility.
107
+
108
+ **Bug fix — stable cache provider proxy.** `CacheManagerImpl.getProvider()`
109
+ now returns a single stable proxy that delegates to whatever provider is
110
+ currently active. Previously, consumers of `createCachedScope` (and any
111
+ direct `cacheManager.getProvider()` caller) captured the active provider
112
+ reference at plugin-init time. After any `setActiveBackend` call — including
113
+ saving the same memory config in the new Cache tab, which reconstructs the
114
+ in-memory cache — those scopes wrote to an orphaned old provider while the
115
+ runtime panel read stats from the new (empty) one, making the runtime panel
116
+ appear to report 0 keys. With the proxy, all consumers share a single stable
117
+ identity and writes always land in the active provider.
118
+
119
+ **Bytes tracking on the in-memory cache.** `InMemoryCache.getStats().sizeBytes`
120
+ now returns a running approximation (UTF-8 bytes of the key plus
121
+ `v8.serialize(value).byteLength`, with a JSON fallback) that's kept in sync
122
+ across all eviction paths. Treat the number as a sanity gauge; it doesn't
123
+ include `Map` per-entry overhead.
124
+
125
+ **Pagination.** Both `Queue<T>.listJobs` and `CacheProvider.listEntries?`
126
+ are offset-paginated. Inputs gain an `offset: number`; outputs change to
127
+ `{ items, total: number | null, hasMore: boolean }`. `total` is nullable
128
+ so backends that can't compute it cheaply still paginate via `hasMore`.
129
+ The UI uses the existing `<Pagination>` component with a 25-row default
130
+ page size. `QueueManager.listJobs` aggregates by over-fetching
131
+ `[0, offset+limit)` per queue, merge-sorting, then slicing the window —
132
+ optimal for the single-queue case, acceptable for the multi-queue case
133
+ within the UI's reasonable page-depth bounds. BullMQ uses native offset
134
+ ranges via `getJobs(types, start, end)` plus `getJobCounts` for `total`.
135
+
136
+ **Pending tab.** The Queue runtime panel exposes a virtual `"pending"`
137
+ state (waiting ∪ delayed, FIFO). It's now the default sub-tab, since
138
+ "what's queued up?" is the most common question. Per-row state is shown
139
+ when viewing the combined list.
140
+
141
+ **Recurring schedules visible under Pending.** Cron- and interval-based
142
+ recurring jobs (e.g. healthchecks) are surfaced under Pending/Delayed
143
+ between fires, with a `nextRunAt` countdown column and a "(recurring)"
144
+ label. `JobSummary` gains optional `nextRunAt: Date` and `recurring:
145
+ boolean` fields. The in-memory queue synthesises these rows from its
146
+ `recurringJobs` registry; BullMQ already materialises the next fire of
147
+ each scheduler as a delayed job and we now surface its trigger time and
148
+ the `repeatJobKey`-derived `recurring` flag.
149
+
150
+ **Bug fix — drop hook emits with no listeners.** `EventBus.emit` no
151
+ longer enqueues a job when zero listeners (distributed or instance-local)
152
+ are registered for the hook. Previously, hooks like
153
+ `core.plugin.initialized` — emitted on every plugin init but subscribed
154
+ to by nothing in the core repo — accumulated one waiting job per emit
155
+ forever. The in-memory queue's `processNext` short-circuits when there
156
+ are zero consumer groups, so its post-loop cleanup never ran for these
157
+ orphaned jobs. The fix drops the emit at the source and logs a debug
158
+ line. Note: in distributed deployments using a Redis-backed queue, this
159
+ means a subscriber on another replica won't receive an event if no
160
+ replica that emits it has a local listener. Plugins needing cross-process
161
+ delivery must register their listener on every replica that should
162
+ receive the hook.
163
+
164
+ **Breaking notes (treated as minor under beta semantics)**:
165
+
166
+ - `@checkstack/infrastructure-common` removes `registerInfrastructureTab`
167
+ and `getInfrastructureTabs`; former callers must register an extension
168
+ into `InfrastructureTabsSlot`.
169
+ - `@checkstack/queue-api`'s `Queue<T>` interface requires the new
170
+ `listJobs(opts)` method returning `ListJobsResult` (paginated). Both
171
+ bundled queue backends (memory, BullMQ) are updated; out-of-tree
172
+ implementations will need to add it.
173
+ - `QueueStats` and `CacheStats` add a required `scope` field.
174
+ - `CacheProvider.listEntries?` (when implemented) now returns
175
+ `ListEntriesResult` instead of `CacheEntrySummary[]`.
176
+ - `JobState` adds a `"pending"` variant.
177
+
178
+ ### Patch Changes
179
+
180
+ - Updated dependencies [42abfff]
181
+ - @checkstack/common@0.9.0
182
+
3
183
  ## 0.2.1
4
184
 
5
185
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checkstack/cache-common",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -14,14 +14,14 @@
14
14
  "lint:code": "eslint . --max-warnings 0"
15
15
  },
16
16
  "dependencies": {
17
- "@checkstack/common": "0.7.0",
17
+ "@checkstack/common": "0.9.0",
18
18
  "@orpc/contract": "^1.13.14",
19
19
  "zod": "^4.0.0"
20
20
  },
21
21
  "devDependencies": {
22
22
  "typescript": "^5.7.2",
23
- "@checkstack/tsconfig": "0.0.6",
24
- "@checkstack/scripts": "0.1.2"
23
+ "@checkstack/tsconfig": "0.0.7",
24
+ "@checkstack/scripts": "0.3.1"
25
25
  },
26
26
  "checkstack": {
27
27
  "type": "common"
@@ -6,6 +6,9 @@ import {
6
6
  CachePluginDtoSchema,
7
7
  CacheConfigurationDtoSchema,
8
8
  UpdateCacheConfigurationSchema,
9
+ CacheRuntimeStatsSchema,
10
+ ListCacheEntriesInputSchema,
11
+ ListCacheEntriesResultSchema,
9
12
  } from "./schemas";
10
13
 
11
14
  /**
@@ -32,8 +35,26 @@ export const cacheContract = {
32
35
  userType: "authenticated",
33
36
  access: [cacheAccess.settings.manage],
34
37
  })
38
+ .route({ method: "PATCH" })
35
39
  .input(UpdateCacheConfigurationSchema)
36
40
  .output(CacheConfigurationDtoSchema),
41
+
42
+ // Cache runtime stats - Read access
43
+ getRuntimeStats: proc({
44
+ operationType: "query",
45
+ userType: "authenticated",
46
+ access: [cacheAccess.settings.read],
47
+ }).output(CacheRuntimeStatsSchema),
48
+
49
+ // List cache entries (without values) - Read access. Backends without an
50
+ // affordable enumeration path return `supported: false`.
51
+ listEntries: proc({
52
+ operationType: "query",
53
+ userType: "authenticated",
54
+ access: [cacheAccess.settings.read],
55
+ })
56
+ .input(ListCacheEntriesInputSchema)
57
+ .output(ListCacheEntriesResultSchema),
37
58
  };
38
59
 
39
60
  // Export contract type
package/src/schemas.ts CHANGED
@@ -36,3 +36,66 @@ export const UpdateCacheConfigurationSchema = z.object({
36
36
  export type UpdateCacheConfiguration = z.infer<
37
37
  typeof UpdateCacheConfigurationSchema
38
38
  >;
39
+
40
+ /**
41
+ * Scope of a cache stats response: `"instance"` if the figures reflect just
42
+ * the local process, `"cluster"` if they're shared across the deployment.
43
+ */
44
+ export const CacheStatsScopeSchema = z.enum(["instance", "cluster"]);
45
+ export type CacheStatsScope = z.infer<typeof CacheStatsScopeSchema>;
46
+
47
+ /**
48
+ * Runtime stats DTO for the Infrastructure UI.
49
+ *
50
+ * Each numeric field is nullable to signal "backend can't report it cheaply".
51
+ * `pluginId` is the active cache backend id at read time. `scope` lets the
52
+ * UI warn the operator when in-memory backends are running with horizontal
53
+ * scaling.
54
+ */
55
+ export const CacheRuntimeStatsSchema = z.object({
56
+ pluginId: z.string(),
57
+ keyCount: z.number().int().nonnegative().nullable(),
58
+ sizeBytes: z.number().int().nonnegative().nullable(),
59
+ hits: z.number().int().nonnegative().nullable(),
60
+ misses: z.number().int().nonnegative().nullable(),
61
+ scope: CacheStatsScopeSchema,
62
+ });
63
+
64
+ export type CacheRuntimeStats = z.infer<typeof CacheRuntimeStatsSchema>;
65
+
66
+ export const CacheEntrySummaryDtoSchema = z.object({
67
+ key: z.string(),
68
+ byteSize: z.number().int().nonnegative(),
69
+ expiresAt: z.coerce.date().nullable(),
70
+ });
71
+
72
+ export type CacheEntrySummaryDto = z.infer<typeof CacheEntrySummaryDtoSchema>;
73
+
74
+ export const ListCacheEntriesInputSchema = z.object({
75
+ offset: z.number().int().nonnegative().default(0),
76
+ limit: z.number().int().min(1).max(200),
77
+ sortBy: z.enum(["biggest", "newest"]),
78
+ });
79
+
80
+ export type ListCacheEntriesInput = z.infer<
81
+ typeof ListCacheEntriesInputSchema
82
+ >;
83
+
84
+ /**
85
+ * Response DTO for `listEntries`. `supported` is `false` when the active
86
+ * cache backend doesn't implement entry enumeration; the UI shows a
87
+ * "Listing not supported by this backend" message in that case.
88
+ *
89
+ * `total` is nullable so backends that can't compute it cheaply (some
90
+ * remote caches) can still paginate using `hasMore`.
91
+ */
92
+ export const ListCacheEntriesResultSchema = z.object({
93
+ supported: z.boolean(),
94
+ items: z.array(CacheEntrySummaryDtoSchema),
95
+ total: z.number().int().nonnegative().nullable(),
96
+ hasMore: z.boolean(),
97
+ });
98
+
99
+ export type ListCacheEntriesResult = z.infer<
100
+ typeof ListCacheEntriesResultSchema
101
+ >;