|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `metadata.prefix` is honoured by the SDK, not restated by it (#16675). |
| 5 | + * |
| 6 | + * THE CONTRACT. `metadata.prefix` is a live `RestServerConfig` key, the exact |
| 7 | + * sibling of the `crud.dataPrefix` #14879 fixed: REST mounts every metadata |
| 8 | + * route under `metaPath = ${basePath}${metadata.prefix}` and the discovery |
| 9 | + * handler advertises the same value as |
| 10 | + * `routes.metadata = ${realBase}${metadata.prefix}`. Three surfaces describe |
| 11 | + * one set of paths — the mounts, the discovery document, and this SDK — so the |
| 12 | + * SDK must READ the value rather than restate it. |
| 13 | + * |
| 14 | + * WHAT WAS WRONG. The SDK's scoped surface restated `/meta` as a literal in |
| 15 | + * all SIX of its metadata methods (`getTypes` / `getItems` / `getItem` / |
| 16 | + * `saveItem` / `deleteItem` / `getHistory`), so on a deployment that moved the |
| 17 | + * prefix it called paths the server does not mount. The unscoped twin of each |
| 18 | + * of those methods was already correct — it builds |
| 19 | + * `${baseUrl}${getRoute('metadata')}` — so ONE SDK disagreed with itself: the |
| 20 | + * unscoped half read the advertised value while the scoped half guessed. |
| 21 | + * |
| 22 | + * WHY THE FIXTURE CREATES THE CONDITION. Measured on `origin/main`, no in-repo |
| 23 | + * caller sets a non-default `metadata.prefix`, so no existing fixture |
| 24 | + * exercises this and nothing in the tree is broken today; the exposure is |
| 25 | + * external deployments. So this suite BOOTS a server on a non-default prefix |
| 26 | + * rather than looking for one. |
| 27 | + * |
| 28 | + * WHY A LIVE SERVER AND A RECORDED URL. A mock that answers 200 to whatever it |
| 29 | + * is asked cannot tell a mounted path from an unmounted one — it would go |
| 30 | + * green against the very bug this pins. So the server is real, and the suite |
| 31 | + * asserts BOTH halves of the claim: that the URL the client puts on the wire |
| 32 | + * is the one the server actually mounts, and (`serves nothing at /meta`) that |
| 33 | + * the old hard-coded path is genuinely dead on this deployment, which is what |
| 34 | + * makes the first assertion mean something. |
| 35 | + * |
| 36 | + * ⚠️ EVERY URL ASSERTION IS FULL-STRING EQUALITY, NEVER `toContain`. The |
| 37 | + * realistic non-default prefix `/metadata` CONTAINS the conventional `/meta` |
| 38 | + * as a prefix, so `expect(url).not.toContain('/meta')` would fail on the |
| 39 | + * CORRECT url and `toContain('/meta')` would pass on it — a substring probe |
| 40 | + * over this pair of values answers noise. Equality is immune to that, and it |
| 41 | + * is also what the negative control below needs to mean anything. |
| 42 | + * |
| 43 | + * THE NEGATIVE CONTROL (the acceptance criterion of #16675). The same drive |
| 44 | + * runs against a default-prefix server built by the same helper, and against a |
| 45 | + * client that never connected at all. It is what distinguishes "the SDK |
| 46 | + * follows the advertised prefix" from "the SDK now always rebuilds its paths |
| 47 | + * out of discovery": a default deployment must be reached at exactly the URLs |
| 48 | + * it was reached at before, byte for byte, and an unconnected client must |
| 49 | + * still produce them WITHOUT putting a discovery round-trip on the wire. An |
| 50 | + * implementation that always derives from discovery passes the non-default |
| 51 | + * case above while making every default deployment slower and more fragile — |
| 52 | + * these two describes are the only thing that catches it. |
| 53 | + */ |
| 54 | + |
| 55 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 56 | +import { LiteKernel } from '@objectstack/core'; |
| 57 | +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; |
| 58 | +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; |
| 59 | +import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; |
| 60 | +import { createRestApiPlugin } from '@objectstack/runtime'; |
| 61 | +import { ObjectStackClient } from './index'; |
| 62 | +import type { IHttpServer } from '@objectstack/spec/contracts'; |
| 63 | + |
| 64 | +const ENV_ID = 'proj-alpha'; |
| 65 | +/** |
| 66 | + * Deliberately the value `packages/spec`'s own `MetadataEndpointsConfigSchema` |
| 67 | + * test uses for "custom prefix" — and deliberately one that has the |
| 68 | + * conventional `/meta` as a string prefix, so the substring trap above is |
| 69 | + * exercised rather than side-stepped. |
| 70 | + */ |
| 71 | +const CUSTOM_PREFIX = '/metadata'; |
| 72 | + |
| 73 | +interface Fixture { |
| 74 | + baseUrl: string; |
| 75 | + kernel: LiteKernel; |
| 76 | +} |
| 77 | + |
| 78 | +/** |
| 79 | + * One boot recipe, two prefixes — so the non-default case and the control |
| 80 | + * differ in exactly the key under test and nothing else. |
| 81 | + */ |
| 82 | +async function bootServer(metadataPrefix?: string): Promise<Fixture> { |
| 83 | + const kernel = new LiteKernel(); |
| 84 | + kernel.use(new ObjectQLPlugin()); |
| 85 | + // Same reason as the sibling scoping suite (#3963): the anonymous-deny |
| 86 | + // gate is unconditional, so a live-server client suite needs a session. |
| 87 | + kernel.use({ |
| 88 | + metadata: { name: 'test-auth', version: '1.0.0' }, |
| 89 | + async init(ctx: any) { |
| 90 | + ctx.registerService('auth', { |
| 91 | + api: { getSession: async () => ({ user: { id: 'test-user' } }) }, |
| 92 | + }); |
| 93 | + }, |
| 94 | + } as any); |
| 95 | + |
| 96 | + const honoPlugin = new HonoServerPlugin({ port: 0 }); |
| 97 | + kernel.use(honoPlugin); |
| 98 | + |
| 99 | + kernel.use( |
| 100 | + createRestApiPlugin({ |
| 101 | + api: { |
| 102 | + api: { |
| 103 | + // Routing test, no auth stack mounted (ADR-0056 D2). |
| 104 | + requireAuth: false, |
| 105 | + enableProjectScoping: true, |
| 106 | + projectResolution: 'auto', |
| 107 | + } as any, |
| 108 | + // The key under test. Omitted entirely for the control, so the |
| 109 | + // control runs the schema's own `.default('/meta')` rather |
| 110 | + // than a second literal written here. |
| 111 | + ...(metadataPrefix ? { metadata: { prefix: metadataPrefix } as any } : {}), |
| 112 | + }, |
| 113 | + }), |
| 114 | + ); |
| 115 | + |
| 116 | + await kernel.bootstrap(); |
| 117 | + |
| 118 | + const ql = kernel.getService<ObjectQL>('objectql'); |
| 119 | + ql.registerDriver(new SqliteWasmDriver({ filename: ':memory:' }) as never, true); |
| 120 | + ql.registerObject({ |
| 121 | + name: 'task', |
| 122 | + label: 'Task', |
| 123 | + fields: { title: { type: 'text', label: 'Title' } }, |
| 124 | + }); |
| 125 | + // Registered after bootstrap, so nothing has issued the DDL yet (#4065). |
| 126 | + await ql.syncObjectSchema('task'); |
| 127 | + |
| 128 | + const httpServer = kernel.getService<IHttpServer>('http.server'); |
| 129 | + const port = httpServer.getPort!(); |
| 130 | + return { baseUrl: `http://localhost:${port}`, kernel }; |
| 131 | +} |
| 132 | + |
| 133 | +async function shutdown(fixture: Fixture | undefined): Promise<void> { |
| 134 | + if (!fixture?.kernel) return; |
| 135 | + await Promise.race([ |
| 136 | + fixture.kernel.shutdown(), |
| 137 | + new Promise<void>((resolve) => setTimeout(resolve, 10_000)), |
| 138 | + ]); |
| 139 | +} |
| 140 | + |
| 141 | +/** |
| 142 | + * A client whose every request URL is recorded. The recorder DELEGATES to the |
| 143 | + * real fetch, so the recorded URL and the server's real answer are the same |
| 144 | + * exchange — the assertion cannot pass on a URL that was never served. |
| 145 | + */ |
| 146 | +function recordingClient(baseUrl: string): { client: ObjectStackClient; urls: string[] } { |
| 147 | + const urls: string[] = []; |
| 148 | + const client = new ObjectStackClient({ |
| 149 | + baseUrl, |
| 150 | + fetch: (input: RequestInfo | URL, init?: RequestInit) => { |
| 151 | + urls.push(typeof input === 'string' ? input : String(input)); |
| 152 | + return globalThis.fetch(input as any, init); |
| 153 | + }, |
| 154 | + } as any); |
| 155 | + return { client, urls }; |
| 156 | +} |
| 157 | + |
| 158 | +/** |
| 159 | + * Drive all SIX scoped metadata methods and return the URL each one put on the |
| 160 | + * wire, in call order. The writes are allowed to reject — a 404 on an |
| 161 | + * unmounted path and a refusal from a live write door are both rejections, and |
| 162 | + * this suite is about the URL, not the answer. Recording happens before the |
| 163 | + * request is made, so a rejected call still contributes its URL. |
| 164 | + */ |
| 165 | +async function driveAllSix(client: ObjectStackClient, urls: string[]): Promise<string[]> { |
| 166 | + const scoped = client.environment(ENV_ID); |
| 167 | + const before = urls.length; |
| 168 | + const swallow = (p: Promise<unknown>) => p.then(() => undefined, () => undefined); |
| 169 | + await swallow(scoped.meta.getTypes()); |
| 170 | + await swallow(scoped.meta.getItems('object')); |
| 171 | + await swallow(scoped.meta.getItem('object', 'task')); |
| 172 | + await swallow(scoped.meta.saveItem('object', 'task', { name: 'task', label: 'Task' })); |
| 173 | + await swallow(scoped.meta.deleteItem('object', 'task')); |
| 174 | + await swallow(scoped.meta.getHistory('object', 'task')); |
| 175 | + return urls.slice(before); |
| 176 | +} |
| 177 | + |
| 178 | +/** The six URLs a deployment on `prefix` must be called at. */ |
| 179 | +function expectedSix(baseUrl: string, prefix: string): string[] { |
| 180 | + const root = `${baseUrl}/api/v1/environments/${ENV_ID}${prefix}`; |
| 181 | + return [ |
| 182 | + `${root}`, |
| 183 | + `${root}/object`, |
| 184 | + `${root}/object/task`, |
| 185 | + `${root}/object/task`, |
| 186 | + `${root}/object/task`, |
| 187 | + `${root}/object/task/history`, |
| 188 | + ]; |
| 189 | +} |
| 190 | + |
| 191 | +describe('SDK honours metadata.prefix (#16675)', () => { |
| 192 | + describe(`non-default prefix (${CUSTOM_PREFIX})`, () => { |
| 193 | + let fx: Fixture; |
| 194 | + |
| 195 | + beforeAll(async () => { fx = await bootServer(CUSTOM_PREFIX); }, 30_000); |
| 196 | + afterAll(async () => { await shutdown(fx); }, 30_000); |
| 197 | + |
| 198 | + it('mounts scoped metadata under the configured prefix, and serves nothing at /meta', async () => { |
| 199 | + const mounted = await fetch(`${fx.baseUrl}/api/v1/environments/${ENV_ID}${CUSTOM_PREFIX}`); |
| 200 | + expect(mounted.status).toBe(200); |
| 201 | + |
| 202 | + // The half that makes this fixture worth anything: the path the |
| 203 | + // SDK used to hard-code is genuinely not mounted here. |
| 204 | + const hardCoded = await fetch(`${fx.baseUrl}/api/v1/environments/${ENV_ID}/meta`); |
| 205 | + expect(hardCoded.status).toBe(404); |
| 206 | + }); |
| 207 | + |
| 208 | + it('advertises the prefix on the discovery document', async () => { |
| 209 | + const res = await fetch(`${fx.baseUrl}/api/v1/discovery`); |
| 210 | + expect(res.status).toBe(200); |
| 211 | + const body = await res.json(); |
| 212 | + const routes = (body?.data ?? body)?.routes; |
| 213 | + expect(routes?.metadata).toBe(`/api/v1${CUSTOM_PREFIX}`); |
| 214 | + }); |
| 215 | + |
| 216 | + it('all six scoped meta methods call the mounted path, not /meta', async () => { |
| 217 | + const { client, urls } = recordingClient(fx.baseUrl); |
| 218 | + await client.connect(); |
| 219 | + |
| 220 | + const called = await driveAllSix(client, urls); |
| 221 | + expect(called).toEqual(expectedSix(fx.baseUrl, CUSTOM_PREFIX)); |
| 222 | + }); |
| 223 | + }); |
| 224 | + |
| 225 | + describe('negative control — default prefix, byte-identical URLs', () => { |
| 226 | + let fx: Fixture; |
| 227 | + |
| 228 | + beforeAll(async () => { fx = await bootServer(); }, 30_000); |
| 229 | + afterAll(async () => { await shutdown(fx); }, 30_000); |
| 230 | + |
| 231 | + it('advertises /api/v1/meta', async () => { |
| 232 | + const res = await fetch(`${fx.baseUrl}/api/v1/discovery`); |
| 233 | + const body = await res.json(); |
| 234 | + const routes = (body?.data ?? body)?.routes; |
| 235 | + expect(routes?.metadata).toBe('/api/v1/meta'); |
| 236 | + }); |
| 237 | + |
| 238 | + it('a CONNECTED client still calls the six /meta URLs, byte for byte', async () => { |
| 239 | + const { client, urls } = recordingClient(fx.baseUrl); |
| 240 | + await client.connect(); |
| 241 | + |
| 242 | + const called = await driveAllSix(client, urls); |
| 243 | + expect(called).toEqual(expectedSix(fx.baseUrl, '/meta')); |
| 244 | + }); |
| 245 | + |
| 246 | + it('an UNCONNECTED client calls the same six URLs and puts NO discovery request on the wire', async () => { |
| 247 | + // No `connect()`, so there is no advertised document to read. The |
| 248 | + // derivation must decline to the conventional literal rather than |
| 249 | + // reach for one -- this is the leg that fails on an |
| 250 | + // "always rebuild the path out of discovery" implementation, which |
| 251 | + // would make every default deployment pay a round-trip it does not |
| 252 | + // pay today. |
| 253 | + const { client, urls } = recordingClient(fx.baseUrl); |
| 254 | + |
| 255 | + const called = await driveAllSix(client, urls); |
| 256 | + expect(called).toEqual(expectedSix(fx.baseUrl, '/meta')); |
| 257 | + |
| 258 | + // Exactly six requests, and none of them is a discovery read. |
| 259 | + expect(urls).toHaveLength(6); |
| 260 | + expect(urls.filter((u) => u.includes('/discovery'))).toEqual([]); |
| 261 | + }); |
| 262 | + }); |
| 263 | +}); |
0 commit comments