feat(platform): canonical SIAX context/errors + real-contract clients, no prod mock fallback
- src/platform/: SiaxRequestContext + propagation headers + 12 canonical
error codes (documented mirror of cl0ud packages/contract), SiaxError,
resource refs (st0re:artifact:...), and the §3/§10 dependency-mode guard:
production runtime + unconfigured dependency/store => hard
DEPENDENCY_UNAVAILABLE at construction, never silent mock/in-memory.
- src/clients/: all four platform clients rewritten against the REAL wire
contracts verified on sibling main branches this session:
* cl0ud: POST /api/policy/evaluate ({data} envelope, allow+requiresApproval)
- the old /v1/cl0ud/policies/evaluate path never existed on CL0UD
* st0re: camelCase ArtifactInput on /v1/st0re/artifacts/register incl.
X-Tenant-Id/X-Actor-Id + X-Idempotency-Key - the old snake_case body
would have been a 400 against the live registry
* n0d: required_role + resource_requirements + body idempotency_key +
CloudEvents callback_url per n0d createJobSchema; adds getJob/getJobResult
* aud0: /v1/aud0/openlineage is AUD0's only lineage ingest -
/v1/aud0/lineage/events never existed; legacy shape converts to a
spec-shaped OpenLineage RunEvent (deterministic runId dedup)
- src/lineage/: OpenLineage subset types + LineageEmitter (never-throw,
§16 evidence semantics)
- shared SiaxHttp transport: timeouts, typed SiaxError mapping, context
propagation, no raw upstream bodies in errors
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
00a1b3997d
commit
b7038d7675
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* src/platform/dependency-mode.ts
|
||||
* ================================
|
||||
* THE production mock-fallback kill switch (Master-DoD §3: "Ingen
|
||||
* production-path faller tyst tillbaka till mock/in-memory", §10: "Production
|
||||
* kan inte falla tillbaka till mock").
|
||||
*
|
||||
* Before this module, every platform client in src/clients/* documented the
|
||||
* same convention: "when no base URL is configured the client runs in
|
||||
* LOCAL/MOCK/NOOP mode". That convention is fine for unit tests and local
|
||||
* dev, and it is EXACTLY the silent-fallback failure mode the Master-DoD
|
||||
* forbids in production. This module centralizes the decision so every
|
||||
* factory makes it the same way:
|
||||
*
|
||||
* - production runtime + no URL → throw SiaxError DEPENDENCY_UNAVAILABLE
|
||||
* at CONSTRUCTION time (fail hard, fail early — not on first call).
|
||||
* - non-production + no URL → the factory may return its local/mock
|
||||
* implementation (hermetic tests, local dev).
|
||||
* - URL configured → real HTTP client, any runtime.
|
||||
*
|
||||
* "Production runtime" means NODE_ENV=production, the same switch the
|
||||
* existing auth layer uses (src/auth/context.ts refuses AUTH_ENFORCE=false
|
||||
* under NODE_ENV=production). There is deliberately NO override that lets
|
||||
* production run on mocks: if a deployment genuinely wants a dependency off,
|
||||
* that is a topology decision expressed by NOT calling the capability, never
|
||||
* by a mock silently answering it.
|
||||
*/
|
||||
import { SiaxError } from "./errors";
|
||||
|
||||
/** True when this process is a production runtime. */
|
||||
export function isProductionRuntime(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
return env.NODE_ENV === "production";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a dependency base URL for a client factory.
|
||||
*
|
||||
* Returns the URL (trimmed, no trailing slash) when configured. Returns
|
||||
* `undefined` when unconfigured in a non-production runtime — the caller may
|
||||
* then use its documented local/mock implementation. THROWS
|
||||
* `SiaxError("DEPENDENCY_UNAVAILABLE")` when unconfigured in production.
|
||||
*/
|
||||
export function resolveDependencyBaseUrl(
|
||||
dependency: string,
|
||||
configuredUrl: string | undefined,
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): string | undefined {
|
||||
const url = configuredUrl?.trim();
|
||||
if (url) return url.replace(/\/+$/, "");
|
||||
if (isProductionRuntime(env)) {
|
||||
throw new SiaxError(
|
||||
"DEPENDENCY_UNAVAILABLE",
|
||||
dependency,
|
||||
`no base URL configured for required dependency "${dependency}" in a production runtime; ` +
|
||||
`refusing to fall back to a mock/in-memory implementation (Master-DoD §3/§10)`
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same decision for stateful stores (Postgres-backed registries): production
|
||||
* with no DATABASE_URL must fail hard rather than serve an in-memory Map.
|
||||
*/
|
||||
export function resolveStoreMode(
|
||||
store: string,
|
||||
databaseUrl: string | undefined,
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): { mode: "postgres"; url: string } | { mode: "memory" } {
|
||||
const url = databaseUrl?.trim();
|
||||
if (url) return { mode: "postgres", url };
|
||||
if (isProductionRuntime(env)) {
|
||||
throw new SiaxError(
|
||||
"DEPENDENCY_UNAVAILABLE",
|
||||
store,
|
||||
`no database configured for persistent store "${store}" in a production runtime; ` +
|
||||
`refusing the in-memory fallback (Master-DoD §3/§10)`
|
||||
);
|
||||
}
|
||||
return { mode: "memory" };
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* src/platform/errors.ts
|
||||
* =======================
|
||||
* The canonical SIAX cross-product error vocabulary (Master-DoD §6), mirrored
|
||||
* from cl0ud's `packages/contract/src/request-context.ts` (`SIAX_ERROR_CODES`
|
||||
* + `httpStatusForSiaxErrorCode`) under the same documented mirror posture as
|
||||
* src/platform/siax-context.ts. tests/contracts/siax-context.contract.test.ts
|
||||
* pins the full code list and status mapping.
|
||||
*
|
||||
* `SiaxError` is the typed error every 0pt platform client and capability
|
||||
* service throws at a product boundary. Retryable vs permanent is explicit
|
||||
* (§6: "Retryable vs permanent är explicit"), correlation id travels in the
|
||||
* error (§6: "Correlation ID finns i felet"), and no sensitive internals are
|
||||
* embedded — `detail` is a short operator-facing string, never a raw body.
|
||||
*/
|
||||
|
||||
export const SIAX_ERROR_CODES = [
|
||||
"UNAUTHENTICATED",
|
||||
"AUTHORIZATION_DENIED",
|
||||
"ENTITLEMENT_REQUIRED",
|
||||
"CAPABILITY_UNAVAILABLE",
|
||||
"QUOTA_EXCEEDED",
|
||||
"RATE_LIMITED",
|
||||
"INVALID_REQUEST",
|
||||
"NOT_FOUND",
|
||||
"CONFLICT",
|
||||
"DEPENDENCY_UNAVAILABLE",
|
||||
"RETRYABLE_FAILURE",
|
||||
"PERMANENT_FAILURE",
|
||||
] as const;
|
||||
|
||||
/** One canonical SIAX error code. */
|
||||
export type SiaxErrorCode = (typeof SIAX_ERROR_CODES)[number];
|
||||
|
||||
/** Canonical HTTP status for a {@link SiaxErrorCode} (transport guidance, pinned to cl0ud). */
|
||||
export function httpStatusForSiaxErrorCode(code: SiaxErrorCode): number {
|
||||
switch (code) {
|
||||
case "UNAUTHENTICATED":
|
||||
return 401;
|
||||
case "AUTHORIZATION_DENIED":
|
||||
return 403;
|
||||
case "ENTITLEMENT_REQUIRED":
|
||||
case "QUOTA_EXCEEDED":
|
||||
return 402;
|
||||
case "CAPABILITY_UNAVAILABLE":
|
||||
return 404;
|
||||
case "RATE_LIMITED":
|
||||
return 429;
|
||||
case "INVALID_REQUEST":
|
||||
return 400;
|
||||
case "NOT_FOUND":
|
||||
return 404;
|
||||
case "CONFLICT":
|
||||
return 409;
|
||||
case "DEPENDENCY_UNAVAILABLE":
|
||||
case "RETRYABLE_FAILURE":
|
||||
return 503;
|
||||
case "PERMANENT_FAILURE":
|
||||
return 500;
|
||||
default: {
|
||||
const _never: never = code;
|
||||
return _never;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a caller may retry the failed operation (with its idempotency key). */
|
||||
export function isRetryableSiaxErrorCode(code: SiaxErrorCode): boolean {
|
||||
return code === "DEPENDENCY_UNAVAILABLE" || code === "RETRYABLE_FAILURE" || code === "RATE_LIMITED";
|
||||
}
|
||||
|
||||
/** Map an upstream HTTP status (from a SIAX dependency) onto the canonical vocabulary. */
|
||||
export function siaxErrorCodeForUpstreamStatus(status: number): SiaxErrorCode {
|
||||
if (status === 400) return "INVALID_REQUEST";
|
||||
if (status === 401) return "UNAUTHENTICATED";
|
||||
if (status === 402) return "ENTITLEMENT_REQUIRED";
|
||||
if (status === 403) return "AUTHORIZATION_DENIED";
|
||||
if (status === 404) return "NOT_FOUND";
|
||||
if (status === 409) return "CONFLICT";
|
||||
if (status === 429) return "RATE_LIMITED";
|
||||
if (status === 501) return "CAPABILITY_UNAVAILABLE";
|
||||
if (status === 502 || status === 503 || status === 504) return "DEPENDENCY_UNAVAILABLE";
|
||||
if (status >= 500) return "RETRYABLE_FAILURE";
|
||||
return "PERMANENT_FAILURE";
|
||||
}
|
||||
|
||||
/** The typed error thrown at 0pt product boundaries. */
|
||||
export class SiaxError extends Error {
|
||||
readonly code: SiaxErrorCode;
|
||||
/** Which dependency/capability produced the failure, e.g. "st0re", "0pt.search.query". */
|
||||
readonly source: string;
|
||||
/** Correlation id of the failing operation, when known (§6). */
|
||||
readonly correlationId?: string;
|
||||
readonly retryable: boolean;
|
||||
readonly httpStatus: number;
|
||||
|
||||
constructor(
|
||||
code: SiaxErrorCode,
|
||||
source: string,
|
||||
detail: string,
|
||||
opts?: { correlationId?: string; cause?: unknown }
|
||||
) {
|
||||
super(`[${code}] ${source}: ${detail}`, { cause: opts?.cause });
|
||||
this.name = "SiaxError";
|
||||
this.code = code;
|
||||
this.source = source;
|
||||
this.correlationId = opts?.correlationId;
|
||||
this.retryable = isRetryableSiaxErrorCode(code);
|
||||
this.httpStatus = httpStatusForSiaxErrorCode(code);
|
||||
}
|
||||
|
||||
/** Structured log/JSON form. Never includes stack or raw upstream bodies. */
|
||||
toJSON(): Record<string, unknown> {
|
||||
return {
|
||||
error: this.code,
|
||||
source: this.source,
|
||||
message: this.message,
|
||||
retryable: this.retryable,
|
||||
...(this.correlationId ? { correlation_id: this.correlationId } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* src/platform/resource-ref.ts
|
||||
* =============================
|
||||
* Canonical SIAX resource references (Master-DoD §5):
|
||||
*
|
||||
* `<product>:<resourceType>:<resourceId>[@<version>]`
|
||||
*
|
||||
* e.g. `st0re:artifact:art_x`, `aud0:evidence:ev_x`, `0pt:dataset:ds_x`,
|
||||
* `0pt:dataset:ds_x@3`. No product needs another product's DB primary key;
|
||||
* references are stable, resolvable through the owning capability, and
|
||||
* authorization happens at dereference (never here — this module is pure
|
||||
* parsing/formatting).
|
||||
*/
|
||||
|
||||
export interface SiaxResourceRef {
|
||||
product: string;
|
||||
resourceType: string;
|
||||
resourceId: string;
|
||||
version?: string;
|
||||
}
|
||||
|
||||
const REF_RE = /^([a-z0-9][a-z0-9-]*):([a-z0-9][a-z0-9_-]*):([^@\s:]+)(?:@([A-Za-z0-9._-]+))?$/;
|
||||
|
||||
/** Format a canonical reference string. */
|
||||
export function formatResourceRef(ref: SiaxResourceRef): string {
|
||||
const base = `${ref.product}:${ref.resourceType}:${ref.resourceId}`;
|
||||
return ref.version ? `${base}@${ref.version}` : base;
|
||||
}
|
||||
|
||||
/** Parse a canonical reference string; returns undefined when malformed. */
|
||||
export function parseResourceRef(raw: string): SiaxResourceRef | undefined {
|
||||
const m = REF_RE.exec(raw.trim());
|
||||
if (!m) return undefined;
|
||||
return { product: m[1], resourceType: m[2], resourceId: m[3], ...(m[4] ? { version: m[4] } : {}) };
|
||||
}
|
||||
|
||||
/** True when `raw` is a canonical reference for the given product/type. */
|
||||
export function isResourceRef(raw: string, product?: string, resourceType?: string): boolean {
|
||||
const ref = parseResourceRef(raw);
|
||||
if (!ref) return false;
|
||||
if (product && ref.product !== product) return false;
|
||||
if (resourceType && ref.resourceType !== resourceType) return false;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* src/platform/siax-context.ts
|
||||
* =============================
|
||||
* MIRROR of cl0ud's canonical cross-product request context
|
||||
* (`sax3l/cl0ud` `packages/contract/src/request-context.ts`, merged to cl0ud
|
||||
* main 2026-08-31). Mirrored — NOT imported — because `@siax/contract` is not
|
||||
* published to a registry this repo consumes yet; the mirror posture is the
|
||||
* same one cl0ud itself documents for its platform-core `ErrorCode` mirror
|
||||
* ("KEEP ALIGNED; drift is a review catch and a test failure").
|
||||
* tests/contracts/siax-context.contract.test.ts pins every header name and
|
||||
* field so drift against the canonical source fails loudly here.
|
||||
*
|
||||
* TRUST BOUNDARY (verbatim from the canonical source): this context is a
|
||||
* CARRIER, not a VERIFIER. A receiving service derives its tenant from the
|
||||
* VERIFIED caller; the `x-tenant-id` propagation header is honoured only for
|
||||
* a verified machine/service principal. The cryptographic binding is the
|
||||
* service credential on the Authorization header — this context rides
|
||||
* alongside it for scoping, policy and tracing.
|
||||
*/
|
||||
|
||||
/** The canonical SIAX cross-product request context (Master-DoD §4). */
|
||||
export interface SiaxRequestContext {
|
||||
/** The tenant this call acts for (`t_<slug>` spine). Server-derived. */
|
||||
tenantId: string;
|
||||
/** The bound project within the tenant, when the operation is project-scoped. */
|
||||
projectId?: string;
|
||||
/** The acting subject: a user `sub`, or a service/machine identity id. */
|
||||
actorId: string;
|
||||
/** The capability being invoked — canonical dotted registry id, e.g. `0pt.search.query.v1`. */
|
||||
capability: string;
|
||||
/** Optional GDPR/purpose-limitation tag, e.g. `valuation`, `support`, `billing`. */
|
||||
purpose?: string;
|
||||
/** Correlation id shared by every hop of one logical operation. */
|
||||
correlationId: string;
|
||||
/** The id of the event/request that CAUSED this one (event-chain lineage). */
|
||||
causationId?: string;
|
||||
/** Distributed-tracing trace id (W3C trace-context compatible where possible). */
|
||||
traceId?: string;
|
||||
/** Idempotency key for retried writes — same key ⇒ same effect, exactly once. */
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical wire headers for propagating a {@link SiaxRequestContext} on
|
||||
* service-to-service calls. Names are pinned to cl0ud's
|
||||
* `SIAX_CONTEXT_HEADERS` verbatim.
|
||||
*/
|
||||
export const SIAX_CONTEXT_HEADERS = {
|
||||
tenant: "x-tenant-id",
|
||||
actor: "x-actor-id",
|
||||
capability: "x-siax-capability",
|
||||
purpose: "x-siax-purpose",
|
||||
project: "x-siax-project-id",
|
||||
correlation: "x-siax-correlation-id",
|
||||
causation: "x-siax-causation-id",
|
||||
trace: "x-siax-trace-id",
|
||||
idempotency: "idempotency-key",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Serialize a context to the canonical propagation headers for an OUTBOUND
|
||||
* service-to-service call. The caller adds its own service `Authorization` —
|
||||
* this function deliberately has no way to carry a token.
|
||||
*/
|
||||
export function toPropagationHeaders(ctx: SiaxRequestContext): Record<string, string> {
|
||||
const h: Record<string, string> = {
|
||||
[SIAX_CONTEXT_HEADERS.tenant]: ctx.tenantId,
|
||||
[SIAX_CONTEXT_HEADERS.actor]: ctx.actorId,
|
||||
[SIAX_CONTEXT_HEADERS.capability]: ctx.capability,
|
||||
[SIAX_CONTEXT_HEADERS.correlation]: ctx.correlationId,
|
||||
};
|
||||
if (ctx.projectId) h[SIAX_CONTEXT_HEADERS.project] = ctx.projectId;
|
||||
if (ctx.purpose) h[SIAX_CONTEXT_HEADERS.purpose] = ctx.purpose;
|
||||
if (ctx.causationId) h[SIAX_CONTEXT_HEADERS.causation] = ctx.causationId;
|
||||
if (ctx.traceId) h[SIAX_CONTEXT_HEADERS.trace] = ctx.traceId;
|
||||
if (ctx.idempotencyKey) h[SIAX_CONTEXT_HEADERS.idempotency] = ctx.idempotencyKey;
|
||||
return h;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure structural validation of a candidate context (e.g. before persisting
|
||||
* to an audit/lineage record). Returns a list of problems — empty means
|
||||
* valid. NOT an authorization check.
|
||||
*/
|
||||
export function validateSiaxRequestContext(ctx: Partial<SiaxRequestContext>): string[] {
|
||||
const problems: string[] = [];
|
||||
const requireNonEmpty = (field: keyof SiaxRequestContext) => {
|
||||
const v = ctx[field];
|
||||
if (typeof v !== "string" || v.trim().length === 0) {
|
||||
problems.push(`${field} is required and must be a non-empty string`);
|
||||
}
|
||||
};
|
||||
requireNonEmpty("tenantId");
|
||||
requireNonEmpty("actorId");
|
||||
requireNonEmpty("capability");
|
||||
requireNonEmpty("correlationId");
|
||||
for (const field of ["projectId", "purpose", "causationId", "traceId", "idempotencyKey"] as const) {
|
||||
const v = ctx[field];
|
||||
if (v !== undefined && (typeof v !== "string" || v.trim().length === 0)) {
|
||||
problems.push(`${field}, when present, must be a non-empty string`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
Reference in New Issue
Block a user