diff --git a/changelog.d/settings-file-and-resolver.md b/changelog.d/settings-file-and-resolver.md new file mode 100644 index 000000000..3fd498748 --- /dev/null +++ b/changelog.d/settings-file-and-resolver.md @@ -0,0 +1,11 @@ +- **TypeScript: a settings file for platform, product, size and secret store (ADR-0070, calls 5 + and 13).** `.metaobjects/settings.json` sits beside `config.json`, and only TypeScript reads + it, so no port's config reader changes. It carries `targets`, `platforms`, + `resourceDefaults` (keyed by platform, then resource kind), `purposes`, `environments` and + `secrets.stores`, and may `extends` a shared estate file (a relative path or a package), + merged key by key with the nearer file winning. `@metaobjectsdev/sdk` adds `loadSettings` and + a resolver (`resolveTarget`, `resolveResource`, `resolveApp`, `resolveGeneratedStore`, + `resolveAdoptedStore`) that answers which target, product, size and store a node gets and + which layer and file each value came from. Experimental; no generator reads it yet, and a + project with no settings file sees no change. `metamodelVersion` does not move. + See `docs/features/settings.md`. diff --git a/docs/README.md b/docs/README.md index 0182dbc44..6645d5fb5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -46,6 +46,7 @@ docs/ │ ├── image-upload.md # view.image form control (TS-web) │ ├── metadata-sources.md # where metadata comes from: sources, scope, discovery │ ├── metadata-dependencies.md # building on a metadata model published elsewhere (FR-023) +│ ├── settings.md # .metaobjects/settings.json: platform, product, size and secret store, layered (TypeScript, ADR-0070) │ ├── libraries.md # reusable declared design you opt into, a layer at a time (FR-043) │ ├── reporting.md # dimensions, measures, segments, reports: vocabulary and load rules (FR-044) │ ├── business-rules.md # operations, permission names and lifecycles: vocabulary, load rules, verify checks (ADR-0066) @@ -80,6 +81,7 @@ this tree is documentation, not the source of truth. | Compare what TS vs Java vs Kotlin vs C# vs Python emit for the same metadata | any [`features/*.md`](features/) — every feature shows all five ports side-by-side | | Author metadata in YAML instead of JSON | [`features/yaml-authoring.md`](features/yaml-authoring.md) | | Point the toolchain at metadata that lives somewhere other than `metaobjects/`, or scope what a project generates and migrates | [`features/metadata-sources.md`](features/metadata-sources.md) | +| Say which platform, product, size and secret store a deployment uses, layered from a shared estate file (`.metaobjects/settings.json`, TypeScript) | [`features/settings.md`](features/settings.md) | | Build on a metadata model another repository publishes (`dependencies`, `meta deps sync`, overlay/extend across the boundary) | [`features/metadata-dependencies.md`](features/metadata-dependencies.md) | | Adopt a design MetaObjects already ships — users/groups/roles, an LLM trace envelope — instead of authoring it (`libraries`, `meta eject `) | [`features/libraries.md`](features/libraries.md) | | Record what the system is supposed to do, and stop agents reviving retired features | [`features/requirements.md`](features/requirements.md) | diff --git a/docs/features/settings.md b/docs/features/settings.md new file mode 100644 index 000000000..cce73441a --- /dev/null +++ b/docs/features/settings.md @@ -0,0 +1,111 @@ +# Settings: platform, product, size and secret store + +The model says what runs and what is kept, in which environment and at which locations. It never +names a platform, a product, a size or a secret store. Those are **settings**, and they live in +their own file, `.metaobjects/settings.json`, beside `config.json` (ADR-0070, calls 5 and 13). + +**TypeScript only, and experimental.** Only TypeScript reads the settings file, so no other port's +config reader changes and `config.json` gains no keys. The reader and the resolver ship in +`@metaobjectsdev/sdk` in 1.4.0; no generator reads them yet, and the file's shape may change in a +minor release while the systems work lands. A project with no settings file has no settings, +and nothing changes for it. + +## The file + +```json +{ + "extends": "../estate/settings.json", + "targets": { + "lab": { "platform": "docker", "host": "lab-01.example", "country": "NL" } + }, + "platforms": { + "docker": { "emitter": "compose" } + }, + "resourceDefaults": { + "docker": { "rdb": { "product": "postgres", "version": "18" } } + }, + "purposes": { + "production": { "replicas": 2, "rdb": { "backupDays": 35 } } + }, + "environments": { + "Production": { + "apps": { "shop::Shop.api": { "replicas": 4 } }, + "provisions": { "shop-db": { "backupDays": 14 } } + } + }, + "secrets": { + "stores": { "vault": { "product": "openbao", "address": "https://bao.example" } }, + "generated": { "docker": "vault" }, + "adopted": "vault" + } +} +``` + +| Block | Says | Keyed by | +|---|---|---| +| `extends` | Another settings file this one builds on: a path relative to this file, or a package specifier | | +| `targets` | The places things can be put: a `platform`, a `country`, the platform's `region` and `zones`, and the platform's own identifiers (`account`, `project`, `host`) | A name you choose | +| `platforms` | For each platform, its `emitter`, and how it runs apps, schedules jobs and routes traffic | Platform | +| `resourceDefaults` | The `product` and `version` for each kind of resource | Platform, then resource kind | +| `purposes` | Sizes and counts for every environment of that purpose: plain values for apps, a block per resource kind | `production`, `staging`, `test`, `development` | +| `environments` | What differs in one environment: an app's size or tag (`apps`), a provision's size (`provisions`), public `hosts`, and API `addresses` | Environment, then node name | +| `secrets` | The `stores`; which one keeps generated credentials for each platform (`generated`) or for one target (`targets`); which keeps adopted keys (`adopted`) | | + +`placement` (which target a location means) and `fileTransports` are accepted so a complete +settings file loads, and are read by later 1.4.0 changes. Any other top-level key is an error. + +## `extends` and the layers + +A settings file may extend a shared estate file, which may extend another. The files merge key +by key and the nearer file wins, so a fleet-wide upgrade from Postgres 18 to 19 is one line in the +shared file. Arrays replace rather than append. Each file may leave out what the file it extends +supplies; the merged result must be complete. `extends` takes a path relative to the file, or a +package specifier: an estate's shared settings usually live in another repository, and a published +package is how a project reaches them, as with tsconfig's `extends`. + +On top of the merged file, one value for one node comes from these layers, lowest first: + +| Layer | From | +|---|---| +| `generator` | The default the generator passes in | +| `resourceDefaults` | `resourceDefaults..`, for a resource | +| `purpose` | `purposes.`: its plain values for an app, its `` block for a resource | +| `environment` | `environments..apps.` or `.provisions.` | + +Every resolved value carries its layer, the key path it was read from, and the file that wrote +it, so a generated file can say where each number came from. + +```ts +import { loadSettings, resolveResource, resolveGeneratedStore } from "@metaobjectsdev/sdk"; + +const settings = await loadSettings(".metaobjects"); +if (settings) { + const db = resolveResource(settings, { + kind: "rdb", + target: "lab", + environment: { name: "Production", purpose: "production" }, + provision: "shop-db", + generatorDefaults: { product: "postgres", version: "18" }, + }); + db.values.get("backupDays"); // { value: 14, layer: "environment", path: [...], file: ".../settings.json" } + resolveGeneratedStore(settings, "lab")?.name; // "vault" +} +``` + +The resolver is told the target by name. Choosing it from a location is `placement`'s job, and +arrives with it. + +## Errors + +| Code | When | +|---|---| +| `ERR_SETTINGS_INVALID` | A file is not JSON, has a key the format does not know, a purpose outside the four, or a nested value where a plain one belongs; or the merged settings miss a required key | +| `ERR_SETTINGS_EXTENDS_NOT_FOUND` | `extends` names a file or package that cannot be found | +| `ERR_SETTINGS_EXTENDS_CYCLE` | Settings files extend each other in a cycle | +| `ERR_SETTINGS_UNKNOWN_PLATFORM` | A target, a `resourceDefaults` key or a `secrets.generated` key names a platform `platforms` does not declare | +| `ERR_SETTINGS_UNKNOWN_STORE` | `secrets` names a store `secrets.stores` does not declare | +| `ERR_SETTINGS_UNKNOWN_TARGET` | `secrets.targets` names, or a resolver is asked for, a target `targets` does not declare | + +These are settings errors, raised by the TypeScript reader, and not loader codes. Checks that read +the model and the settings together (a key that names no node, a location with no target) are +`meta verify` rules and arrive with the vocabulary they read. diff --git a/server/typescript/packages/sdk/src/index.ts b/server/typescript/packages/sdk/src/index.ts index 20299be42..fa40d1a9b 100644 --- a/server/typescript/packages/sdk/src/index.ts +++ b/server/typescript/packages/sdk/src/index.ts @@ -19,6 +19,37 @@ export { ConfigSchema, DEFAULT_CONFIG, loadConfig, setConfigWarningSink, splitUnknownTopLevelKeys, CONFIG_TOP_LEVEL_KEYS, saveConfig, AllowTokenEnum, physicalNamingFromConfig, wireFormatFromConfig, enumDefaultsFromConfig, rulesSettingsFromConfig, apiPaginationFromConfig, apiUnknownFieldsFromConfig, HAND_EDITS_POLICIES, type HandEditsPolicy } from "./config.js"; export type { Config } from "./config.js"; +// Settings (ADR-0070, calls 5 and 13): `.metaobjects/settings.json`, read by TypeScript only, +// its `extends` chain, and the resolver for a node's target, product, size and secret store. +export { + SETTINGS_FILE, + SETTINGS_PURPOSES, + SETTINGS_LAYERS, + SETTINGS_ERROR_CODES, + SettingsError, + SettingsFileSchema, + loadSettings, + loadSettingsFile, + resolveTarget, + resolveResource, + resolveApp, + resolveGeneratedStore, + resolveAdoptedStore, + type Settings, + type SettingsFile, + type SettingsPurpose, + type SettingsLayer, + type SettingsErrorCode, + type SettingValue, + type Resolved, + type ResolvedTarget, + type ResolvedResource, + type ResolvedStore, + type EnvironmentRef, + type ResolveResourceInput, + type ResolveAppInput, +} from "./settings.js"; + // Metadata dependencies (FR-023) — the `dependencies` config key's schema, // constants, the manifest/lock schemas + integrity hashing, and the snapshot // verification + exclusion-key helpers `resolveCollection` composes into diff --git a/server/typescript/packages/sdk/src/settings.ts b/server/typescript/packages/sdk/src/settings.ts new file mode 100644 index 000000000..cffe492ab --- /dev/null +++ b/server/typescript/packages/sdk/src/settings.ts @@ -0,0 +1,516 @@ +// Settings: tier 3 of the systems design (ADR-0070, calls 5 and 13). +// +// The model says WHAT runs and is kept, in which environment, at which locations. Everything a +// platform needs beyond that — which platform, which product and version, which size, which +// secret store — is a setting. Settings live in their own file, `.metaobjects/settings.json`, +// beside `config.json` and never inside it: only TypeScript reads settings, so no other port's +// config reader changes (ADR-0070, "Settings live in a separate settings file"). +// +// A settings file may `extends` another (a shared estate file), and that one may extend a third. +// The files merge key by key, the extending file winning, so a fleet-wide upgrade is one line in +// the shared file. On top of the merged file, a value for one node is resolved through the layers +// below, lowest first; each answer says which layer, and which file, it came from: +// +// 1. generator — the default a generator passes in +// 2. resourceDefaults.. (resources: product and version) +// 3. purposes. (sizes and counts for every environment of that purpose) +// 4. environments..apps|provisions. (one environment, one node) +// +// Which target a LOCATION means (`placement`) and the file-transport products (`fileTransports`) +// belong to later changes. This module accepts both blocks so a complete settings file loads, and +// reads neither: the resolver is told the target by name. + +import { readFile } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, isAbsolute, join, resolve as resolvePath } from "node:path"; +import { z } from "zod"; + +/** The settings file's basename, in the project's `.metaobjects/` directory. */ +export const SETTINGS_FILE = "settings.json"; + +/** The closed set of environment purposes (ADR-0070, call 4: `environment.stage @purpose`). */ +export const SETTINGS_PURPOSES = ["production", "staging", "test", "development"] as const; +export type SettingsPurpose = (typeof SETTINGS_PURPOSES)[number]; + +/** The codes a settings failure carries. Settings are read by TypeScript only, so these are not loader codes. */ +export const SETTINGS_ERROR_CODES = [ + "ERR_SETTINGS_INVALID", + "ERR_SETTINGS_EXTENDS_NOT_FOUND", + "ERR_SETTINGS_EXTENDS_CYCLE", + "ERR_SETTINGS_UNKNOWN_PLATFORM", + "ERR_SETTINGS_UNKNOWN_TARGET", + "ERR_SETTINGS_UNKNOWN_STORE", +] as const; +export type SettingsErrorCode = (typeof SETTINGS_ERROR_CODES)[number]; + +export class SettingsError extends Error { + readonly code: SettingsErrorCode; + constructor(code: SettingsErrorCode, message: string) { + super(`${code}: ${message}`); + this.code = code; + this.name = "SettingsError"; + } +} + +// --------------------------------------------------------------------------------------------- +// The schema. Strict wherever the design fixes the keys; open (a catch-all of plain values) +// where a platform or product names its own (an Amazon `account`, a Railway `project`, an +// `instanceClass`). A nested object is a typo trap, so open records hold scalars only, except +// where the design nests one level (a purpose's per-kind block). +// --------------------------------------------------------------------------------------------- + +const Name = z.string().min(1); + +/** A plain setting value: what a size, count, flag or identifier can be. */ +const SettingValue = z.union([z.string(), z.number(), z.boolean()]); +export type SettingValue = z.infer; + +/** A node's settings: a flat record of plain values (`replicas`, `memoryMb`, `instanceClass`). */ +const NodeSettings = z.record(Name, SettingValue); + +/** + * The schema, built twice. A file in an `extends` chain may leave out what the file it extends + * supplies (a project that only moves `version` from "18" to "19"), so each FILE is checked with + * the required keys optional; the MERGED document is then checked complete. + */ +function settingsSchema(complete: boolean) { + // The static type is always the complete one: the layer schema's result is read only for its + // `extends`, and everything else is read from the merged document, which is checked complete. + const req = (s: T): T => (complete ? s : (s.optional() as unknown as T)); + + const target = z + .object({ + platform: req(Name), + /** ISO 3166 alpha-2 country, or `any` (accepted only for development and test; a later rule checks that). */ + country: req(Name), + region: Name.optional(), + /** The platform's name for each failure domain. A target with no zones is one failure domain. */ + zones: z.record(Name, Name).optional(), + }) + .catchall(z.string()); + + const platform = z.object({ emitter: req(Name) }).catchall(z.string()); + + const resourceDefault = z.object({ product: req(Name), version: Name.optional() }).catchall(SettingValue); + + /** A purpose block: plain values apply to apps; an object value is one resource kind's block. */ + const purpose = z.record(Name, z.union([SettingValue, NodeSettings])); + + const address = z.union([Name, z.object({ borrow: Name }).strict()]); + + const environment = z + .object({ + apps: z.record(Name, NodeSettings).optional(), + provisions: z.record(Name, NodeSettings).optional(), + /** Public host names: one name, or one per jurisdiction. */ + hosts: z.record(Name, z.union([Name, z.record(Name, Name)])).optional(), + /** The address of each API on this environment's address list, or the environment it borrows it from. */ + addresses: z.record(Name, address).optional(), + }) + .strict(); + + const secretStore = z.object({ product: req(Name) }).catchall(z.string()); + + const secrets = z + .object({ + stores: req(z.record(Name, secretStore)), + /** Which store keeps the credentials generated for each platform. */ + generated: z.record(Name, Name).optional(), + /** Which store keeps adopted keys (issued by someone else, never generated here). */ + adopted: Name.optional(), + /** A store for one target, ahead of its platform's `generated` store. */ + targets: z.record(Name, Name).optional(), + }) + .strict(); + + return z + .object({ + /** Another settings file this one extends: a path relative to this file, or a package specifier. */ + extends: Name.optional(), + targets: z.record(Name, target).optional(), + platforms: z.record(Name, platform).optional(), + resourceDefaults: z.record(Name, z.record(Name, resourceDefault)).optional(), + purposes: z.partialRecord(z.enum(SETTINGS_PURPOSES), purpose).optional(), + environments: z.record(Name, environment).optional(), + secrets: secrets.optional(), + /** Read by the placement change, not by this module. Accepted so a complete file loads. */ + placement: z.array(z.unknown()).optional(), + /** Read by the file-transport change, not by this module. Accepted so a complete file loads. */ + fileTransports: z.record(Name, z.unknown()).optional(), + }) + .strict(); +} + +/** The merged settings: every required key present. */ +export const SettingsFileSchema = settingsSchema(true); +/** One file of an `extends` chain: what the file it extends supplies may be left out. */ +const SettingsLayerSchema = settingsSchema(false); + +type TargetSettings = NonNullable[string]; +type PlatformSettings = NonNullable[string]; +type SecretStoreSettings = NonNullable["stores"][string]; + +export type SettingsFile = z.infer; + +// --------------------------------------------------------------------------------------------- +// Loading and merging. +// --------------------------------------------------------------------------------------------- + +type Json = string | number | boolean | null | Json[] | { [key: string]: Json }; +type JsonObject = { [key: string]: Json }; + +/** For every leaf of the merged document, the file that wrote it. Keyed by the JSON path joined with NUL. */ +type Origins = Map; + +/** A settings file and everything it extends, merged, with the file each value came from. */ +export interface Settings { + /** The merged document. */ + readonly data: SettingsFile; + /** The files read, the project file first, then each file it extends in turn. */ + readonly files: readonly string[]; + /** The file that wrote the value at `path` (a key path into {@link data}), or undefined. */ + originOf(path: readonly string[]): string | undefined; +} + +function isPlainObject(v: unknown): v is JsonObject { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +const pathKey = (path: readonly string[]): string => path.join("\u0000"); + +/** Record `file` as the origin of every leaf under `value` at `path`. Arrays are leaves: they replace, never merge. */ +function markOrigins(value: Json, path: string[], file: string, origins: Origins): void { + if (isPlainObject(value)) { + for (const [k, v] of Object.entries(value)) markOrigins(v, [...path, k], file, origins); + } else { + origins.set(pathKey(path), file); + } +} + +/** Merge `over` onto `base`: objects merge key by key, anything else in `over` replaces. */ +function mergeInto(base: JsonObject, over: JsonObject, path: string[], file: string, origins: Origins): JsonObject { + const out: JsonObject = { ...base }; + for (const [k, v] of Object.entries(over)) { + const here = [...path, k]; + const prior = out[k]; + if (isPlainObject(prior) && isPlainObject(v)) { + out[k] = mergeInto(prior, v, here, file, origins); + } else { + // Whatever `over` replaces, its old leaves no longer exist. + for (const key of [...origins.keys()]) { + if (key === pathKey(here) || key.startsWith(pathKey(here) + "\u0000")) origins.delete(key); + } + out[k] = v; + markOrigins(v, here, file, origins); + } + } + return out; +} + +function describeIssues(file: string, error: z.ZodError): string { + const lines = error.issues.map((issue) => { + const at = issue.path.map(String).join("."); + return ` ${at === "" ? "(top level)" : at}: ${issue.message}`; + }); + return [`${file} is not a valid MetaObjects settings file:`, ...lines].join("\n"); +} + +async function readSettingsDocument(file: string): Promise & JsonObject> { + let doc: unknown; + try { + doc = JSON.parse(await readFile(file, "utf8")); + } catch (err) { + throw new SettingsError("ERR_SETTINGS_INVALID", `${file} could not be read as JSON: ${(err as Error).message}`); + } + const result = SettingsLayerSchema.safeParse(doc); + if (!result.success) throw new SettingsError("ERR_SETTINGS_INVALID", describeIssues(file, result.error)); + return doc as z.infer & JsonObject; +} + +/** + * Where an `extends` value points: a path relative to the extending file, or a package specifier. + * The package form is how a project reaches an estate's shared settings kept in another repository, + * as tsconfig's `extends` does. + */ +function resolveExtends(spec: string, fromFile: string): string { + if (spec.startsWith(".") || isAbsolute(spec)) { + const target = resolvePath(dirname(fromFile), spec); + if (!existsSync(target)) { + throw new SettingsError("ERR_SETTINGS_EXTENDS_NOT_FOUND", `${fromFile} extends "${spec}", and ${target} does not exist.`); + } + return target; + } + try { + return createRequire(fromFile).resolve(spec); + } catch { + throw new SettingsError( + "ERR_SETTINGS_EXTENDS_NOT_FOUND", + `${fromFile} extends "${spec}", which is neither a relative path nor a package this project can resolve.`, + ); + } +} + +/** + * Read one settings file and everything it extends, and merge them: the file named here wins over + * the file it extends, key by key. Then check that the names the merged file uses exist in it: + * every target's platform is declared under `platforms`, and every store `secrets` names is + * declared under `secrets.stores`. + */ +export async function loadSettingsFile(file: string): Promise { + const chain: { file: string; doc: z.infer & JsonObject }[] = []; + let current = resolvePath(file); + for (;;) { + if (chain.some((c) => c.file === current)) { + const cycle = [...chain.map((c) => c.file), current].join(" -> "); + throw new SettingsError("ERR_SETTINGS_EXTENDS_CYCLE", `settings files extend each other in a cycle: ${cycle}`); + } + const doc = await readSettingsDocument(current); + chain.push({ file: current, doc }); + if (doc.extends === undefined) break; + current = resolveExtends(doc.extends, current); + } + + const origins: Origins = new Map(); + let merged: JsonObject = {}; + // The most distant file first, so each nearer file overrides it. + for (const { file: f, doc } of [...chain].reverse()) { + const { extends: _extends, ...rest } = doc; + merged = mergeInto(merged, rest as JsonObject, [], f, origins); + } + + const complete = SettingsFileSchema.safeParse(merged); + if (!complete.success) { + const names = chain.map((c) => c.file).join(", which extends "); + throw new SettingsError("ERR_SETTINGS_INVALID", describeIssues(`the merged settings of ${names}`, complete.error)); + } + const data = complete.data; + checkNames(data, chain[0]!.file); + return { + data, + files: chain.map((c) => c.file), + originOf: (path) => origins.get(pathKey(path)), + }; +} + +/** + * Read the project's settings, `/settings.json`. A project with no settings file has no + * settings, and that is not an error: nothing in the model needs one until it deploys. + */ +export async function loadSettings(metaRoot: string): Promise { + const file = join(metaRoot, SETTINGS_FILE); + if (!existsSync(file)) return undefined; + return loadSettingsFile(file); +} + +/** The value `record` itself holds under `key`; never one inherited from Object.prototype. */ +function own(record: Readonly> | undefined, key: string): T | undefined { + return record !== undefined && Object.hasOwn(record, key) ? record[key] : undefined; +} + +function checkNames(data: SettingsFile, file: string): void { + const platformNames: [string, string][] = [ + ...Object.entries(data.targets ?? {}).map(([t, target]): [string, string] => [`target "${t}" is on platform`, target.platform]), + ...Object.keys(data.resourceDefaults ?? {}).map((p): [string, string] => ["resourceDefaults names platform", p]), + ...Object.keys(data.secrets?.generated ?? {}).map((p): [string, string] => ["secrets.generated names platform", p]), + ]; + for (const [where, platform] of platformNames) { + if (own(data.platforms, platform) === undefined) { + throw new SettingsError("ERR_SETTINGS_UNKNOWN_PLATFORM", `${file}: ${where} "${platform}", which "platforms" does not declare.`); + } + } + const secrets = data.secrets; + if (secrets === undefined) return; + const stores = secrets.stores; + const named: [string, string][] = [ + ...Object.entries(secrets.generated ?? {}).map(([p, s]): [string, string] => [`secrets.generated.${p}`, s]), + ...Object.entries(secrets.targets ?? {}).map(([t, s]): [string, string] => [`secrets.targets.${t}`, s]), + ...(secrets.adopted === undefined ? [] : [["secrets.adopted", secrets.adopted] as [string, string]]), + ]; + for (const [where, store] of named) { + if (own(stores, store) === undefined) { + throw new SettingsError("ERR_SETTINGS_UNKNOWN_STORE", `${file}: ${where} names store "${store}", which secrets.stores does not declare.`); + } + } + for (const target of Object.keys(secrets.targets ?? {})) { + if (own(data.targets, target) === undefined) { + throw new SettingsError("ERR_SETTINGS_UNKNOWN_TARGET", `${file}: secrets.targets names target "${target}", which "targets" does not declare.`); + } + } +} + +// --------------------------------------------------------------------------------------------- +// The resolver: which target, product, size and store for one node, and from which layer. +// --------------------------------------------------------------------------------------------- + +/** The layer a resolved value came from, lowest first. */ +export const SETTINGS_LAYERS = ["generator", "resourceDefaults", "purpose", "environment"] as const; +export type SettingsLayer = (typeof SETTINGS_LAYERS)[number]; + +/** One resolved value, the layer that supplied it and, unless it is the generator's, the file that wrote it. */ +export interface Resolved { + readonly value: T; + readonly layer: SettingsLayer; + /** The settings file, or undefined for a generator default. */ + readonly file: string | undefined; + /** The key path in the merged settings, or undefined for a generator default. */ + readonly path: readonly string[] | undefined; +} + +export interface ResolvedTarget { + readonly name: string; + readonly platform: string; + readonly target: TargetSettings; + readonly platformSettings: PlatformSettings; + readonly file: string | undefined; +} + +/** Which environment a node is resolved for: its name, and the purpose its `environment.stage` declares. */ +export interface EnvironmentRef { + readonly name: string; + readonly purpose: SettingsPurpose; +} + +function layerValues( + out: Map, + values: Record | undefined, + layer: SettingsLayer, + settings: Settings, + path: readonly string[], + include: (value: unknown) => value is SettingValue, +): void { + if (values === undefined) return; + for (const [key, value] of Object.entries(values)) { + if (!include(value)) continue; + const at = [...path, key]; + out.set(key, { value, layer, file: settings.originOf(at), path: at }); + } +} + +const isSettingValue = (v: unknown): v is SettingValue => + typeof v === "string" || typeof v === "number" || typeof v === "boolean"; + +function generatorLayer(defaults: Readonly> | undefined): Map { + const out = new Map(); + for (const [key, value] of Object.entries(defaults ?? {})) { + out.set(key, { value, layer: "generator", file: undefined, path: undefined }); + } + return out; +} + +/** The target a node is placed on, with its platform's settings. Throws when either is not declared. */ +export function resolveTarget(settings: Settings, targetName: string): ResolvedTarget { + const target = own(settings.data.targets, targetName); + if (target === undefined) { + throw new SettingsError("ERR_SETTINGS_UNKNOWN_TARGET", `no target "${targetName}" in ${settings.files[0]}.`); + } + const platformSettings = own(settings.data.platforms, target.platform); + if (platformSettings === undefined) { + // loadSettingsFile already refused this; reachable only for a hand-built Settings. + throw new SettingsError("ERR_SETTINGS_UNKNOWN_PLATFORM", `target "${targetName}" names platform "${target.platform}", which is not declared.`); + } + return { + name: targetName, + platform: target.platform, + target, + platformSettings, + file: settings.originOf(["targets", targetName, "platform"]), + }; +} + +export interface ResolveResourceInput { + /** The resource kind: the subtype of the `resource` node (`rdb`, `keyValue`, `objectStore`, ...). */ + readonly kind: string; + /** The target the resource is placed on, by name. */ + readonly target: string; + readonly environment?: EnvironmentRef; + /** The `provision.resource` node's name, for the environment layer. */ + readonly provision?: string; + /** What the generator writes when no setting says otherwise. */ + readonly generatorDefaults?: Readonly>; +} + +export interface ResolvedResource { + readonly target: ResolvedTarget; + /** Every resolved value by key: `product`, `version`, and the sizes (`instanceClass`, `backupDays`, ...). */ + readonly values: ReadonlyMap; +} + +/** + * The product, version and sizes of one resource on one target: the generator's defaults, then + * `resourceDefaults..`, then the environment purpose's `` block, then + * `environments..provisions.`. Each value says which layer and file supplied it. + */ +export function resolveResource(settings: Settings, input: ResolveResourceInput): ResolvedResource { + const target = resolveTarget(settings, input.target); + const values = generatorLayer(input.generatorDefaults); + const d = settings.data; + layerValues(values, own(own(d.resourceDefaults, target.platform), input.kind), "resourceDefaults", settings, + ["resourceDefaults", target.platform, input.kind], isSettingValue); + if (input.environment !== undefined) { + const { name, purpose } = input.environment; + const block = own(own(d.purposes, purpose), input.kind); + if (isPlainObject(block)) { + layerValues(values, block, "purpose", settings, ["purposes", purpose, input.kind], isSettingValue); + } + if (input.provision !== undefined) { + layerValues(values, own(own(d.environments, name)?.provisions, input.provision), "environment", settings, + ["environments", name, "provisions", input.provision], isSettingValue); + } + } + return { target, values }; +} + +export interface ResolveAppInput { + /** The app's canonical name (`pkg::System.app`), as the settings key it. */ + readonly app: string; + readonly environment?: EnvironmentRef; + readonly generatorDefaults?: Readonly>; +} + +/** + * The sizes, counts and tag of one app: the generator's defaults, then the plain values of the + * environment purpose's block (`replicas`), then `environments..apps.`. + */ +export function resolveApp(settings: Settings, input: ResolveAppInput): ReadonlyMap { + const values = generatorLayer(input.generatorDefaults); + if (input.environment !== undefined) { + const { name, purpose } = input.environment; + layerValues(values, own(settings.data.purposes, purpose), "purpose", settings, ["purposes", purpose], isSettingValue); + layerValues(values, own(own(settings.data.environments, name)?.apps, input.app), "environment", settings, + ["environments", name, "apps", input.app], isSettingValue); + } + return values; +} + +export interface ResolvedStore { + readonly name: string; + readonly store: SecretStoreSettings; + /** The key path that chose the store: `secrets.targets.`, `secrets.generated.` or `secrets.adopted`. */ + readonly chosenBy: readonly string[]; + readonly file: string | undefined; +} + +/** + * The store that keeps credentials generated for anything on `targetName`: the target's own store + * (`secrets.targets`) if it has one, else its platform's (`secrets.generated`). Undefined when the + * settings name neither. + */ +export function resolveGeneratedStore(settings: Settings, targetName: string): ResolvedStore | undefined { + const target = resolveTarget(settings, targetName); + const secrets = settings.data.secrets; + if (secrets === undefined) return undefined; + const byTarget = own(secrets.targets, targetName); + const chosenBy = byTarget !== undefined ? ["secrets", "targets", targetName] : ["secrets", "generated", target.platform]; + const name = byTarget ?? own(secrets.generated, target.platform); + if (name === undefined) return undefined; + return { name, store: secrets.stores[name]!, chosenBy, file: settings.originOf(chosenBy) }; +} + +/** The store that keeps adopted keys, or undefined when the settings name none. */ +export function resolveAdoptedStore(settings: Settings): ResolvedStore | undefined { + const secrets = settings.data.secrets; + if (secrets?.adopted === undefined) return undefined; + const chosenBy = ["secrets", "adopted"]; + return { name: secrets.adopted, store: secrets.stores[secrets.adopted]!, chosenBy, file: settings.originOf(chosenBy) }; +} diff --git a/server/typescript/packages/sdk/test/fixtures/settings/setup-a.settings.json b/server/typescript/packages/sdk/test/fixtures/settings/setup-a.settings.json new file mode 100644 index 000000000..6d6577eee --- /dev/null +++ b/server/typescript/packages/sdk/test/fixtures/settings/setup-a.settings.json @@ -0,0 +1,101 @@ +{ + "targets": { + "aws-eu-west": { "platform": "aws", "account": "quillhaven-production", "region": "eu-west-1", "country": "IE", + "zones": { "a": "eu-west-1a", "b": "eu-west-1b", "c": "eu-west-1c" } }, + "aws-eu-central": { "platform": "aws", "account": "quillhaven-production", "region": "eu-central-1", "country": "DE", + "zones": { "a": "eu-central-1a", "b": "eu-central-1b" } }, + "aws-us-east": { "platform": "aws", "account": "quillhaven-production", "region": "us-east-1", "country": "US", + "zones": { "a": "us-east-1a", "b": "us-east-1b", "c": "us-east-1c" } }, + "aws-us-west": { "platform": "aws", "account": "quillhaven-production", "region": "us-west-2", "country": "US", + "zones": { "a": "us-west-2a", "b": "us-west-2b" } }, + "aws-lower-eu": { "platform": "aws", "account": "quillhaven-lower", "region": "eu-west-1", "country": "IE" }, + "aws-lower-us": { "platform": "aws", "account": "quillhaven-lower", "region": "us-east-1", "country": "US" } + }, + + "placement": [ + { "purpose": "production", "location": "EU.EuWest", "target": "aws-eu-west" }, + { "purpose": "production", "location": "EU.EuCentral", "target": "aws-eu-central" }, + { "purpose": "production", "location": "US.UsEast", "target": "aws-us-east" }, + { "purpose": "production", "location": "US.UsWest", "target": "aws-us-west" }, + { "location": "EU.EuWest", "target": "aws-lower-eu" }, + { "location": "US.UsEast", "target": "aws-lower-us" } + ], + + "platforms": { + "aws": { "emitter": "terraform", "compute": "ecs-fargate", "schedule": "eventbridge-scheduler", "traffic": "route53-latency" } + }, + + "resourceDefaults": { + "aws": { + "rdb": { "product": "aurora-postgresql", "version": "17" }, + "keyValue": { "product": "elasticache-valkey", "version": "8" }, + "objectStore": { "product": "s3" }, + "document": { "product": "documentdb", "version": "8.0" }, + "search": { "product": "opensearch-service", "version": "3.1" }, + "queue": { "product": "sqs" }, + "stream": { "product": "msk", "version": "4.1" } + } + }, + + "fileTransports": { + "aws": { "sftp": { "product": "transfer-family" } } + }, + + "secrets": { + "stores": { + "aws": { "product": "aws-secrets-manager" } + }, + "generated": { "aws": "aws" }, + "adopted": "aws" + }, + + "purposes": { + "production": { "replicas": 3, "rdb": { "instanceClass": "db.r8g.large", "backupDays": 35 } }, + "staging": { "replicas": 1, "rdb": { "instanceClass": "db.t4g.medium", "backupDays": 7 } }, + "test": { "replicas": 1, "rdb": { "instanceClass": "db.t4g.medium", "backupDays": 0 } }, + "development": { "replicas": 1, "rdb": { "instanceClass": "db.t4g.medium", "backupDays": 0 } } + }, + + "environments": { + "Production": { + "apps": { + "quillhaven::parcels::Parcels.api": { "replicas": 6, "memoryMb": 2048 }, + "corvid::wayfinder::Wayfinder.planner": { "tag": "4.2.0" }, + "corvid::wayfinder::Wayfinder.nightlySolve": { "tag": "4.2.0", "memoryMb": 8192 } + }, + "provisions": { + "parcels-db-us": { "instanceClass": "db.r8g.xlarge", "writeForwarding": true }, + "parcels-events-us": { "brokersPerZone": 1, "retentionHours": 168 } + }, + "hosts": { + "quillhaven::parcels::Parcels.api": { "EU": "eu.parcels.quillhaven.example", "US": "us.parcels.quillhaven.example" }, + "quillhaven::rates::Rates.api": "rates.quillhaven.example" + }, + "addresses": { + "larkspur::pay::PaymentsApi": "https://api.larkspur.example", + "tidewell::CustomsFilingIntake": "sftp.tidewell.example:22" + } + }, + "Staging": { + "addresses": { + "larkspur::pay::PaymentsApi": "https://sandbox.larkspur.example", + "tidewell::CustomsFilingIntake": "sftp-test.tidewell.example:22" + } + }, + "Preview": { + "addresses": { + "quillhaven::rates::api::RateApi": { "borrow": "Staging" }, + "quillhaven::ledger::api::LedgerApi": { "borrow": "Staging" }, + "corvid::wayfinder::RouteApi": { "borrow": "Staging" }, + "tidewell::CustomsFilingIntake": "sftp-test.tidewell.example:22" + } + }, + "Development": { + "addresses": { + "quillhaven::ledger::api::LedgerApi": { "borrow": "Staging" }, + "corvid::wayfinder::RouteApi": { "borrow": "Staging" }, + "tidewell::CustomsFilingIntake": "sftp-test.tidewell.example:22" + } + } + } +} diff --git a/server/typescript/packages/sdk/test/fixtures/settings/setup-b.settings.json b/server/typescript/packages/sdk/test/fixtures/settings/setup-b.settings.json new file mode 100644 index 000000000..021e4639f --- /dev/null +++ b/server/typescript/packages/sdk/test/fixtures/settings/setup-b.settings.json @@ -0,0 +1,114 @@ +{ + "targets": { + "aws-eu-west": { "platform": "aws", "account": "quillhaven-production", "region": "eu-west-1", "country": "IE", + "zones": { "a": "eu-west-1a", "b": "eu-west-1b", "c": "eu-west-1c" } }, + "aws-eu-central": { "platform": "aws", "account": "quillhaven-production", "region": "eu-central-1", "country": "DE", + "zones": { "a": "eu-central-1a", "b": "eu-central-1b" } }, + "aws-us-east": { "platform": "aws", "account": "quillhaven-production", "region": "us-east-1", "country": "US", + "zones": { "a": "us-east-1a", "b": "us-east-1b", "c": "us-east-1c" } }, + "aws-us-west": { "platform": "aws", "account": "quillhaven-production", "region": "us-west-2", "country": "US", + "zones": { "a": "us-west-2a", "b": "us-west-2b" } }, + "aws-lower-eu": { "platform": "aws", "account": "quillhaven-lower", "region": "eu-west-1", "country": "IE" }, + "aws-lower-us": { "platform": "aws", "account": "quillhaven-lower", "region": "us-east-1", "country": "US" }, + + "railway-eu": { "platform": "railway", "project": "wayfinder-eu", "region": "europe-west4-drams3a", "country": "NL" }, + "railway-us": { "platform": "railway", "project": "wayfinder-us", "region": "us-east4-eqdc4a", "country": "US" }, + + "dc-rotterdam": { "platform": "docker", "host": "rtm-app-01.dc.quillhaven.example", "country": "NL" }, + "dc-frankfurt": { "platform": "docker", "host": "fra-app-01.dc.quillhaven.example", "country": "DE" } + }, + + "placement": [ + { "purpose": "production", "location": "EU.EuWest", "target": "aws-eu-west" }, + { "purpose": "production", "location": "EU.EuCentral", "target": "aws-eu-central" }, + { "purpose": "production", "location": "US.UsEast", "target": "aws-us-east" }, + { "purpose": "production", "location": "US.UsWest", "target": "aws-us-west" }, + { "location": "EU.EuWest", "target": "aws-lower-eu" }, + { "location": "US.UsEast", "target": "aws-lower-us" }, + + { "system": "corvid::wayfinder::Wayfinder", "location": "EU.EuWest", "target": "railway-eu" }, + { "system": "corvid::wayfinder::Wayfinder", "location": "US.UsEast", "target": "railway-us" }, + + { "system": "quillhaven::ledger::Ledger", "location": "EU.EuWest", "target": "dc-rotterdam" }, + { "system": "quillhaven::ledger::Ledger", "location": "EU.EuCentral", "target": "dc-frankfurt" } + ], + + "platforms": { + "aws": { "emitter": "terraform", "compute": "ecs-fargate", "schedule": "eventbridge-scheduler", "traffic": "route53-latency" }, + "railway": { "emitter": "railway-ts" }, + "docker": { "emitter": "compose", "schedule": "systemd-timer", "traffic": "caddy" } + }, + + "resourceDefaults": { + "aws": { + "rdb": { "product": "aurora-postgresql", "version": "17" }, + "keyValue": { "product": "elasticache-valkey", "version": "8" }, + "objectStore": { "product": "s3" }, + "document": { "product": "documentdb", "version": "8.0" }, + "search": { "product": "opensearch-service", "version": "3.1" }, + "queue": { "product": "sqs" }, + "stream": { "product": "msk", "version": "4.1" } + }, + "railway": { + "rdb": { "product": "railway-postgres" }, + "keyValue": { "product": "railway-redis" } + }, + "docker": { + "rdb": { "product": "postgres", "version": "18" }, + "objectStore": { "product": "seaweedfs" }, + "queue": { "product": "rabbitmq", "version": "4.4" } + } + }, + + "fileTransports": { + "aws": { "sftp": { "product": "transfer-family" } } + }, + + "secrets": { + "stores": { + "aws": { "product": "aws-secrets-manager" }, + "railway": { "product": "railway-sealed-variables" }, + "datacentre": { "product": "openbao", "address": "https://bao.dc.quillhaven.example", "mount": "estate/" }, + "partners": { "product": "openbao", "address": "https://bao.dc.quillhaven.example", "mount": "partners/" } + }, + "generated": { "aws": "aws", "railway": "railway", "docker": "datacentre" }, + "adopted": "partners" + }, + + "purposes": { + "production": { "replicas": 3, "rdb": { "backupDays": 35 } }, + "staging": { "replicas": 1, "rdb": { "backupDays": 7 } }, + "test": { "replicas": 1 }, + "development": { "replicas": 1 } + }, + + "environments": { + "Production": { + "apps": { + "quillhaven::parcels::Parcels.api": { "replicas": 6, "memoryMb": 2048 }, + "corvid::wayfinder::Wayfinder.planner": { "tag": "4.2.0", "replicas": 2 }, + "corvid::wayfinder::Wayfinder.nightlySolve": { "tag": "4.2.0" }, + "quillhaven::ledger::Ledger.api": { "replicas": 2 } + }, + "provisions": { + "parcels-db-us": { "instanceClass": "db.r8g.xlarge", "writeForwarding": true } + }, + "hosts": { + "quillhaven::parcels::Parcels.api": { "EU": "eu.parcels.quillhaven.example", "US": "us.parcels.quillhaven.example" }, + "quillhaven::rates::Rates.api": "rates.quillhaven.example", + "quillhaven::ledger::Ledger.api": "ledger.quillhaven.example", + "corvid::wayfinder::Wayfinder.planner": { "EU": "routes-eu.quillhaven.example", "US": "routes-us.quillhaven.example" } + }, + "addresses": { + "larkspur::pay::PaymentsApi": "https://api.larkspur.example", + "tidewell::CustomsFilingIntake": "sftp.tidewell.example:22" + } + }, + "Staging": { + "addresses": { + "larkspur::pay::PaymentsApi": "https://sandbox.larkspur.example", + "tidewell::CustomsFilingIntake": "sftp-test.tidewell.example:22" + } + } + } +} diff --git a/server/typescript/packages/sdk/test/fixtures/settings/setup-c.settings.json b/server/typescript/packages/sdk/test/fixtures/settings/setup-c.settings.json new file mode 100644 index 000000000..42af908b0 --- /dev/null +++ b/server/typescript/packages/sdk/test/fixtures/settings/setup-c.settings.json @@ -0,0 +1,88 @@ +{ + "targets": { + "dc-rotterdam": { "platform": "docker", "country": "NL", + "zones": { "a": "rtm-hall1.dc.quillhaven.example", "b": "rtm-hall2.dc.quillhaven.example", "c": "rtm-hall3.dc.quillhaven.example" } }, + "dc-frankfurt": { "platform": "docker", "country": "DE", + "zones": { "a": "fra-hall1.dc.quillhaven.example", "b": "fra-hall2.dc.quillhaven.example" } }, + "dc-ashburn": { "platform": "docker", "country": "US", + "zones": { "a": "iad-hall1.dc.quillhaven.example", "b": "iad-hall2.dc.quillhaven.example", "c": "iad-hall3.dc.quillhaven.example" } }, + "dc-reno": { "platform": "docker", "country": "US", + "zones": { "a": "rno-hall1.dc.quillhaven.example", "b": "rno-hall2.dc.quillhaven.example" } }, + "lab-rotterdam": { "platform": "docker", "host": "rtm-lab-01.dc.quillhaven.example", "country": "NL" }, + "lab-ashburn": { "platform": "docker", "host": "iad-lab-01.dc.quillhaven.example", "country": "US" }, + "laptop": { "platform": "docker", "host": "local", "country": "any" } + }, + + "placement": [ + { "purpose": "production", "location": "EU.EuWest", "target": "dc-rotterdam" }, + { "purpose": "production", "location": "EU.EuCentral", "target": "dc-frankfurt" }, + { "purpose": "production", "location": "US.UsEast", "target": "dc-ashburn" }, + { "purpose": "production", "location": "US.UsWest", "target": "dc-reno" }, + { "location": "EU.EuWest", "target": "lab-rotterdam" }, + { "location": "US.UsEast", "target": "lab-ashburn" }, + { "purpose": "development", "target": "laptop" } + ], + + "platforms": { + "docker": { "emitter": "compose", "schedule": "systemd-timer", "traffic": "caddy" } + }, + + "resourceDefaults": { + "docker": { + "rdb": { "product": "postgres", "version": "18" }, + "keyValue": { "product": "valkey", "version": "9" }, + "objectStore": { "product": "seaweedfs" }, + "document": { "product": "mongodb", "version": "8" }, + "search": { "product": "opensearch", "version": "2" }, + "queue": { "product": "rabbitmq", "version": "4.4" }, + "stream": { "product": "kafka", "version": "4.1.0" } + } + }, + + "fileTransports": { + "docker": { "sftp": { "product": "sftpgo", "version": "v2.7.5" } } + }, + + "secrets": { + "stores": { + "datacentre": { "product": "openbao", "address": "https://bao.dc.quillhaven.example", "mount": "estate/" }, + "partners": { "product": "openbao", "address": "https://bao.dc.quillhaven.example", "mount": "partners/" }, + "laptop": { "product": "env-file", "path": ".env.local" } + }, + "generated": { "docker": "datacentre" }, + "adopted": "partners", + "targets": { "laptop": "laptop" } + }, + + "purposes": { + "production": { "replicas": 2 }, + "staging": { "replicas": 1 }, + "test": { "replicas": 1 }, + "development": { "replicas": 1 } + }, + + "environments": { + "Production": { + "apps": { + "quillhaven::parcels::Parcels.api": { "replicas": 4 }, + "corvid::wayfinder::Wayfinder.planner": { "tag": "4.2.0" }, + "corvid::wayfinder::Wayfinder.nightlySolve": { "tag": "4.2.0" } + }, + "hosts": { + "quillhaven::parcels::Parcels.api": { "EU": "eu.parcels.quillhaven.example", "US": "us.parcels.quillhaven.example" }, + "quillhaven::rates::Rates.api": "rates.quillhaven.example", + "quillhaven::ledger::Ledger.api": "ledger.quillhaven.example" + }, + "addresses": { + "larkspur::pay::PaymentsApi": "https://api.larkspur.example", + "tidewell::CustomsFilingIntake": "sftp.tidewell.example:22" + } + }, + "Staging": { + "addresses": { + "larkspur::pay::PaymentsApi": "https://sandbox.larkspur.example", + "tidewell::CustomsFilingIntake": "sftp-test.tidewell.example:22" + } + } + } +} diff --git a/server/typescript/packages/sdk/test/settings.test.ts b/server/typescript/packages/sdk/test/settings.test.ts new file mode 100644 index 000000000..67e8f0396 --- /dev/null +++ b/server/typescript/packages/sdk/test/settings.test.ts @@ -0,0 +1,302 @@ +// Settings (ADR-0070, calls 5 and 13): the separate `.metaobjects/settings.json`, its `extends` +// chain, and the resolver that answers which target, product, size and secret store a node gets, +// and from which layer. +// +// The oracle for the three setup files is the systems design itself: each fixture under +// fixtures/settings/ is one of its three complete settings files, copied unchanged, and every +// expected value below is read off that file by hand (which layer should win is the design's +// layer order: generator, resourceDefaults, purpose, environment). + +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + SETTINGS_FILE, + SettingsError, + loadSettings, + loadSettingsFile, + resolveAdoptedStore, + resolveApp, + resolveGeneratedStore, + resolveResource, + resolveTarget, + type Settings, + type SettingsErrorCode, +} from "../src/settings.js"; + +const fixtures = join(import.meta.dir, "fixtures", "settings"); +const setup = (name: "a" | "b" | "c"): Promise => loadSettingsFile(join(fixtures, `setup-${name}.settings.json`)); + +const scratchRoot = await mkdtemp(join(process.env.DEV_SCRATCH ?? tmpdir(), "mo-settings-test-")); +afterAll(async () => { + await rm(scratchRoot, { recursive: true, force: true }); +}); +let n = 0; +/** A fresh directory with the given files (name -> JSON value) written into it. */ +async function dirWith(files: Record): Promise { + const dir = join(scratchRoot, `case-${n++}`); + for (const [name, doc] of Object.entries(files)) { + const path = join(dir, name); + await mkdir(join(path, ".."), { recursive: true }); + await writeFile(path, JSON.stringify(doc, null, 2)); + } + return dir; +} + +async function codeOf(p: Promise): Promise { + try { + await p; + return "resolved"; + } catch (err) { + if (err instanceof SettingsError) return err.code; + throw err; + } +} + +const PRODUCTION = { name: "Production", purpose: "production" } as const; +const STAGING = { name: "Staging", purpose: "staging" } as const; + +describe("the design's three setup files", () => { + test("all three load", async () => { + for (const name of ["a", "b", "c"] as const) { + const s = await setup(name); + expect(s.files).toHaveLength(1); + } + }); + + test("A: Parcels' US database on Amazon in Production takes every layer", async () => { + const s = await setup("a"); + const r = resolveResource(s, { + kind: "rdb", + target: "aws-us-east", + environment: PRODUCTION, + provision: "parcels-db-us", + generatorDefaults: { product: "postgres", version: "18", storageGb: 20 }, + }); + expect(r.target.platform).toBe("aws"); + expect(r.target.platformSettings.emitter).toBe("terraform"); + expect(r.target.target.region).toBe("us-east-1"); + const v = Object.fromEntries([...r.values].map(([k, x]) => [k, [x.value, x.layer]])); + expect(v).toEqual({ + product: ["aurora-postgresql", "resourceDefaults"], + version: ["17", "resourceDefaults"], + storageGb: [20, "generator"], + backupDays: [35, "purpose"], + instanceClass: ["db.r8g.xlarge", "environment"], + writeForwarding: [true, "environment"], + }); + expect(r.values.get("instanceClass")?.path).toEqual(["environments", "Production", "provisions", "parcels-db-us", "instanceClass"]); + }); + + test("A: the same database in Staging takes the staging purpose's size", async () => { + const s = await setup("a"); + const r = resolveResource(s, { kind: "rdb", target: "aws-lower-us", environment: STAGING, provision: "parcels-db-us" }); + expect(r.values.get("instanceClass")).toMatchObject({ value: "db.t4g.medium", layer: "purpose" }); + expect(r.values.get("backupDays")).toMatchObject({ value: 7, layer: "purpose" }); + expect(r.values.has("writeForwarding")).toBe(false); + }); + + test("A: apps take the purpose's replicas unless the environment names the app", async () => { + const s = await setup("a"); + const api = resolveApp(s, { app: "quillhaven::parcels::Parcels.api", environment: PRODUCTION }); + expect(api.get("replicas")).toMatchObject({ value: 6, layer: "environment" }); + expect(api.get("memoryMb")).toMatchObject({ value: 2048, layer: "environment" }); + const rates = resolveApp(s, { app: "quillhaven::rates::Rates.api", environment: PRODUCTION }); + expect(rates.get("replicas")).toMatchObject({ value: 3, layer: "purpose", path: ["purposes", "production", "replicas"] }); + // A purpose's kind block (rdb) is a resource's, never an app's. + expect(rates.has("rdb")).toBe(false); + const planner = resolveApp(s, { app: "corvid::wayfinder::Wayfinder.planner", environment: PRODUCTION }); + expect(planner.get("tag")).toMatchObject({ value: "4.2.0", layer: "environment" }); + }); + + test("A: one store holds generated and adopted keys", async () => { + const s = await setup("a"); + expect(resolveGeneratedStore(s, "aws-eu-west")).toMatchObject({ name: "aws", store: { product: "aws-secrets-manager" } }); + expect(resolveAdoptedStore(s)?.name).toBe("aws"); + }); + + test("B: three platforms, each with its own products and store", async () => { + const s = await setup("b"); + const railway = resolveResource(s, { kind: "rdb", target: "railway-eu" }); + expect(railway.target.platformSettings.emitter).toBe("railway-ts"); + expect(railway.values.get("product")?.value).toBe("railway-postgres"); + expect(railway.values.has("version")).toBe(false); + const dc = resolveResource(s, { kind: "rdb", target: "dc-rotterdam", environment: PRODUCTION }); + expect(dc.target.target.host).toBe("rtm-app-01.dc.quillhaven.example"); + expect(dc.values.get("product")?.value).toBe("postgres"); + expect(dc.values.get("version")?.value).toBe("18"); + expect(dc.values.get("backupDays")).toMatchObject({ value: 35, layer: "purpose" }); + expect(resolveGeneratedStore(s, "dc-rotterdam")).toMatchObject({ name: "datacentre", chosenBy: ["secrets", "generated", "docker"] }); + expect(resolveGeneratedStore(s, "railway-us")?.store.product).toBe("railway-sealed-variables"); + expect(resolveAdoptedStore(s)).toMatchObject({ name: "partners", store: { mount: "partners/" } }); + }); + + test("B: a kind the platform has no default for resolves to the generator's", async () => { + const s = await setup("b"); + const r = resolveResource(s, { kind: "stream", target: "dc-frankfurt", generatorDefaults: { product: "kafka" } }); + expect(r.values.get("product")).toMatchObject({ value: "kafka", layer: "generator", file: undefined }); + }); + + test("C: a target's own store comes before its platform's", async () => { + const s = await setup("c"); + expect(resolveGeneratedStore(s, "laptop")).toMatchObject({ + name: "laptop", + store: { product: "env-file", path: ".env.local" }, + chosenBy: ["secrets", "targets", "laptop"], + }); + expect(resolveGeneratedStore(s, "dc-ashburn")?.name).toBe("datacentre"); + const doc = resolveResource(s, { kind: "document", target: "dc-reno" }); + expect(doc.values.get("product")?.value).toBe("mongodb"); + expect(resolveTarget(s, "dc-reno").target.zones).toEqual({ a: "rno-hall1.dc.quillhaven.example", b: "rno-hall2.dc.quillhaven.example" }); + const api = resolveApp(s, { app: "quillhaven::parcels::Parcels.api", environment: PRODUCTION }); + expect(api.get("replicas")).toMatchObject({ value: 4, layer: "environment" }); + }); +}); + +describe("extends: a shared estate file under the project's", () => { + const estate = { + platforms: { docker: { emitter: "compose" } }, + targets: { lab: { platform: "docker", host: "lab-01", country: "NL" } }, + resourceDefaults: { docker: { rdb: { product: "postgres", version: "18" }, keyValue: { product: "valkey", version: "9" } } }, + purposes: { production: { replicas: 3, rdb: { backupDays: 35 } } }, + secrets: { stores: { vault: { product: "openbao" } }, generated: { docker: "vault" } }, + placement: [{ location: "EU.EuWest", target: "lab" }], + }; + + test("the project wins key by key, and each value names the file that wrote it", async () => { + const dir = await dirWith({ + "estate/settings.json": estate, + [`.metaobjects/${SETTINGS_FILE}`]: { + extends: "../estate/settings.json", + resourceDefaults: { docker: { rdb: { version: "19" } } }, + purposes: { production: { rdb: { backupDays: 14 } } }, + }, + }); + const s = await loadSettings(join(dir, ".metaobjects")); + expect(s).toBeDefined(); + const settings = s!; + const project = join(dir, ".metaobjects", SETTINGS_FILE); + const estateFile = join(dir, "estate", "settings.json"); + expect(settings.files).toEqual([project, estateFile]); + const r = resolveResource(settings, { kind: "rdb", target: "lab", environment: PRODUCTION }); + expect(r.values.get("product")).toMatchObject({ value: "postgres", layer: "resourceDefaults", file: estateFile }); + expect(r.values.get("version")).toMatchObject({ value: "19", layer: "resourceDefaults", file: project }); + expect(r.values.get("backupDays")).toMatchObject({ value: 14, layer: "purpose", file: project }); + // Untouched by the project: still the estate's. + expect(resolveResource(settings, { kind: "keyValue", target: "lab" }).values.get("version")).toMatchObject({ value: "9", file: estateFile }); + expect(resolveApp(settings, { app: "x::S.api", environment: PRODUCTION }).get("replicas")).toMatchObject({ value: 3, file: estateFile }); + expect(resolveGeneratedStore(settings, "lab")).toMatchObject({ name: "vault", file: estateFile }); + }); + + test("a chain of three files merges nearest last", async () => { + const dir = await dirWith({ + "base.json": { ...estate, resourceDefaults: { docker: { rdb: { product: "postgres", version: "16" } } } }, + "estate.json": { extends: "./base.json", resourceDefaults: { docker: { rdb: { version: "17" } } } }, + "project.json": { extends: "./estate.json", purposes: { production: { replicas: 5 } } }, + }); + const s = await loadSettingsFile(join(dir, "project.json")); + expect(s.files.map((f) => f.slice(dir.length + 1))).toEqual(["project.json", "estate.json", "base.json"]); + const r = resolveResource(s, { kind: "rdb", target: "lab" }); + expect(r.values.get("version")).toMatchObject({ value: "17", file: join(dir, "estate.json") }); + expect(r.values.get("product")).toMatchObject({ value: "postgres", file: join(dir, "base.json") }); + expect(resolveApp(s, { app: "x::S.api", environment: PRODUCTION }).get("replicas")?.value).toBe(5); + }); + + test("an array replaces the extended file's, never appends to it", async () => { + const dir = await dirWith({ + "estate.json": estate, + "project.json": { extends: "./estate.json", placement: [{ location: "US.UsEast", target: "lab" }] }, + }); + const s = await loadSettingsFile(join(dir, "project.json")); + expect(s.data.placement).toEqual([{ location: "US.UsEast", target: "lab" }]); + expect(s.originOf(["placement"])).toBe(join(dir, "project.json")); + }); + + test("a package specifier resolves through the project's node_modules", async () => { + const dir = await dirWith({ + "node_modules/@estate/metaobjects-defaults/package.json": { name: "@estate/metaobjects-defaults", main: "settings.json" }, + "node_modules/@estate/metaobjects-defaults/settings.json": estate, + [`.metaobjects/${SETTINGS_FILE}`]: { extends: "@estate/metaobjects-defaults" }, + }); + const s = (await loadSettings(join(dir, ".metaobjects")))!; + expect(resolveResource(s, { kind: "rdb", target: "lab" }).values.get("product")?.value).toBe("postgres"); + }); + + test("each file may be partial, but the merged settings must be complete", async () => { + const dir = await dirWith({ + "estate.json": { platforms: { docker: { emitter: "compose" } } }, + "project.json": { extends: "./estate.json", resourceDefaults: { docker: { rdb: { version: "19" } } } }, + }); + // Neither file names the product, so the merged rdb default has none. + expect(await codeOf(loadSettingsFile(join(dir, "project.json")))).toBe("ERR_SETTINGS_INVALID"); + }); + + test("a relative path to a file that is not there is refused", async () => { + const missing = await dirWith({ "p.json": { extends: "./nope.json" } }); + expect(await codeOf(loadSettingsFile(join(missing, "p.json")))).toBe("ERR_SETTINGS_EXTENDS_NOT_FOUND"); + }); + + test("a package specifier the project cannot resolve is refused", async () => { + const noPackage = await dirWith({ "p.json": { extends: "@estate/not-installed" } }); + expect(await codeOf(loadSettingsFile(join(noPackage, "p.json")))).toBe("ERR_SETTINGS_EXTENDS_NOT_FOUND"); + }); + + test("files that extend each other are refused", async () => { + const cycle = await dirWith({ "a.json": { extends: "./b.json" }, "b.json": { extends: "./a.json" } }); + expect(await codeOf(loadSettingsFile(join(cycle, "a.json")))).toBe("ERR_SETTINGS_EXTENDS_CYCLE"); + }); +}); + +describe("what a settings file may not say", () => { + const minimal = { platforms: { docker: { emitter: "compose" } }, targets: { lab: { platform: "docker", country: "NL" } } }; + const load = async (doc: unknown) => codeOf(loadSettingsFile(join(await dirWith({ "s.json": doc }), "s.json"))); + + test("a project with no settings file has no settings", async () => { + expect(await loadSettings(await dirWith({}))).toBeUndefined(); + }); + + test("the minimal file loads", async () => { + expect(await load(minimal)).toBe("resolved"); + }); + + test("an unknown top-level key, a purpose outside the closed set, and a nested size are refused", async () => { + expect(await load({ ...minimal, target: {} })).toBe("ERR_SETTINGS_INVALID"); + expect(await load({ ...minimal, purposes: { prod: { replicas: 1 } } })).toBe("ERR_SETTINGS_INVALID"); + expect(await load({ ...minimal, environments: { Production: { apps: { "x::S.api": { size: { cpu: 1 } } } } } })).toBe("ERR_SETTINGS_INVALID"); + expect(await load({ ...minimal, environments: { Production: { provision: {} } } })).toBe("ERR_SETTINGS_INVALID"); + expect(await load({ ...minimal, resourceDefaults: { docker: { rdb: { version: "18" } } } })).toBe("ERR_SETTINGS_INVALID"); + }); + + test("a target on an undeclared platform is refused", async () => { + expect(await load({ ...minimal, targets: { cloud: { platform: "aws", country: "IE" } } })).toBe("ERR_SETTINGS_UNKNOWN_PLATFORM"); + }); + + test("a resourceDefaults or secrets.generated key that is not a declared platform is refused", async () => { + expect(await load({ ...minimal, resourceDefaults: { dokcer: { rdb: { product: "postgres" } } } })).toBe("ERR_SETTINGS_UNKNOWN_PLATFORM"); + const stores = { stores: { vault: { product: "openbao" } } }; + expect(await load({ ...minimal, secrets: { ...stores, generated: { dokcer: "vault" } } })).toBe("ERR_SETTINGS_UNKNOWN_PLATFORM"); + }); + + test("a name inherited from Object.prototype is not a declared platform, store or target", async () => { + expect(await load({ ...minimal, targets: { cloud: { platform: "constructor", country: "IE" } } })).toBe("ERR_SETTINGS_UNKNOWN_PLATFORM"); + const stores = { stores: { vault: { product: "openbao" } } }; + expect(await load({ ...minimal, secrets: { ...stores, adopted: "toString" } })).toBe("ERR_SETTINGS_UNKNOWN_STORE"); + expect(await load({ ...minimal, secrets: { ...stores, targets: { constructor: "vault" } } })).toBe("ERR_SETTINGS_UNKNOWN_TARGET"); + const s = await loadSettingsFile(join(await dirWith({ "s.json": minimal }), "s.json")); + expect(() => resolveTarget(s, "constructor")).toThrow("ERR_SETTINGS_UNKNOWN_TARGET"); + }); + + test("secrets may name only declared stores and targets", async () => { + const stores = { stores: { vault: { product: "openbao" } } }; + expect(await load({ ...minimal, secrets: { ...stores, generated: { docker: "vault" }, adopted: "vault" } })).toBe("resolved"); + expect(await load({ ...minimal, secrets: { ...stores, generated: { docker: "elsewhere" } } })).toBe("ERR_SETTINGS_UNKNOWN_STORE"); + expect(await load({ ...minimal, secrets: { ...stores, adopted: "elsewhere" } })).toBe("ERR_SETTINGS_UNKNOWN_STORE"); + expect(await load({ ...minimal, secrets: { ...stores, targets: { nowhere: "vault" } } })).toBe("ERR_SETTINGS_UNKNOWN_TARGET"); + }); + + test("resolving onto a target the settings do not declare is refused", async () => { + const s = await setup("c"); + expect(() => resolveResource(s, { kind: "rdb", target: "aws-eu-west" })).toThrow("ERR_SETTINGS_UNKNOWN_TARGET"); + }); +});