@checkstack/backend 0.9.0 → 0.10.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,200 @@
1
1
  # @checkstack/backend
2
2
 
3
+ ## 0.10.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
+ - @checkstack/auth-common@0.7.0
60
+ - @checkstack/api-docs-common@0.1.13
61
+ - @checkstack/backend-api@0.15.2
62
+ - @checkstack/pluginmanager-common@0.2.2
63
+ - @checkstack/signal-backend@0.2.5
64
+ - @checkstack/signal-common@0.2.3
65
+ - @checkstack/cache-api@0.3.1
66
+ - @checkstack/queue-api@0.3.1
67
+
68
+ ## 0.9.1
69
+
70
+ ### Patch Changes
71
+
72
+ - aa89bc5: Replace the bespoke `registerInfrastructureTab()` registry with a standard
73
+ slot-extension contract (`InfrastructureTabsSlot` from
74
+ `@checkstack/infrastructure-common`). Plugins now contribute infrastructure
75
+ tabs via `createSlotExtension`, depending only on the slot owner.
76
+
77
+ The slot system in `@checkstack/frontend-api` gains a second type parameter
78
+ on `createSlot<TContext, TMetadata>` so extensions can declare typed static
79
+ metadata at registration time (label, icon, access rules, ordering for the
80
+ infrastructure tab bar). A new `useSlotExtensions(slot)` hook returns typed
81
+ extensions and subscribes to plugin lifecycle changes.
82
+
83
+ Each tab body now stacks a **Runtime** sub-section (live state, read-only)
84
+ on top of a **Configuration** sub-section (settings, gated by `canUpdate`).
85
+
86
+ **Queue runtime panel.** Surfaces aggregated counts (pending / processing /
87
+ completed / failed) plus three sub-tabs of recent jobs: **Active**, **Recent
88
+ failed** (with the failure message), and **Recent completed** (with
89
+ duration). Job payloads are deliberately not surfaced — they may carry
90
+ secrets and need a separate manage-access gate to be shown.
91
+
92
+ To support this, `Queue<T>` gains a required `listJobs(opts)` method
93
+ returning `JobSummary[]` (no payloads), and `QueueStats` gains a
94
+ `scope: "instance" | "cluster"` field. The in-memory queue keeps rolling
95
+ ring buffers (200 entries) for completed/failed history and tracks active
96
+ jobs by id; BullMQ uses native `getJobs`. `QueueManager.listJobs` aggregates
97
+ across queues and sorts (most-recent-first for terminal states, FIFO for
98
+ active/waiting/delayed).
99
+
100
+ **Cache runtime panel.** Lists the top N entries by size (or by recency) so
101
+ operators can debug a cache filling up. Values are deliberately omitted —
102
+ PII / secret risk. Backends opt in via an optional `listEntries?` method on
103
+ `CacheProvider`; non-supporting backends return `{ supported: false }` and
104
+ the UI renders a "not supported by this backend" hint. The in-memory cache
105
+ implements it using its existing per-entry byte tracking.
106
+
107
+ `CacheStats` also gains `scope: "instance" | "cluster"`.
108
+
109
+ **Multi-instance scope warning.** A new `<InstanceScopeBanner>` component in
110
+ `@checkstack/ui` renders a yellow banner above any runtime panel whose
111
+ backend reports `scope: "instance"` — i.e. in-memory queue or cache running
112
+ in a horizontally scaled deployment. The banner explains the metrics are
113
+ local to the responding replica and recommends switching to a clustered
114
+ backend (Redis-backed queue / cache) for cluster-wide visibility.
115
+
116
+ **Bug fix — stable cache provider proxy.** `CacheManagerImpl.getProvider()`
117
+ now returns a single stable proxy that delegates to whatever provider is
118
+ currently active. Previously, consumers of `createCachedScope` (and any
119
+ direct `cacheManager.getProvider()` caller) captured the active provider
120
+ reference at plugin-init time. After any `setActiveBackend` call — including
121
+ saving the same memory config in the new Cache tab, which reconstructs the
122
+ in-memory cache — those scopes wrote to an orphaned old provider while the
123
+ runtime panel read stats from the new (empty) one, making the runtime panel
124
+ appear to report 0 keys. With the proxy, all consumers share a single stable
125
+ identity and writes always land in the active provider.
126
+
127
+ **Bytes tracking on the in-memory cache.** `InMemoryCache.getStats().sizeBytes`
128
+ now returns a running approximation (UTF-8 bytes of the key plus
129
+ `v8.serialize(value).byteLength`, with a JSON fallback) that's kept in sync
130
+ across all eviction paths. Treat the number as a sanity gauge; it doesn't
131
+ include `Map` per-entry overhead.
132
+
133
+ **Pagination.** Both `Queue<T>.listJobs` and `CacheProvider.listEntries?`
134
+ are offset-paginated. Inputs gain an `offset: number`; outputs change to
135
+ `{ items, total: number | null, hasMore: boolean }`. `total` is nullable
136
+ so backends that can't compute it cheaply still paginate via `hasMore`.
137
+ The UI uses the existing `<Pagination>` component with a 25-row default
138
+ page size. `QueueManager.listJobs` aggregates by over-fetching
139
+ `[0, offset+limit)` per queue, merge-sorting, then slicing the window —
140
+ optimal for the single-queue case, acceptable for the multi-queue case
141
+ within the UI's reasonable page-depth bounds. BullMQ uses native offset
142
+ ranges via `getJobs(types, start, end)` plus `getJobCounts` for `total`.
143
+
144
+ **Pending tab.** The Queue runtime panel exposes a virtual `"pending"`
145
+ state (waiting ∪ delayed, FIFO). It's now the default sub-tab, since
146
+ "what's queued up?" is the most common question. Per-row state is shown
147
+ when viewing the combined list.
148
+
149
+ **Recurring schedules visible under Pending.** Cron- and interval-based
150
+ recurring jobs (e.g. healthchecks) are surfaced under Pending/Delayed
151
+ between fires, with a `nextRunAt` countdown column and a "(recurring)"
152
+ label. `JobSummary` gains optional `nextRunAt: Date` and `recurring:
153
+ boolean` fields. The in-memory queue synthesises these rows from its
154
+ `recurringJobs` registry; BullMQ already materialises the next fire of
155
+ each scheduler as a delayed job and we now surface its trigger time and
156
+ the `repeatJobKey`-derived `recurring` flag.
157
+
158
+ **Bug fix — drop hook emits with no listeners.** `EventBus.emit` no
159
+ longer enqueues a job when zero listeners (distributed or instance-local)
160
+ are registered for the hook. Previously, hooks like
161
+ `core.plugin.initialized` — emitted on every plugin init but subscribed
162
+ to by nothing in the core repo — accumulated one waiting job per emit
163
+ forever. The in-memory queue's `processNext` short-circuits when there
164
+ are zero consumer groups, so its post-loop cleanup never ran for these
165
+ orphaned jobs. The fix drops the emit at the source and logs a debug
166
+ line. Note: in distributed deployments using a Redis-backed queue, this
167
+ means a subscriber on another replica won't receive an event if no
168
+ replica that emits it has a local listener. Plugins needing cross-process
169
+ delivery must register their listener on every replica that should
170
+ receive the hook.
171
+
172
+ **Breaking notes (treated as minor under beta semantics)**:
173
+
174
+ - `@checkstack/infrastructure-common` removes `registerInfrastructureTab`
175
+ and `getInfrastructureTabs`; former callers must register an extension
176
+ into `InfrastructureTabsSlot`.
177
+ - `@checkstack/queue-api`'s `Queue<T>` interface requires the new
178
+ `listJobs(opts)` method returning `ListJobsResult` (paginated). Both
179
+ bundled queue backends (memory, BullMQ) are updated; out-of-tree
180
+ implementations will need to add it.
181
+ - `QueueStats` and `CacheStats` add a required `scope` field.
182
+ - `CacheProvider.listEntries?` (when implemented) now returns
183
+ `ListEntriesResult` instead of `CacheEntrySummary[]`.
184
+ - `JobState` adds a `"pending"` variant.
185
+
186
+ - Updated dependencies [42abfff]
187
+ - Updated dependencies [aa89bc5]
188
+ - @checkstack/common@0.9.0
189
+ - @checkstack/queue-api@0.3.0
190
+ - @checkstack/cache-api@0.3.0
191
+ - @checkstack/api-docs-common@0.1.12
192
+ - @checkstack/auth-common@0.6.6
193
+ - @checkstack/backend-api@0.15.1
194
+ - @checkstack/pluginmanager-common@0.2.1
195
+ - @checkstack/signal-backend@0.2.4
196
+ - @checkstack/signal-common@0.2.2
197
+
3
198
  ## 0.9.0
4
199
 
5
200
  ### Minor Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checkstack/backend",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "license": "Elastic-2.0",
5
5
  "checkstack": {
6
6
  "type": "backend"
@@ -14,16 +14,16 @@
14
14
  "lint:code": "eslint . --max-warnings 0"
15
15
  },
16
16
  "dependencies": {
17
- "@checkstack/api-docs-common": "0.1.10",
18
- "@checkstack/auth-common": "0.6.4",
19
- "@checkstack/backend-api": "0.14.1",
20
- "@checkstack/common": "0.7.0",
21
- "@checkstack/drizzle-helper": "0.0.4",
22
- "@checkstack/cache-api": "0.2.3",
23
- "@checkstack/queue-api": "0.2.17",
24
- "@checkstack/signal-backend": "0.2.2",
25
- "@checkstack/signal-common": "0.2.0",
26
- "@checkstack/pluginmanager-common": "0.1.0",
17
+ "@checkstack/api-docs-common": "0.1.12",
18
+ "@checkstack/auth-common": "0.6.6",
19
+ "@checkstack/backend-api": "0.15.1",
20
+ "@checkstack/common": "0.9.0",
21
+ "@checkstack/drizzle-helper": "0.0.5",
22
+ "@checkstack/cache-api": "0.3.0",
23
+ "@checkstack/queue-api": "0.3.0",
24
+ "@checkstack/signal-backend": "0.2.4",
25
+ "@checkstack/signal-common": "0.2.2",
26
+ "@checkstack/pluginmanager-common": "0.2.1",
27
27
  "@hono/zod-validator": "^0.7.6",
28
28
  "@orpc/client": "^1.13.14",
29
29
  "@orpc/contract": "^1.13.14",
@@ -44,9 +44,9 @@
44
44
  "@types/pg": "^8.11.0",
45
45
  "@types/bun": "latest",
46
46
  "@types/semver": "^7.5.0",
47
- "@checkstack/tsconfig": "0.0.6",
48
- "@checkstack/scripts": "0.1.2",
49
- "@checkstack/test-utils-backend": "0.1.23",
47
+ "@checkstack/tsconfig": "0.0.7",
48
+ "@checkstack/scripts": "0.3.1",
49
+ "@checkstack/test-utils-backend": "0.1.25",
50
50
  "drizzle-kit": "^0.31.10"
51
51
  }
52
52
  }
package/src/index.ts CHANGED
@@ -335,8 +335,13 @@ if (frontendDistPath && fs.existsSync(frontendDistPath)) {
335
335
  // Serve root-level static files (e.g., /favicon.svg) from the dist directory
336
336
  // before the SPA fallback, so they don't get caught by the index.html handler
337
337
  app.get("*", async (c, next) => {
338
- // Skip API and WebSocket routes - let them pass through to actual handlers
339
- if (c.req.path.startsWith("/api")) {
338
+ // Skip API and WebSocket routes - let them pass through to actual handlers.
339
+ // The trailing slash matters: `/api-docs` is a frontend route and must hit
340
+ // the SPA fallback below, while `/api/...` and `/rest/...` go to backend
341
+ // handlers (oRPC RPC + OpenAPI REST mounts).
342
+ const apiPath =
343
+ c.req.path.startsWith("/api/") || c.req.path.startsWith("/rest/");
344
+ if (apiPath) {
340
345
  return next();
341
346
  }
342
347
 
@@ -10,6 +10,7 @@ import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4";
10
10
  import type { AnyContractRouter } from "@orpc/contract";
11
11
  import type { PluginManager } from "./plugin-manager";
12
12
  import type { AuthService } from "@checkstack/backend-api";
13
+ import type { AccessRule } from "@checkstack/common";
13
14
 
14
15
  /**
15
16
  * Check if a user has a specific access rule.
@@ -25,40 +26,57 @@ function hasAccess(
25
26
  );
26
27
  }
27
28
 
29
+ /**
30
+ * Shape of the metadata we surface in the OpenAPI spec as `x-orpc-meta`.
31
+ * `accessRules` are the fully-qualified access rule IDs (e.g.
32
+ * `"catalog.system.read"`), flattened from each procedure's `access`
33
+ * AccessRule[] so doc consumers don't need to know the AccessRule shape.
34
+ */
35
+ interface ExposedProcedureMeta {
36
+ userType?: string;
37
+ accessRules?: string[];
38
+ }
39
+
28
40
  /**
29
41
  * Extract procedure metadata from a contract using oRPC internal structure.
42
+ * Returns the raw `meta` block stored on the contract procedure builder.
30
43
  */
31
- function extractProcedureMetadata(
44
+ function extractRawProcedureMeta(
32
45
  contract: unknown
33
- ): { userType?: string; accessRules?: string[] } | undefined {
46
+ ): { userType?: string; access?: AccessRule[] } | undefined {
34
47
  const orpcData = (contract as Record<string, unknown>)?.["~orpc"] as
35
- | { meta?: { userType?: string; accessRules?: string[] } }
48
+ | { meta?: { userType?: string; access?: AccessRule[] } }
36
49
  | undefined;
37
50
  return orpcData?.meta;
38
51
  }
39
52
 
40
53
  /**
41
- * Build a lookup map of operationId -> metadata from all contracts.
42
- * operationId format: "pluginId.procedureName"
54
+ * Build a lookup map of operationId -> exposed metadata from all contracts.
55
+ * operationId format: "pluginId.procedureName".
56
+ *
57
+ * The procedure metadata stores `access` as AccessRule[]; we flatten it to
58
+ * `accessRules: string[]` of qualified IDs (`{pluginId}.{ruleId}`) so the
59
+ * OpenAPI consumer (API docs UI, third-party clients) gets a plain list.
43
60
  */
44
61
  function buildMetadataLookup(
45
62
  contracts: Map<string, AnyContractRouter>
46
- ): Map<string, { userType?: string; accessRules?: string[] }> {
47
- const lookup = new Map<
48
- string,
49
- { userType?: string; accessRules?: string[] }
50
- >();
63
+ ): Map<string, ExposedProcedureMeta> {
64
+ const lookup = new Map<string, ExposedProcedureMeta>();
51
65
 
52
66
  for (const [pluginId, contract] of contracts) {
53
- // Contract is an object with procedure names as keys
54
67
  for (const [procedureName, procedure] of Object.entries(
55
68
  contract as Record<string, unknown>
56
69
  )) {
57
- const meta = extractProcedureMetadata(procedure);
58
- if (meta) {
59
- const operationId = `${pluginId}.${procedureName}`;
60
- lookup.set(operationId, meta);
61
- }
70
+ const raw = extractRawProcedureMeta(procedure);
71
+ if (!raw) continue;
72
+
73
+ const accessRules = raw.access?.map((rule) => `${pluginId}.${rule.id}`);
74
+
75
+ const operationId = `${pluginId}.${procedureName}`;
76
+ lookup.set(operationId, {
77
+ userType: raw.userType,
78
+ ...(accessRules && accessRules.length > 0 ? { accessRules } : {}),
79
+ });
62
80
  }
63
81
  }
64
82
 
@@ -107,13 +125,14 @@ export async function generateOpenApiSpec({
107
125
  >;
108
126
  };
109
127
 
110
- // Post-process: Add x-orpc-meta to each operation and prefix paths with /api
128
+ // Post-process: Add x-orpc-meta to each operation and prefix paths with /rest.
129
+ // The REST handler is mounted at /rest/:pluginId/* (see api-router.ts);
130
+ // /api/:pluginId/* serves oRPC's native wire protocol, not REST.
111
131
  if (spec.paths) {
112
132
  const prefixedPaths: typeof spec.paths = {};
113
133
 
114
134
  for (const [path, methods] of Object.entries(spec.paths)) {
115
- // Prefix path with /api
116
- const prefixedPath = `/api${path.startsWith("/") ? path : `/${path}`}`;
135
+ const prefixedPath = `/rest${path.startsWith("/") ? path : `/${path}`}`;
117
136
  prefixedPaths[prefixedPath] = methods;
118
137
 
119
138
  // Add metadata to each operation