Skip to content

Commit 4fa7d9f

Browse files
committed
feat(service-settings): judge map values at the save and env doors
One shared judgement for both doors: the value must be an object of keyed rows, each key admitted by the key column's option source and each cell of its column's kind. Refusals name the entry and the expected form. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2fBJ6xsLWJsnNJGMMx
1 parent e5750d8 commit 4fa7d9f

5 files changed

Lines changed: 817 additions & 175 deletions

File tree

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Test scaffolding: a settings door over the real `ObjectQL` engine, the real
5+
* platform setting objects and the real `PUT /api/settings/:namespace` route,
6+
* with a Map driver underneath. Shared by the door suites that judge a value
7+
* shape end to end (#31241 `json`, #30208 `map`).
8+
*/
9+
10+
import { vi } from 'vitest';
11+
import { ObjectQL } from '@objectstack/objectql';
12+
import { SysPlatformSetting, SysSecret, SysSetting } from '@objectstack/platform-objects/system';
13+
import type { IHttpServer, IHttpRequest, IHttpResponse, RouteHandler } from '@objectstack/spec/contracts';
14+
import type { SettingsManifest } from '@objectstack/spec/system';
15+
import { SettingsService } from '../settings-service.js';
16+
import { SettingsServicePlugin, wrapEngineAsSettingsEngine } from '../settings-service-plugin.js';
17+
import { withEngineRegistry } from './settings-organization.testkit.js';
18+
import { LocalCryptoProvider } from '../local-crypto-provider.js';
19+
import { registerSettingsRoutes } from '../settings-routes.js';
20+
21+
const OWNER_PACKAGE = 'com.objectstack.test.settings-door';
22+
23+
/** A driver over plain Maps — the verbs the settings path reaches through `ObjectQL`. */
24+
export function makeMemoryDriver() {
25+
const store = new Map<string, Map<string, Record<string, unknown>>>();
26+
let nextId = 0;
27+
const copy = (r: Record<string, unknown>) => ({ ...r });
28+
const rowsOf = (object: string) => {
29+
let s = store.get(object);
30+
if (!s) { s = new Map(); store.set(object, s); }
31+
return s;
32+
};
33+
// `$or` is the one combinator the settings reads emit; anything else refuses,
34+
// so a predicate this double cannot express never reads as "no such row".
35+
const matches = (row: Record<string, unknown>, where: any): boolean => {
36+
if (!where || typeof where !== 'object') return true;
37+
return Object.entries(where).every(([k, v]) => {
38+
if (k === '$or') return (v as any[]).some((b) => matches(row, b));
39+
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
40+
return (row[k] ?? null) === (v ?? null);
41+
});
42+
};
43+
const driver: any = {
44+
name: 'memory', version: '0.0.0', supports: {} as any,
45+
async connect() {}, async disconnect() {}, async checkHealth() { return true; },
46+
async execute() { return null; },
47+
async find(object: string, ast: any) {
48+
// The caller's bound by PRESENCE, after the filter and before the copy.
49+
const hits = [...rowsOf(object).values()].filter((r) => matches(r, ast?.where));
50+
const page = typeof ast?.limit === 'number' ? hits.slice(0, ast.limit) : hits;
51+
return page.map(copy);
52+
},
53+
async findOne(object: string, ast: any) {
54+
for (const r of rowsOf(object).values()) if (matches(r, ast?.where)) return copy(r);
55+
return null;
56+
},
57+
async create(object: string, data: Record<string, unknown>) {
58+
nextId += 1;
59+
const id = (data.id as string) ?? `row_${nextId}`;
60+
const row = { ...data, id };
61+
rowsOf(object).set(id, row);
62+
return copy(row);
63+
},
64+
async update(object: string, id: string, data: Record<string, unknown>) {
65+
const s = rowsOf(object);
66+
const cur = s.get(id);
67+
if (!cur) return null;
68+
const next = { ...cur, ...data, id };
69+
s.set(id, next);
70+
return copy(next);
71+
},
72+
async upsert(object: string, data: Record<string, unknown>) {
73+
const id = data.id as string | undefined;
74+
return id && rowsOf(object).has(id) ? this.update(object, id, data) : this.create(object, data);
75+
},
76+
async delete(object: string, id: string) { return rowsOf(object).delete(id); },
77+
async count(object: string, ast: any) { return (await this.find(object, ast)).length; },
78+
async bulkCreate(object: string, rows: Record<string, unknown>[]) {
79+
return Promise.all(rows.map((r) => this.create(object, r)));
80+
},
81+
async bulkUpdate() { return []; },
82+
async bulkDelete() {},
83+
async updateMany(object: string, ast: any, data: Record<string, unknown>) {
84+
const rows = await this.find(object, ast);
85+
const s = rowsOf(object);
86+
for (const r of rows) s.set(r.id as string, { ...s.get(r.id as string), ...data, id: r.id });
87+
return rows.length;
88+
},
89+
async deleteMany(object: string, ast: any) {
90+
const rows = await this.find(object, ast);
91+
for (const r of rows) rowsOf(object).delete(r.id as string);
92+
return rows.length;
93+
},
94+
async syncSchema() {}, async dropTable() {},
95+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
96+
async commit() {}, async rollback() {},
97+
};
98+
return { driver, rowsOf };
99+
}
100+
101+
export class MockHttp implements IHttpServer {
102+
routes = new Map<string, RouteHandler>();
103+
private add(method: string, path: string, h: RouteHandler) { this.routes.set(`${method} ${path}`, h); }
104+
get(p: string, h: RouteHandler) { this.add('GET', p, h); return this as any; }
105+
post(p: string, h: RouteHandler) { this.add('POST', p, h); return this as any; }
106+
put(p: string, h: RouteHandler) { this.add('PUT', p, h); return this as any; }
107+
delete(p: string, h: RouteHandler) { this.add('DELETE', p, h); return this as any; }
108+
patch(p: string, h: RouteHandler) { this.add('PATCH', p, h); return this as any; }
109+
use() { return this as any; }
110+
listen() { return Promise.resolve(); }
111+
close() { return Promise.resolve(); }
112+
getInstance() { return null; }
113+
}
114+
115+
/**
116+
* The pieces the running server binds: the real `ObjectQL` engine over a Map
117+
* driver, the platform setting objects, a `SettingsService` with `manifest`
118+
* registered, and the settings routes. `before` runs on the service before the
119+
* manifest registers (an option source, as a plugin registers one).
120+
*/
121+
export async function bootSettingsDoor(
122+
manifest: SettingsManifest,
123+
options: { before?: (svc: SettingsService) => void } = {},
124+
) {
125+
const engine = new ObjectQL();
126+
const { driver, rowsOf } = makeMemoryDriver();
127+
engine.registerDriver(driver, true);
128+
await engine.init();
129+
for (const o of [SysSetting, SysPlatformSetting, SysSecret]) {
130+
engine.registry.registerObject(o as any, OWNER_PACKAGE);
131+
}
132+
const svc = new SettingsService({
133+
env: {},
134+
engine: withEngineRegistry(wrapEngineAsSettingsEngine(engine as any), engine),
135+
cryptoProvider: new LocalCryptoProvider(),
136+
secretStore: (new SettingsServicePlugin() as any).buildSecretStore(engine),
137+
});
138+
options.before?.(svc);
139+
svc.registerManifest(manifest);
140+
const http = new MockHttp();
141+
registerSettingsRoutes(http, svc, {
142+
contextFromRequest: () => ({ enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' }),
143+
});
144+
const put = http.routes.get('PUT /api/settings/:namespace')!;
145+
const namespace = manifest.namespace;
146+
/** One `PUT /api/settings/:namespace` with `body`, as the console sends it (a flat patch). */
147+
const save = async (body: Record<string, unknown>) => {
148+
const req: IHttpRequest = { params: { namespace }, query: {}, body, headers: {}, method: 'PUT', path: '/' };
149+
const state: { status: number; body?: any } = { status: 200 };
150+
const res: IHttpResponse = {
151+
json: vi.fn((d) => { state.body = d; }) as any,
152+
send: vi.fn() as any,
153+
status: vi.fn((c: number) => { state.status = c; return res; }) as any,
154+
header: vi.fn(() => res) as any,
155+
};
156+
await put(req, res);
157+
return state;
158+
};
159+
const stored = (key: string) =>
160+
[...rowsOf('sys_platform_setting').values()].find((r) => r.namespace === namespace && r.key === key);
161+
const seed = (row: Record<string, unknown>) =>
162+
rowsOf('sys_platform_setting').set(String(row.id), { encrypted: false, locked: false, value_enc: null, ...row });
163+
return { svc, save, stored, seed };
164+
}
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { LIFECYCLE_DURATION_REGEX } from '@objectstack/spec/data';
4+
5+
/**
6+
* The shape judgement of a `map` specifier's value (#30208; ADR-0007 as amended
7+
* 2026-11-08): ONE judgement, shared by both doors that produce an effective
8+
* value, the save door (`SettingsService.validatePatch`) and the env door
9+
* (`SettingsService.effectiveEnvOverride`), on the precedent of the option and
10+
* pattern families (#5204, #6580). A comparison living on one door only is how
11+
* those two defects happened.
12+
*
13+
* A `map` stores keyed rows. With one value column the entry IS the value
14+
* (`{ "sys_audit_log": 1000000 }`); with several it is an object of the
15+
* declared columns (`{ "sys_job_run": { "maxAge": "1y" } }`). Before this type,
16+
* the three lifecycle maps were `json` keys that neither door judged: a misspelt
17+
* object, `"1e6"` or `30 days` was stored, answered "saved", and silently did
18+
* nothing.
19+
*/
20+
21+
/** The value kinds a column may declare — the spec's closed `kind` set. */
22+
export type MapColumnKind = 'duration' | 'positive_integer';
23+
24+
const COLUMN_KINDS: ReadonlySet<string> = new Set<MapColumnKind>(['duration', 'positive_integer']);
25+
26+
/** One declared value column, as the doors judge it. */
27+
export interface MapColumn {
28+
name: string;
29+
kind: MapColumnKind;
30+
}
31+
32+
/** What a `map` specifier declares that a value is judged against. */
33+
export interface DeclaredMapShape {
34+
columns: ReadonlyArray<MapColumn>;
35+
}
36+
37+
/**
38+
* The shape a `map` specifier declares, or `null` when it declares none this
39+
* side can judge. `registerManifest` takes manifests as given (no Zod pass), so
40+
* a hand-built manifest's malformed columns are dropped rather than trusted, and
41+
* a map left with no column records nothing to enforce: the same leniency the
42+
* option table and the pattern take, never a reject-everything hole.
43+
*/
44+
export function declaredMapShape(spec: { type?: unknown; columns?: unknown }): DeclaredMapShape | null {
45+
if (spec.type !== 'map' || !Array.isArray(spec.columns)) return null;
46+
const columns: MapColumn[] = [];
47+
for (const col of spec.columns) {
48+
if (!col || typeof col !== 'object') continue;
49+
const { name, kind } = col as { name?: unknown; kind?: unknown };
50+
if (typeof name !== 'string' || name === '' || typeof kind !== 'string' || !COLUMN_KINDS.has(kind)) continue;
51+
columns.push({ name, kind: kind as MapColumnKind });
52+
}
53+
return columns.length > 0 ? { columns } : null;
54+
}
55+
56+
/** Why a value is not the map its specifier declares — see {@link firstMapShapeMiss}. */
57+
export type MapShapeMiss =
58+
/** The value is not an object of keyed rows at all (JSON text, a scalar, an array). */
59+
| { kind: 'not_a_map'; shape: string }
60+
/** An entry's key is not one the key column admits. */
61+
| { kind: 'key'; entry: string }
62+
/** Several columns: an entry is not an object, or names none of the columns. */
63+
| { kind: 'not_an_entry'; entry: string; shape: string }
64+
/** Several columns: an entry carries a property no column declares. */
65+
| { kind: 'unknown_column'; entry: string; column: string }
66+
/** A cell's value is not of its column's kind. */
67+
| { kind: 'cell'; entry: string; column: MapColumn; shape: string };
68+
69+
/**
70+
* The first way `value` is not the map `shape` declares, or `null` when it is.
71+
*
72+
* `null` / `undefined` pass: that is a clear, which falls back to the default.
73+
* Entries are judged in their own order, each key before its value, so the
74+
* verdict names the first entry a reader would trip over. `admitsKey` is the key
75+
* column's domain (the option source the settings service registers for the
76+
* key); absent, every key is admitted.
77+
*
78+
* A cell is judged as stored, never coerced: the one reader of these maps
79+
* (`LifecycleService.loadGovernance`) applies a quota only when it is a number
80+
* and a window only when it parses as a duration, so `"1000"` and `" 7y"` are
81+
* exactly the values that are stored and then do nothing.
82+
*/
83+
export function firstMapShapeMiss(
84+
shape: DeclaredMapShape,
85+
value: unknown,
86+
admitsKey?: (key: string) => boolean,
87+
): MapShapeMiss | null {
88+
if (value === null || typeof value === 'undefined') return null;
89+
if (!isPlainRecord(value)) return { kind: 'not_a_map', shape: shapeOf(value) };
90+
const single = shape.columns.length === 1;
91+
for (const [entry, cell] of Object.entries(value)) {
92+
if (admitsKey && !admitsKey(entry)) return { kind: 'key', entry };
93+
if (single) {
94+
const column = shape.columns[0];
95+
if (!cellFits(column.kind, cell)) return { kind: 'cell', entry, column, shape: shapeOf(cell) };
96+
continue;
97+
}
98+
if (!isPlainRecord(cell)) return { kind: 'not_an_entry', entry, shape: shapeOf(cell) };
99+
const declared = new Map(shape.columns.map((c) => [c.name, c]));
100+
let named = 0;
101+
for (const [prop, v] of Object.entries(cell)) {
102+
const column = declared.get(prop);
103+
if (!column) return { kind: 'unknown_column', entry, column: prop };
104+
// An absent cell (`null` / `undefined`) is a column left empty.
105+
if (v === null || typeof v === 'undefined') continue;
106+
if (!cellFits(column.kind, v)) return { kind: 'cell', entry, column, shape: shapeOf(v) };
107+
named += 1;
108+
}
109+
if (named === 0) return { kind: 'not_an_entry', entry, shape: 'an object that names no column' };
110+
}
111+
return null;
112+
}
113+
114+
function cellFits(kind: MapColumnKind, v: unknown): boolean {
115+
if (kind === 'duration') return typeof v === 'string' && LIFECYCLE_DURATION_REGEX.test(v);
116+
return typeof v === 'number' && Number.isInteger(v) && v > 0;
117+
}
118+
119+
/** What a column of this kind takes, as a sentence fragment with an example. */
120+
export function columnKindPhrase(kind: MapColumnKind): string {
121+
return kind === 'duration'
122+
? 'a duration such as 7y (a whole number followed by h, d, w or y)'
123+
: 'a whole number greater than 0, such as 1000000';
124+
}
125+
126+
/**
127+
* The one sentence a {@link MapShapeMiss} is told in, at both doors. It names
128+
* the entry (and the column), and the form expected. A string value is
129+
* described by its length (`a string of 7 characters`), never printed, as the
130+
* format family does (#24882); a whole number is named, since it is the
131+
* number an operator typed and carries nothing secret.
132+
*/
133+
export function mapMissSentence(
134+
label: string,
135+
shape: DeclaredMapShape,
136+
miss: MapShapeMiss,
137+
allowedKeys?: readonly string[],
138+
): string {
139+
const columnNames = shape.columns.map((c) => c.name).join(', ');
140+
switch (miss.kind) {
141+
case 'not_a_map':
142+
return `${label} must be an object of keyed rows, such as ${exampleOf(shape, allowedKeys)}, not ${miss.shape}. ` +
143+
'Send the parsed value, not its JSON text.';
144+
case 'key':
145+
return `${label}: '${miss.entry}' is not a key this setting admits.` +
146+
(allowedKeys && allowedKeys.length > 0 ? ` Allowed: ${allowedKeys.join(', ')}.` : '');
147+
case 'not_an_entry':
148+
return `${label}: '${miss.entry}' must be an object with at least one of ${columnNames}, ` +
149+
`such as ${entryExampleOf(shape)}, not ${miss.shape}.`;
150+
case 'unknown_column':
151+
return `${label}: '${miss.entry}' has a property '${miss.column}' this setting does not declare. ` +
152+
`Allowed: ${columnNames}.`;
153+
case 'cell': {
154+
const where = shape.columns.length === 1 ? `'${miss.entry}'` : `'${miss.entry}'.${miss.column.name}`;
155+
return `${label}: ${where} must be ${columnKindPhrase(miss.column.kind)}, not ${miss.shape}.`;
156+
}
157+
}
158+
}
159+
160+
function exampleCell(kind: MapColumnKind): string {
161+
return kind === 'duration' ? '"7y"' : '1000000';
162+
}
163+
164+
function entryExampleOf(shape: DeclaredMapShape): string {
165+
const first = shape.columns[0];
166+
return `{ "${first.name}": ${exampleCell(first.kind)} }`;
167+
}
168+
169+
function exampleOf(shape: DeclaredMapShape, allowedKeys?: readonly string[]): string {
170+
const key = allowedKeys?.[0] ?? 'key';
171+
const cell = shape.columns.length === 1 ? exampleCell(shape.columns[0].kind) : entryExampleOf(shape);
172+
return `{ "${key}": ${cell} }`;
173+
}
174+
175+
function isPlainRecord(v: unknown): v is Record<string, unknown> {
176+
if (!v || typeof v !== 'object' || Array.isArray(v)) return false;
177+
const proto = Object.getPrototypeOf(v);
178+
return proto === Object.prototype || proto === null;
179+
}
180+
181+
/** A value's kind and, for a string, its length — never its content. */
182+
export function shapeOf(v: unknown): string {
183+
if (v === null) return 'null';
184+
if (Array.isArray(v)) return 'an array';
185+
if (typeof v === 'string') return `a string of ${v.length} character${v.length === 1 ? '' : 's'}`;
186+
if (typeof v === 'number') return Number.isInteger(v) ? `the whole number ${v}` : 'a number with a fraction';
187+
if (typeof v === 'object') return isPlainRecord(v) ? 'an object' : 'a non-plain object';
188+
return `a ${typeof v}`;
189+
}

0 commit comments

Comments
 (0)