Files
0pt/src/clients/st0re-client.ts
T
Simon AxelssonandClaude Fable 5 b7038d7675 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>
2026-08-31 16:35:01 +02:00

158 lines
6.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* src/clients/st0re-client.ts
* ============================
* 0pt's client for the generic ST0RE Artifact registry. Distinct from
* `./st0re-lakehouse-client.ts` (the /v1/st0re/lakehouse/* table registry).
*
* REWRITTEN 2026-08-31 against ST0RE's REAL wire contract (sax3l/st0re branch
* feat/siax-platforms-p0-storage-os, `src/api/routes/artifacts.ts` +
* `src/api/validation.ts` ArtifactInputSchema, verified this session):
*
* createArtifact -> POST {baseUrl}/v1/st0re/artifacts/register
*
* The REAL request body is camelCase (`tenantId`, `artifactType`,
* `primaryObjectId`, ...), NOT the snake_case + `object_location{...}` shape
* this client used to send — that shape would have been a 400 against the
* live registry. Key contract facts encoded here:
*
* - required: tenantId, projectId, appId, artifactType, displayName,
* producedBy, primaryObjectId, schemaVersion, retentionPolicy, createdBy;
* - checksumSha256 is DE FACTO required when ST0RE cannot derive it from a
* known same-tenant object (0pt always sends it — it always has the
* checksum, and never wants the fail-closed 400);
* - primaryObjectId accepts the `s3://<bucket>/<key>` storage URI (0pt
* formats it from its bucket/key pair);
* - headers: X-Tenant-Id + X-Actor-Id are REQUIRED on every ST0RE route;
* idempotency via X-Idempotency-Key (201 new, 200 idempotent replay);
* - body tenantId is ignored server-side in favour of X-Tenant-Id (sent
* anyway to satisfy validation).
*
* The 0pt-side input keeps its historical snake_case field names so existing
* call sites stay stable; the wire mapping lives here and is pinned by
* tests/contracts/st0re-client.contract.test.ts.
*
* Production fallback policy (Master-DoD §3/§10): no base URL in a production
* runtime throws `SiaxError("DEPENDENCY_UNAVAILABLE")` at construction. The
* in-memory mock (ids prefixed "mock_artifact_") survives only for
* non-production runtimes.
*/
import crypto from "crypto";
import { SiaxHttp } from "./http";
import { resolveDependencyBaseUrl } from "../platform/dependency-mode";
import type { SiaxRequestContext } from "../platform/siax-context";
export interface St0reObjectLocation {
provider: string;
bucket: string;
key: string;
region?: string;
}
export interface St0reArtifactInput {
tenant_id: string;
project_id: string;
artifact_type: string;
app_id: string;
produced_by: string;
object_location: St0reObjectLocation;
content_type: string;
size_bytes: number;
checksum_sha256: string;
pii_level: "none" | "low" | "medium" | "high";
retention_policy: string;
data_residency: string;
/** Risk level L0–L5 per the SIAX Cloud risk taxonomy. */
risk_level: string;
correlation_id?: string;
/** Human-readable name; defaults to the object key's basename. */
display_name?: string;
/** Artifact schema version; defaults to "v1". */
schema_version?: string;
/** Registering actor; defaults to produced_by. */
created_by?: string;
/** Tenant-scoped dedup key (ST0RE replays the existing artifact on 200). */
idempotency_key?: string;
}
/** Alias so both historical import names resolve to the same shape. */
export type CreateArtifactInput = St0reArtifactInput;
export interface St0reArtifact extends St0reArtifactInput {
artifact_id: string;
created_at: string;
}
export interface St0reClient {
createArtifact(input: St0reArtifactInput, context?: SiaxRequestContext): Promise<St0reArtifact>;
}
export function createSt0reClient(baseUrl?: string, opts?: { token?: string }): St0reClient {
const resolved = resolveDependencyBaseUrl("st0re", baseUrl ?? process.env.ST0RE_URL);
if (!resolved) return new MockSt0reClient();
return new HttpSt0reClient(resolved, opts?.token ?? process.env.ST0RE_SERVICE_TOKEN);
}
/** Non-production runtimes only: deterministic in-memory mock artifact. */
class MockSt0reClient implements St0reClient {
async createArtifact(input: St0reArtifactInput): Promise<St0reArtifact> {
return {
...input,
artifact_id: `mock_artifact_${crypto.randomUUID()}`,
created_at: new Date().toISOString(),
};
}
}
class HttpSt0reClient implements St0reClient {
private readonly http: SiaxHttp;
constructor(baseUrl: string, token?: string) {
this.http = new SiaxHttp({ dependency: "st0re", baseUrl, token });
}
async createArtifact(input: St0reArtifactInput, context?: SiaxRequestContext): Promise<St0reArtifact> {
const storageUri = `s3://${input.object_location.bucket}/${input.object_location.key}`;
const keyBasename = input.object_location.key.split("/").pop() ?? input.object_location.key;
const actorId = input.created_by ?? input.produced_by;
const res = await this.http.request({
method: "POST",
path: "/v1/st0re/artifacts/register",
context,
// ST0RE requires X-Tenant-Id + X-Actor-Id on every route; the SIAX
// propagation headers (x-tenant-id/x-actor-id) satisfy that when a
// context is supplied, and these explicit values win regardless.
headers: {
"X-Tenant-Id": input.tenant_id,
"X-Actor-Id": actorId,
...(input.idempotency_key ? { "X-Idempotency-Key": input.idempotency_key } : {}),
},
body: {
tenantId: input.tenant_id,
projectId: input.project_id,
appId: input.app_id,
artifactType: input.artifact_type,
displayName: input.display_name ?? keyBasename,
producedBy: input.produced_by,
primaryObjectId: storageUri,
schemaVersion: input.schema_version ?? "v1",
retentionPolicy: input.retention_policy,
createdBy: actorId,
checksumSha256: input.checksum_sha256,
piiLevel: input.pii_level,
dataResidency: input.data_residency,
...(input.idempotency_key ? { idempotencyKey: input.idempotency_key } : {}),
},
// 200 = idempotent replay of an existing artifact — a success here.
acceptStatuses: [200],
});
const body = (res.json ?? {}) as { artifactId?: string; createdAt?: number };
return {
...input,
artifact_id: body.artifactId ?? "",
created_at: body.createdAt ? new Date(body.createdAt).toISOString() : new Date().toISOString(),
};
}
}