fix(recovery): restore source removed by production documentation merge
This commit is contained in:
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* 0pt's sole AUD0 producer boundary.
|
||||
*
|
||||
* Default clients are durable: when DATABASE_URL is configured, evidence is
|
||||
* first written to opt_aud0_evidence_outbox and later delivered by the
|
||||
* dispatcher. `durable:false` exists only for that dispatcher, which must
|
||||
* perform the real HTTP delivery rather than enqueue recursively.
|
||||
*/
|
||||
import { SiaxHttp } from "./http";
|
||||
import { createAud0OutboxRepositoryFromEnv, type Aud0OutboxRepository } from "../evidence/aud0-outbox";
|
||||
import { resolveDependencyBaseUrl } from "../platform/dependency-mode";
|
||||
import type { SiaxRequestContext } from "../platform/siax-context";
|
||||
import type { OpenLineageRunEvent } from "../lineage/openlineage";
|
||||
|
||||
export interface Aud0Event {
|
||||
event_id: string;
|
||||
event_type: string;
|
||||
tenant_id: string;
|
||||
project_id: string;
|
||||
actor_id: string;
|
||||
app_id: string;
|
||||
capability_id: string;
|
||||
resource_type: string;
|
||||
resource_id: string;
|
||||
risk_level: string;
|
||||
payload?: unknown;
|
||||
created_at: string;
|
||||
correlation_id?: string;
|
||||
occurred_at?: string;
|
||||
purpose?: string;
|
||||
policy_decision?: string;
|
||||
causation_id?: string;
|
||||
trace_id?: string;
|
||||
result?: string;
|
||||
input_refs?: string[];
|
||||
output_refs?: string[];
|
||||
idempotency_key?: string;
|
||||
}
|
||||
|
||||
export interface Aud0LineageEvent {
|
||||
lineage_event_id: string;
|
||||
tenant_id: string;
|
||||
project_id: string;
|
||||
app_id: string;
|
||||
capability_id: string;
|
||||
source_type: string;
|
||||
source_id: string;
|
||||
target_type: string;
|
||||
target_id: string;
|
||||
lineage_type: string;
|
||||
metadata?: unknown;
|
||||
created_at: string;
|
||||
correlation_id?: string;
|
||||
}
|
||||
|
||||
export type Aud0EventInput = Aud0Event;
|
||||
export type Aud0LineageEventInput = Aud0LineageEvent;
|
||||
|
||||
export interface Aud0OpenLineageAck {
|
||||
tenant_id: string;
|
||||
run_id: string;
|
||||
job: string;
|
||||
event_id: string;
|
||||
evidence_id?: string;
|
||||
deduplicated?: boolean;
|
||||
}
|
||||
|
||||
export interface Aud0Client {
|
||||
ingestEvent(event: Aud0Event, context?: SiaxRequestContext): Promise<Aud0Event>;
|
||||
ingestOpenLineageEvent(
|
||||
tenantId: string,
|
||||
appId: string,
|
||||
event: OpenLineageRunEvent,
|
||||
context?: SiaxRequestContext,
|
||||
): Promise<Aud0OpenLineageAck>;
|
||||
ingestLineageEvent(event: Aud0LineageEvent, context?: SiaxRequestContext): Promise<Aud0LineageEvent>;
|
||||
}
|
||||
|
||||
export interface CreateAud0ClientOptions {
|
||||
token?: string;
|
||||
/** False only for the outbox dispatcher/raw diagnostics. Default true. */
|
||||
durable?: boolean;
|
||||
}
|
||||
|
||||
export function createAud0Client(baseUrl?: string, opts?: CreateAud0ClientOptions): Aud0Client {
|
||||
const resolved = resolveDependencyBaseUrl("aud0", baseUrl ?? process.env.AUD0_URL);
|
||||
const raw: Aud0Client = resolved
|
||||
? new HttpAud0Client(resolved, opts?.token ?? process.env.AUD0_SERVICE_TOKEN)
|
||||
: new NoopAud0Client();
|
||||
|
||||
if (opts?.durable === false) return raw;
|
||||
const outbox = createAud0OutboxRepositoryFromEnv();
|
||||
return outbox ? new DurableAud0Client(outbox) : raw;
|
||||
}
|
||||
|
||||
export function legacyLineageToOpenLineage(event: Aud0LineageEvent): OpenLineageRunEvent {
|
||||
return {
|
||||
eventType: "COMPLETE",
|
||||
eventTime: event.created_at,
|
||||
producer: "https://git.siax.io/sax3l/0pt",
|
||||
run: {
|
||||
runId: event.lineage_event_id,
|
||||
facets: {
|
||||
...(event.correlation_id ? { siaxCorrelation: { correlation_id: event.correlation_id } } : {}),
|
||||
siaxLegacyLineage: {
|
||||
lineage_type: event.lineage_type,
|
||||
capability_id: event.capability_id,
|
||||
project_id: event.project_id,
|
||||
...(event.metadata !== undefined ? { metadata: event.metadata } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
job: { namespace: event.app_id, name: event.capability_id },
|
||||
inputs: [{ namespace: event.app_id, name: `${event.source_type}/${event.source_id}` }],
|
||||
outputs: [{ namespace: event.app_id, name: `${event.target_type}/${event.target_id}` }],
|
||||
};
|
||||
}
|
||||
|
||||
class DurableAud0Client implements Aud0Client {
|
||||
constructor(private readonly outbox: Aud0OutboxRepository) {}
|
||||
|
||||
async ingestEvent(event: Aud0Event): Promise<Aud0Event> {
|
||||
await this.outbox.enqueueEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
async ingestOpenLineageEvent(
|
||||
tenantId: string,
|
||||
appId: string,
|
||||
event: OpenLineageRunEvent,
|
||||
): Promise<Aud0OpenLineageAck> {
|
||||
const row = await this.outbox.enqueueOpenLineage(tenantId, appId, event);
|
||||
return {
|
||||
tenant_id: tenantId,
|
||||
run_id: event.run.runId,
|
||||
job: `${event.job.namespace}/${event.job.name}`,
|
||||
event_id: `outbox:${row.outbox_id}`,
|
||||
};
|
||||
}
|
||||
|
||||
async ingestLineageEvent(event: Aud0LineageEvent): Promise<Aud0LineageEvent> {
|
||||
await this.ingestOpenLineageEvent(event.tenant_id, event.app_id, legacyLineageToOpenLineage(event));
|
||||
return event;
|
||||
}
|
||||
}
|
||||
|
||||
/** Non-production/env-less runtime fallback only. */
|
||||
class NoopAud0Client implements Aud0Client {
|
||||
async ingestEvent(event: Aud0Event): Promise<Aud0Event> {
|
||||
return event;
|
||||
}
|
||||
|
||||
async ingestOpenLineageEvent(
|
||||
tenantId: string,
|
||||
_appId: string,
|
||||
event: OpenLineageRunEvent,
|
||||
): Promise<Aud0OpenLineageAck> {
|
||||
return {
|
||||
tenant_id: tenantId,
|
||||
run_id: event.run.runId,
|
||||
job: `${event.job.namespace}/${event.job.name}`,
|
||||
event_id: `noop_${event.run.runId}`,
|
||||
};
|
||||
}
|
||||
|
||||
async ingestLineageEvent(event: Aud0LineageEvent): Promise<Aud0LineageEvent> {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
|
||||
class HttpAud0Client implements Aud0Client {
|
||||
private readonly http: SiaxHttp;
|
||||
|
||||
constructor(baseUrl: string, token?: string) {
|
||||
this.http = new SiaxHttp({ dependency: "aud0", baseUrl, token });
|
||||
}
|
||||
|
||||
async ingestEvent(event: Aud0Event, context?: SiaxRequestContext): Promise<Aud0Event> {
|
||||
const res = await this.http.request({
|
||||
method: "POST",
|
||||
path: "/v1/aud0/events",
|
||||
context,
|
||||
headers: { "X-Tenant-Id": event.tenant_id, "X-Actor-Id": event.actor_id },
|
||||
body: event,
|
||||
acceptStatuses: [200],
|
||||
});
|
||||
return (res.json ?? event) as Aud0Event;
|
||||
}
|
||||
|
||||
async ingestOpenLineageEvent(
|
||||
tenantId: string,
|
||||
appId: string,
|
||||
event: OpenLineageRunEvent,
|
||||
context?: SiaxRequestContext,
|
||||
): Promise<Aud0OpenLineageAck> {
|
||||
const res = await this.http.request({
|
||||
method: "POST",
|
||||
path: "/v1/aud0/openlineage",
|
||||
query: { tenant_id: tenantId, app_id: appId },
|
||||
context,
|
||||
headers: { "X-Tenant-Id": tenantId, "X-Actor-Id": appId },
|
||||
body: event,
|
||||
acceptStatuses: [200],
|
||||
});
|
||||
return (res.json ?? {
|
||||
tenant_id: tenantId,
|
||||
run_id: event.run.runId,
|
||||
job: `${event.job.namespace}/${event.job.name}`,
|
||||
event_id: "",
|
||||
}) as Aud0OpenLineageAck;
|
||||
}
|
||||
|
||||
async ingestLineageEvent(event: Aud0LineageEvent, context?: SiaxRequestContext): Promise<Aud0LineageEvent> {
|
||||
await this.ingestOpenLineageEvent(event.tenant_id, event.app_id, legacyLineageToOpenLineage(event), context);
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* src/clients/cl0ud-client.ts
|
||||
* ============================
|
||||
* 0pt's ONLY path to the CL0UD control-plane policy decision point.
|
||||
*
|
||||
* REWRITTEN 2026-08-31 against CL0UD's REAL wire contract (cl0ud main,
|
||||
* `packages/contract/openapi.yaml` + `apps/console/app/api/policy/evaluate/
|
||||
* route.ts`, verified this session):
|
||||
*
|
||||
* evaluatePolicy -> POST {baseUrl}/api/policy/evaluate
|
||||
* listCapabilities -> GET {baseUrl}/api/capabilities
|
||||
*
|
||||
* The earlier client POSTed snake_case to `/v1/cl0ud/policies/evaluate` — a
|
||||
* path that has never existed on CL0UD. That was exactly the MOCK_ONLY trap
|
||||
* the Master-DoD audit predicted: the mock worked, the HTTP path had never
|
||||
* been exercised against the real contract. The real contract is camelCase,
|
||||
* envelope `{ data, meta }`, decision ∈ {allow, deny} plus a separate
|
||||
* `requiresApproval` flag (allow+requiresApproval = route into approval, NOT
|
||||
* a deny). 0pt maps that pair onto its historical three-value
|
||||
* `PolicyDecisionValue` so existing call sites keep their exact semantics:
|
||||
* anything other than plain "allow" aborts the caller.
|
||||
*
|
||||
* Production fallback policy (Master-DoD §3/§10): `createCl0udClient()`
|
||||
* without a base URL THROWS `SiaxError("DEPENDENCY_UNAVAILABLE")` in a
|
||||
* production runtime (NODE_ENV=production). The allow-only local
|
||||
* pass-through survives ONLY for non-production runtimes (unit tests, local
|
||||
* dev) — it never invents a deny, and it stamps a clearly local decision id.
|
||||
* Policy itself remains fail-closed: a configured CL0UD answering 200 with a
|
||||
* body missing `decision` is read as deny, never allow.
|
||||
*/
|
||||
import crypto from "crypto";
|
||||
import { SiaxHttp } from "./http";
|
||||
import { resolveDependencyBaseUrl } from "../platform/dependency-mode";
|
||||
import type { SiaxRequestContext } from "../platform/siax-context";
|
||||
|
||||
/** The decision vocabulary 0pt call sites consume (unchanged). */
|
||||
export type PolicyDecisionValue = "allow" | "deny" | "approval_required";
|
||||
|
||||
export interface EvaluatePolicyInput {
|
||||
tenant_id: string;
|
||||
project_id: string;
|
||||
actor_id: string;
|
||||
capability_id: string;
|
||||
resource_type: string;
|
||||
resource_id: string;
|
||||
/** Risk level L0–L5 per the SIAX Cloud risk taxonomy. */
|
||||
risk_level: string;
|
||||
correlation_id?: string;
|
||||
/**
|
||||
* The CL0UD actor descriptor. 0pt calls CL0UD as a platform service, and
|
||||
* cl0ud's resolve-actor only lets an OPERATOR principal name an arbitrary
|
||||
* actor — default is therefore `{ kind: "operator", role: "member" }`.
|
||||
*/
|
||||
actor?: { kind: "customer" | "operator"; role: "owner" | "admin" | "member" | "viewer" };
|
||||
}
|
||||
|
||||
/** The decision record 0pt call sites consume (unchanged shape). */
|
||||
export interface PolicyDecision {
|
||||
decision: PolicyDecisionValue;
|
||||
decision_id: string;
|
||||
reason?: string;
|
||||
/** CL0UD's deny code when decision = "deny" (e.g. rbac_forbidden). */
|
||||
deny_code?: string;
|
||||
}
|
||||
|
||||
/** Alias so both historical import names resolve to the same shape. */
|
||||
export type PolicyResult = PolicyDecision;
|
||||
|
||||
/** One CL0UD capability-registry entry (discovery API, tolerant-reader subset). */
|
||||
export interface Cl0udCapability {
|
||||
name: string;
|
||||
version: string;
|
||||
owner: string;
|
||||
status?: "beta" | "active" | "deprecated" | "retired";
|
||||
deprecation?: { since: string; replacement?: string; sunsetAt?: string; note?: string };
|
||||
requiredEntitlement?: string;
|
||||
surfaces?: string[];
|
||||
[extra: string]: unknown;
|
||||
}
|
||||
|
||||
export interface Cl0udClient {
|
||||
evaluatePolicy(input: EvaluatePolicyInput, context?: SiaxRequestContext): Promise<PolicyDecision>;
|
||||
listCapabilities(
|
||||
filter?: { owner?: string; surface?: string; status?: string; version?: string },
|
||||
context?: SiaxRequestContext
|
||||
): Promise<Cl0udCapability[]>;
|
||||
}
|
||||
|
||||
export function createCl0udClient(baseUrl?: string, opts?: { token?: string }): Cl0udClient {
|
||||
const resolved = resolveDependencyBaseUrl("cl0ud", baseUrl ?? process.env.CL0UD_URL);
|
||||
if (!resolved) return new LocalAllowCl0udClient();
|
||||
return new HttpCl0udClient(resolved, opts?.token ?? process.env.CL0UD_SERVICE_TOKEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-production runtimes only (the factory has already thrown in
|
||||
* production): allow-only local pass-through, empty capability catalog.
|
||||
*/
|
||||
class LocalAllowCl0udClient implements Cl0udClient {
|
||||
async evaluatePolicy(_input: EvaluatePolicyInput): Promise<PolicyDecision> {
|
||||
return { decision: "allow", decision_id: `pdec_local_${crypto.randomUUID()}` };
|
||||
}
|
||||
async listCapabilities(): Promise<Cl0udCapability[]> {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
class HttpCl0udClient implements Cl0udClient {
|
||||
private readonly http: SiaxHttp;
|
||||
|
||||
constructor(baseUrl: string, token?: string) {
|
||||
this.http = new SiaxHttp({ dependency: "cl0ud", baseUrl, token });
|
||||
}
|
||||
|
||||
async evaluatePolicy(input: EvaluatePolicyInput, context?: SiaxRequestContext): Promise<PolicyDecision> {
|
||||
const res = await this.http.request({
|
||||
method: "POST",
|
||||
path: "/api/policy/evaluate",
|
||||
context,
|
||||
body: {
|
||||
capability: input.capability_id,
|
||||
actor: input.actor ?? { kind: "operator", role: "member" },
|
||||
tenantId: input.tenant_id,
|
||||
projectId: input.project_id,
|
||||
surface: "api",
|
||||
resource: { type: input.resource_type, id: input.resource_id },
|
||||
...(input.correlation_id ? { correlationId: input.correlation_id } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
const data = (res.json as { data?: Record<string, unknown> } | undefined)?.data;
|
||||
const rawDecision = data?.decision;
|
||||
// FAIL CLOSED: 200 with a missing/unknown decision is a deny, never allow.
|
||||
let decision: PolicyDecisionValue = "deny";
|
||||
if (rawDecision === "allow") {
|
||||
decision = data?.requiresApproval === true ? "approval_required" : "allow";
|
||||
} else if (rawDecision === "deny") {
|
||||
decision = "deny";
|
||||
}
|
||||
return {
|
||||
decision,
|
||||
decision_id:
|
||||
typeof data?.decisionId === "string" ? data.decisionId : `pdec_${crypto.randomUUID()}`,
|
||||
reason: typeof data?.reason === "string" ? data.reason : undefined,
|
||||
deny_code: typeof data?.denyCode === "string" ? data.denyCode : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async listCapabilities(
|
||||
filter?: { owner?: string; surface?: string; status?: string; version?: string },
|
||||
context?: SiaxRequestContext
|
||||
): Promise<Cl0udCapability[]> {
|
||||
const res = await this.http.request({
|
||||
method: "GET",
|
||||
path: "/api/capabilities",
|
||||
context,
|
||||
query: {
|
||||
owner: filter?.owner,
|
||||
surface: filter?.surface,
|
||||
status: filter?.status,
|
||||
version: filter?.version,
|
||||
},
|
||||
});
|
||||
const data = (res.json as { data?: unknown } | undefined)?.data;
|
||||
return Array.isArray(data) ? (data as Cl0udCapability[]) : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* src/clients/http.ts
|
||||
* ====================
|
||||
* Shared HTTP core for 0pt's four platform clients (cl0ud/st0re/n0d/aud0).
|
||||
* One place for the behaviours Master-DoD §6/§10 require of every
|
||||
* cross-product call:
|
||||
*
|
||||
* - request timeout (no hung platform call can wedge a capability),
|
||||
* - typed `SiaxError` mapping from upstream status codes (retryable vs
|
||||
* permanent explicit, correlation id carried, no raw upstream body leaked
|
||||
* into the error message),
|
||||
* - canonical SIAX context propagation headers (src/platform/siax-context.ts)
|
||||
* plus optional service `Authorization` bearer (never the end-user token),
|
||||
* - JSON body handling.
|
||||
*
|
||||
* Each client keeps its own wire mapping (the four dependencies genuinely
|
||||
* differ: ST0RE is camelCase + X-Tenant-Id/X-Actor-Id, AUD0 is snake_case,
|
||||
* CL0UD wraps in a `{ data, meta }` envelope, N0D is snake_case + 202) — this
|
||||
* module owns only the transport discipline they share.
|
||||
*/
|
||||
import { SiaxError, siaxErrorCodeForUpstreamStatus } from "../platform/errors";
|
||||
import { toPropagationHeaders, type SiaxRequestContext } from "../platform/siax-context";
|
||||
|
||||
export interface SiaxHttpOptions {
|
||||
/** Dependency name for error attribution, e.g. "st0re". */
|
||||
dependency: string;
|
||||
baseUrl: string;
|
||||
/** Service bearer token (machine identity). Optional — some deployments gate by network + headers. */
|
||||
token?: string;
|
||||
/** Per-request timeout in ms. Default 15_000. */
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface SiaxRequestOptions {
|
||||
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
||||
path: string;
|
||||
/** Query string parameters (skipped when undefined). */
|
||||
query?: Record<string, string | undefined>;
|
||||
body?: unknown;
|
||||
/** Canonical SIAX context — serialized to propagation headers when present. */
|
||||
context?: SiaxRequestContext;
|
||||
/** Extra headers (e.g. ST0RE's X-Idempotency-Key). Applied last. */
|
||||
headers?: Record<string, string>;
|
||||
/** Statuses the caller handles itself (returned, not thrown). */
|
||||
acceptStatuses?: number[];
|
||||
}
|
||||
|
||||
export interface SiaxHttpResponse {
|
||||
status: number;
|
||||
/** Parsed JSON body, or undefined when the body was empty/non-JSON. */
|
||||
json: unknown;
|
||||
}
|
||||
|
||||
export class SiaxHttp {
|
||||
private readonly dependency: string;
|
||||
private readonly baseUrl: string;
|
||||
private readonly token?: string;
|
||||
private readonly timeoutMs: number;
|
||||
|
||||
constructor(opts: SiaxHttpOptions) {
|
||||
this.dependency = opts.dependency;
|
||||
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
||||
this.token = opts.token;
|
||||
this.timeoutMs = opts.timeoutMs ?? 15_000;
|
||||
}
|
||||
|
||||
async request(opts: SiaxRequestOptions): Promise<SiaxHttpResponse> {
|
||||
const url = new URL(`${this.baseUrl}${opts.path}`);
|
||||
for (const [k, v] of Object.entries(opts.query ?? {})) {
|
||||
if (v !== undefined) url.searchParams.set(k, v);
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (this.token) headers["Authorization"] = `Bearer ${this.token}`;
|
||||
if (opts.context) Object.assign(headers, toPropagationHeaders(opts.context));
|
||||
Object.assign(headers, opts.headers ?? {});
|
||||
|
||||
const correlationId = opts.context?.correlationId;
|
||||
let res: Response;
|
||||
try {
|
||||
// NOTE: fetch is called with a STRING (not a URL object) so test fetch
|
||||
// stubs that inspect `url.includes(...)` keep working.
|
||||
res = await fetch(url.toString(), {
|
||||
method: opts.method,
|
||||
headers,
|
||||
body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
});
|
||||
} catch (cause) {
|
||||
// Network failure / timeout: the dependency is unavailable — retryable.
|
||||
throw new SiaxError(
|
||||
"DEPENDENCY_UNAVAILABLE",
|
||||
this.dependency,
|
||||
`${opts.method} ${opts.path} failed to reach ${this.dependency} (${cause instanceof Error ? cause.name : "fetch error"})`,
|
||||
{ correlationId, cause }
|
||||
);
|
||||
}
|
||||
|
||||
if (!res.ok && !(opts.acceptStatuses ?? []).includes(res.status)) {
|
||||
// Read the upstream machine-readable code when present, but never embed
|
||||
// the raw body in the error (§6: no sensitive internals).
|
||||
const upstream = (await res.json().catch(() => undefined)) as
|
||||
| { error?: { code?: string; message?: string } }
|
||||
| undefined;
|
||||
const upstreamCode = upstream?.error?.code;
|
||||
throw new SiaxError(
|
||||
siaxErrorCodeForUpstreamStatus(res.status),
|
||||
this.dependency,
|
||||
`${opts.method} ${opts.path} → HTTP ${res.status}${upstreamCode ? ` (${upstreamCode})` : ""}`,
|
||||
{ correlationId }
|
||||
);
|
||||
}
|
||||
|
||||
const json = (await res.json().catch(() => undefined)) as unknown;
|
||||
return { status: res.status, json };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
/**
|
||||
* src/clients/n0d-client.ts
|
||||
* ==========================
|
||||
* 0pt's ONLY path for REQUESTING heavy compute jobs from N0D (the Compute
|
||||
* OS). 0pt requests jobs and holds the returned `job_id`; it never executes
|
||||
* heavy work in-process and never owns N0D's scheduling decisions.
|
||||
*
|
||||
* REWRITTEN 2026-08-31 against N0D's REAL wire contract (sax3l/n0d branch
|
||||
* feat/siax-platforms-p0-compute-os, `src/api/schemas.ts` createJobSchema +
|
||||
* `src/api/mappers.ts` jobRecordToWire + `src/api/routes/job-lifecycle.ts`,
|
||||
* verified this session):
|
||||
*
|
||||
* createJob -> POST {baseUrl}/v1/n0d/jobs (202 Accepted)
|
||||
* runDataQuality -> POST {baseUrl}/v1/n0d/quality/run (202 Accepted)
|
||||
* getJob -> GET {baseUrl}/v1/n0d/jobs/:jobId
|
||||
* getJobResult -> GET {baseUrl}/v1/n0d/jobs/:jobId/result
|
||||
*
|
||||
* Real-contract facts encoded here:
|
||||
* - required create fields: job_type, capability_id, tenant_id,
|
||||
* required_role (enum), resource_requirements {cpu, memory_gb, disk_gb};
|
||||
* - idempotency is BODY-ONLY (`idempotency_key`; there is no
|
||||
* Idempotency-Key header on N0D) — same-tenant replay returns the
|
||||
* existing record, foreign-tenant probe is a 404 (no existence oracle);
|
||||
* - completion can be pushed as CloudEvents to `callback_url`
|
||||
* (io.siax.n0d.job.*.v1) or polled via getJob/getJobResult;
|
||||
* - the legacy fields this client used to send (`requested_by_app_id`,
|
||||
* `required_node_roles[]`, `resource_profile`, `output_artifact_type`,
|
||||
* `risk_level`) are NOT part of N0D's create schema. They remain
|
||||
* accepted on the 0pt-side input for call-site stability and are MAPPED
|
||||
* (documented per field below); tests/contracts/n0d-client.contract.test.ts
|
||||
* pins the wire shape.
|
||||
*
|
||||
* 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_job_") survives only
|
||||
* for non-production runtimes; it never runs anything.
|
||||
*/
|
||||
import crypto from "crypto";
|
||||
import { SiaxHttp } from "./http";
|
||||
import { resolveDependencyBaseUrl } from "../platform/dependency-mode";
|
||||
import type { SiaxRequestContext } from "../platform/siax-context";
|
||||
|
||||
/** N0D node roles (verbatim from n0d's createJobSchema). */
|
||||
export type N0dRequiredRole =
|
||||
| "control_plane"
|
||||
| "ai_gpu"
|
||||
| "compute_general"
|
||||
| "storage"
|
||||
| "shared_utility";
|
||||
|
||||
/** N0D resource requirements (verbatim from n0d's createJobSchema). */
|
||||
export interface N0dResourceRequirements {
|
||||
cpu: number;
|
||||
memory_gb: number;
|
||||
gpu?: number;
|
||||
vram_gb?: number;
|
||||
disk_gb: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Named resource profiles 0pt uses when a call site does not spell out raw
|
||||
* requirements. The mapping is 0pt-owned (N0D takes only raw numbers).
|
||||
*/
|
||||
export const N0D_RESOURCE_PROFILES: Readonly<Record<string, N0dResourceRequirements>> = {
|
||||
small: { cpu: 1, memory_gb: 2, gpu: 0, disk_gb: 5 },
|
||||
standard: { cpu: 2, memory_gb: 4, gpu: 0, disk_gb: 10 },
|
||||
large: { cpu: 8, memory_gb: 16, gpu: 0, disk_gb: 50 },
|
||||
gpu_standard: { cpu: 4, memory_gb: 16, gpu: 1, vram_gb: 16, disk_gb: 50 },
|
||||
};
|
||||
|
||||
export interface N0dCreateJobInput {
|
||||
tenant_id: string;
|
||||
project_id: string;
|
||||
job_type: string;
|
||||
capability_id: string;
|
||||
/** Mapped to wire `app_id`. */
|
||||
requested_by_app_id: string;
|
||||
/** Mapped to wire `requested_by`. */
|
||||
requested_by_actor_id: string;
|
||||
input_artifact_ids?: string[];
|
||||
/** NOT on N0D's wire contract; folded into input artifact ids by callers that need it. */
|
||||
input_dataset_ids?: string[];
|
||||
/** Mapped to wire `output_policy.artifact_type` (+ write_to_st0re: true). */
|
||||
output_artifact_type: string;
|
||||
/** Mapped to wire `requires_shared_backbone`. */
|
||||
requires_backbone: boolean;
|
||||
/** Drives the required_role default (ai_gpu when true) + resource profile default. */
|
||||
requires_gpu: boolean;
|
||||
/** Legacy multi-role list; first entry that matches N0D's enum wins as `required_role`. */
|
||||
required_node_roles: string[];
|
||||
/** Named profile resolved via {@link N0D_RESOURCE_PROFILES} unless resource_requirements given. */
|
||||
resource_profile: string;
|
||||
/** Risk level L0–L5. NOT on N0D's create schema (documented inert there); kept for 0pt audit emission. */
|
||||
risk_level: string;
|
||||
correlation_id?: string;
|
||||
/** Explicit raw requirements (wins over resource_profile). */
|
||||
resource_requirements?: N0dResourceRequirements;
|
||||
/** Explicit role (wins over required_node_roles/requires_gpu inference). */
|
||||
required_role?: N0dRequiredRole;
|
||||
priority?: "low" | "normal" | "high";
|
||||
timeout_seconds?: number;
|
||||
max_retries?: number;
|
||||
/** Body-only idempotency key (tenant-scoped on N0D's side). */
|
||||
idempotency_key?: string;
|
||||
/** CloudEvents completion callback URL (must be on N0D's callback allowlist). */
|
||||
callback_url?: string;
|
||||
}
|
||||
|
||||
/** Alias so both historical import names resolve to the same shape. */
|
||||
export type CreateJobInput = N0dCreateJobInput;
|
||||
|
||||
/** N0D's real 13-state job lifecycle (verbatim; no `succeeded` state exists). */
|
||||
export type N0dJobStatus =
|
||||
| "created"
|
||||
| "validated"
|
||||
| "queued"
|
||||
| "scheduled"
|
||||
| "running"
|
||||
| "retrying"
|
||||
| "waiting_for_capacity"
|
||||
| "waiting_for_approval"
|
||||
| "completed"
|
||||
| "completed_with_warnings"
|
||||
| "failed"
|
||||
| "cancelled"
|
||||
| "expired";
|
||||
|
||||
/** Alias kept for the older name used elsewhere in this repo's history. */
|
||||
export type N0dJobState = N0dJobStatus;
|
||||
|
||||
/** The wire job record (n0d jobRecordToWire; tolerant-reader subset). */
|
||||
export interface N0dJob {
|
||||
job_id: string;
|
||||
job_type: string;
|
||||
tenant_id: string;
|
||||
project_id?: string;
|
||||
status: N0dJobStatus;
|
||||
capability_id?: string;
|
||||
app_id?: string;
|
||||
requested_by?: string;
|
||||
resource_requirements?: N0dResourceRequirements;
|
||||
assigned_node_id?: string | null;
|
||||
placement_reason?: string | null;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
/** GET /v1/n0d/jobs/:id/result (n0d job-lifecycle.ts). */
|
||||
export interface N0dJobResult {
|
||||
job_id: string;
|
||||
run_id?: string;
|
||||
outcome?: "succeeded" | "failed" | "cancelled" | "expired";
|
||||
exit_code?: number | null;
|
||||
result?: unknown;
|
||||
error?: string | null;
|
||||
metrics?: Record<string, number>;
|
||||
completed_at?: string;
|
||||
input_artifacts?: { st0re_artifact_id: string; artifact_type?: string }[];
|
||||
output_artifacts?: { st0re_artifact_id: string; artifact_type?: string }[];
|
||||
}
|
||||
|
||||
/** Quality rule-set body for the N0D data-quality delegation (n0dRunDataQuality). */
|
||||
export interface RunDataQualityInput {
|
||||
tenant_id: string;
|
||||
dataset_id: string;
|
||||
quality_rule_set_id: string;
|
||||
project_id?: string;
|
||||
app_id?: string;
|
||||
requested_by?: string;
|
||||
run_inline?: {
|
||||
dataset_csv: string;
|
||||
rules: Record<string, unknown>[];
|
||||
};
|
||||
priority?: "low" | "normal" | "high";
|
||||
risk_level?: string;
|
||||
idempotency_key?: string;
|
||||
timeout_seconds?: number;
|
||||
max_retries?: number;
|
||||
callback_url?: string;
|
||||
}
|
||||
|
||||
export interface N0dClient {
|
||||
createJob(input: N0dCreateJobInput, context?: SiaxRequestContext): Promise<N0dJob>;
|
||||
runDataQuality(input: RunDataQualityInput, context?: SiaxRequestContext): Promise<N0dJob>;
|
||||
getJob(jobId: string, tenantId: string, context?: SiaxRequestContext): Promise<N0dJob>;
|
||||
getJobResult(jobId: string, tenantId: string, context?: SiaxRequestContext): Promise<N0dJobResult>;
|
||||
}
|
||||
|
||||
export function createN0dClient(baseUrl?: string, opts?: { token?: string }): N0dClient {
|
||||
const resolved = resolveDependencyBaseUrl("n0d", baseUrl ?? process.env.N0D_URL);
|
||||
if (!resolved) return new MockN0dClient();
|
||||
return new HttpN0dClient(resolved, opts?.token ?? process.env.N0D_SERVICE_TOKEN);
|
||||
}
|
||||
|
||||
const N0D_ROLE_VALUES: ReadonlySet<string> = new Set([
|
||||
"control_plane",
|
||||
"ai_gpu",
|
||||
"compute_general",
|
||||
"storage",
|
||||
"shared_utility",
|
||||
]);
|
||||
|
||||
/** Resolve the wire `required_role` from the richer 0pt-side input. */
|
||||
export function resolveRequiredRole(input: N0dCreateJobInput): N0dRequiredRole {
|
||||
if (input.required_role) return input.required_role;
|
||||
const legacy = input.required_node_roles.find((r) => N0D_ROLE_VALUES.has(r));
|
||||
if (legacy) return legacy as N0dRequiredRole;
|
||||
return input.requires_gpu ? "ai_gpu" : "compute_general";
|
||||
}
|
||||
|
||||
/** Resolve the wire `resource_requirements` from the richer 0pt-side input. */
|
||||
export function resolveResourceRequirements(input: N0dCreateJobInput): N0dResourceRequirements {
|
||||
if (input.resource_requirements) return input.resource_requirements;
|
||||
const profile = N0D_RESOURCE_PROFILES[input.resource_profile];
|
||||
if (profile) return input.requires_gpu && !profile.gpu ? N0D_RESOURCE_PROFILES.gpu_standard : profile;
|
||||
return input.requires_gpu ? N0D_RESOURCE_PROFILES.gpu_standard : N0D_RESOURCE_PROFILES.standard;
|
||||
}
|
||||
|
||||
/** Non-production runtimes only: deterministic mock job; runs nothing. */
|
||||
class MockN0dClient implements N0dClient {
|
||||
private readonly jobs = new Map<string, N0dJob>();
|
||||
|
||||
async createJob(input: N0dCreateJobInput): Promise<N0dJob> {
|
||||
const job: N0dJob = {
|
||||
job_id: `mock_job_${crypto.randomUUID()}`,
|
||||
job_type: input.job_type,
|
||||
tenant_id: input.tenant_id,
|
||||
project_id: input.project_id,
|
||||
capability_id: input.capability_id,
|
||||
app_id: input.requested_by_app_id,
|
||||
requested_by: input.requested_by_actor_id,
|
||||
resource_requirements: resolveResourceRequirements(input),
|
||||
status: "queued",
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
this.jobs.set(job.job_id, job);
|
||||
return job;
|
||||
}
|
||||
|
||||
async getJob(jobId: string, tenantId: string): Promise<N0dJob> {
|
||||
const job = this.jobs.get(jobId);
|
||||
if (!job || job.tenant_id !== tenantId) {
|
||||
throw new Error(`mock N0D: job ${jobId} not found`);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
async getJobResult(jobId: string, tenantId: string): Promise<N0dJobResult> {
|
||||
await this.getJob(jobId, tenantId);
|
||||
throw new Error(`mock N0D: job ${jobId} has no result (mock jobs never run)`);
|
||||
}
|
||||
|
||||
async runDataQuality(input: RunDataQualityInput): Promise<N0dJob> {
|
||||
const job: N0dJob = {
|
||||
job_id: `mock_job_${crypto.randomUUID()}`,
|
||||
job_type: "0pt.data_quality_job",
|
||||
tenant_id: input.tenant_id,
|
||||
project_id: input.project_id,
|
||||
capability_id: "0pt.quality.run.v1",
|
||||
app_id: input.app_id ?? input.requested_by ?? "0pt",
|
||||
requested_by: input.requested_by ?? "svc_0pt",
|
||||
resource_requirements: { cpu: 2, memory_gb: 4, gpu: 0, disk_gb: 10 },
|
||||
status: "queued",
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
this.jobs.set(job.job_id, job);
|
||||
return job;
|
||||
}
|
||||
}
|
||||
|
||||
class HttpN0dClient implements N0dClient {
|
||||
private readonly http: SiaxHttp;
|
||||
|
||||
constructor(baseUrl: string, token?: string) {
|
||||
this.http = new SiaxHttp({ dependency: "n0d", baseUrl, token });
|
||||
}
|
||||
|
||||
async createJob(input: N0dCreateJobInput, context?: SiaxRequestContext): Promise<N0dJob> {
|
||||
const res = await this.http.request({
|
||||
method: "POST",
|
||||
path: "/v1/n0d/jobs",
|
||||
context,
|
||||
headers: { "X-Tenant-Id": input.tenant_id },
|
||||
body: {
|
||||
job_type: input.job_type,
|
||||
capability_id: input.capability_id,
|
||||
tenant_id: input.tenant_id,
|
||||
project_id: input.project_id,
|
||||
app_id: input.requested_by_app_id,
|
||||
requested_by: input.requested_by_actor_id,
|
||||
required_role: resolveRequiredRole(input),
|
||||
resource_requirements: resolveResourceRequirements(input),
|
||||
priority: input.priority ?? "normal",
|
||||
requires_shared_backbone: input.requires_backbone,
|
||||
...(input.input_artifact_ids?.length ? { input: { artifact_ids: input.input_artifact_ids } } : {}),
|
||||
output_policy: { write_to_st0re: true, artifact_type: input.output_artifact_type },
|
||||
...(input.timeout_seconds ? { timeout_seconds: input.timeout_seconds } : {}),
|
||||
...(input.max_retries !== undefined ? { max_retries: input.max_retries } : {}),
|
||||
...(input.idempotency_key ? { idempotency_key: input.idempotency_key } : {}),
|
||||
...(input.callback_url ? { callback_url: input.callback_url } : {}),
|
||||
...(input.correlation_id ? { correlation_id: input.correlation_id } : {}),
|
||||
},
|
||||
acceptStatuses: [202],
|
||||
});
|
||||
return (res.json ?? {}) as N0dJob;
|
||||
}
|
||||
|
||||
async runDataQuality(input: RunDataQualityInput, context?: SiaxRequestContext): Promise<N0dJob> {
|
||||
const res = await this.http.request({
|
||||
method: "POST",
|
||||
path: "/v1/n0d/quality/run",
|
||||
context,
|
||||
headers: { "X-Tenant-Id": input.tenant_id },
|
||||
body: {
|
||||
tenant_id: input.tenant_id,
|
||||
project_id: input.project_id,
|
||||
dataset_id: input.dataset_id,
|
||||
quality_rule_set_id: input.quality_rule_set_id,
|
||||
run_inline: input.run_inline,
|
||||
app_id: input.app_id,
|
||||
requested_by: input.requested_by,
|
||||
priority: input.priority ?? "normal",
|
||||
risk_level: input.risk_level ?? "L2",
|
||||
requires_shared_backbone: false,
|
||||
...(input.idempotency_key ? { idempotency_key: input.idempotency_key } : {}),
|
||||
...(input.timeout_seconds ? { timeout_seconds: input.timeout_seconds } : {}),
|
||||
...(input.max_retries !== undefined ? { max_retries: input.max_retries } : {}),
|
||||
...(input.callback_url ? { callback_url: input.callback_url } : {}),
|
||||
},
|
||||
acceptStatuses: [202],
|
||||
});
|
||||
return (res.json ?? {}) as N0dJob;
|
||||
}
|
||||
|
||||
async getJob(jobId: string, tenantId: string, context?: SiaxRequestContext): Promise<N0dJob> {
|
||||
const res = await this.http.request({
|
||||
method: "GET",
|
||||
path: `/v1/n0d/jobs/${encodeURIComponent(jobId)}`,
|
||||
context,
|
||||
headers: { "X-Tenant-Id": tenantId },
|
||||
});
|
||||
return (res.json ?? {}) as N0dJob;
|
||||
}
|
||||
|
||||
async getJobResult(jobId: string, tenantId: string, context?: SiaxRequestContext): Promise<N0dJobResult> {
|
||||
const res = await this.http.request({
|
||||
method: "GET",
|
||||
path: `/v1/n0d/jobs/${encodeURIComponent(jobId)}/result`,
|
||||
context,
|
||||
headers: { "X-Tenant-Id": tenantId },
|
||||
});
|
||||
return (res.json ?? {}) as N0dJobResult;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* 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(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
// ST0RE lakehouse client -- 0pt's ONLY path for writing Iceberg table/
|
||||
// snapshot state. 0pt must never persist lakehouse table/catalog/snapshot
|
||||
// state anywhere else (see docs/ICEBERG_WRITE_BOUNDARY.md).
|
||||
//
|
||||
// Distinct from `./st0re-client.ts` (the generic Artifact registry client,
|
||||
// snake_case request shape) because it targets a different, newer route
|
||||
// family on the SAME ST0RE service: `/v1/st0re/lakehouse/*`
|
||||
// (sax3l/st0re `src/api/routes/lakehouse.ts`, commit 9ea0abb). That route
|
||||
// family's Fastify handlers parse camelCase JSON bodies matching ST0RE's own
|
||||
// `IcebergTableInput`/`TableSnapshotInput`/`LakehouseNamespaceInput` types
|
||||
// (sax3l/st0re `src/types.ts`) -- this client's request/response shapes are
|
||||
// camelCase deliberately, to match ST0RE's real contract byte-for-byte
|
||||
// rather than 0pt's own snake_case domain convention. The service layer
|
||||
// (`src/services/dataset-iceberg-mapping-service.ts`,
|
||||
// `src/services/iceberg-write-service.ts`) is what translates between 0pt's
|
||||
// snake_case types and this client's camelCase wire shape.
|
||||
//
|
||||
// LIVE-VERIFIED this session (2026-07-13): a prior 0pt pass left an honest
|
||||
// "not live-verified, no reachable ST0RE_URL" caveat here. This session
|
||||
// found `api.st0re.siax.io` IS reachable from this environment (resolves to
|
||||
// 188.40.230.69) and used curl, then this repo's own updated client/service
|
||||
// code, to drive a real namespace -> table -> snapshot write against
|
||||
// production ST0RE. That surfaced three real contract facts this
|
||||
// client/service pair had wrong or missing, which would have made live calls
|
||||
// fail or misbehave:
|
||||
// 1. ST0RE's Fastify routes require `X-Tenant-Id` + `X-Actor-Id` request
|
||||
// headers on EVERY lakehouse route (namespaces/tables/snapshots, GET and
|
||||
// POST alike) -- confirmed via a live 400
|
||||
// `ST0RE_VALIDATION_ERROR: Missing required header(s)`. The previous
|
||||
// version of `HttpSt0reLakehouseClient` sent no headers at all. Fixed
|
||||
// below by threading a `St0reRequestContext { tenantId, actorId }`
|
||||
// through every method.
|
||||
// 2. `IcebergTableInput.datasetId` is a foreign key into ST0RE's OWN
|
||||
// dataset/artifact table (`st0re_iceberg_tables_dataset_id_fkey`), not a
|
||||
// free-form string -- passing 0pt's own `dataset_id` (which is never a
|
||||
// row in ST0RE's dataset table) fails live with
|
||||
// `insert or update on table "st0re_iceberg_tables" violates foreign key
|
||||
// constraint`. Fixed in `iceberg-write-service.ts`: `datasetId` is no
|
||||
// longer sent; 0pt's dataset<->table linkage lives entirely in 0pt's own
|
||||
// `DatasetIcebergMapping` row (`iceberg_table_id` pointing at ST0RE),
|
||||
// never in ST0RE's optional `datasetId` field.
|
||||
// 3. ST0RE enforces a real UNIQUE constraint on lakehouse namespaces
|
||||
// (`(tenant_id, project_id, name)`) -- registering the same namespace
|
||||
// name twice 400s with `duplicate key value violates unique constraint
|
||||
// "st0re_lakehouse_namespaces_tenant_id_project_id_name_key"`. There is
|
||||
// no upsert route. Fixed via `listNamespaces` + client-side
|
||||
// lookup-or-create in `IcebergWriteService.mapDatasetToIcebergTable`
|
||||
// (necessary because finding #4 below means server-side filtering can't
|
||||
// be trusted either).
|
||||
// Findings validated against the real, live ST0RE deployment (not just
|
||||
// reasoned about) -- see docs/ICEBERG_WRITE_BOUNDARY.md's "Live verification"
|
||||
// section for the actual namespaceId/tableId/snapshotId this session
|
||||
// created. This client still falls back to a deterministic in-memory mock
|
||||
// when no base URL is configured (same convention as
|
||||
// `cl0ud-client.ts`/`aud0-client.ts`/`n0d-client.ts`/`st0re-client.ts`), so
|
||||
// unit tests remain fast and hermetic; only the explicit live-integration
|
||||
// test (`tests/p0/iceberg-write-service.realinfra.test.ts`) exercises the
|
||||
// HTTP path, and it skips honestly if ST0RE is not reachable when it runs.
|
||||
//
|
||||
// Separately noted, NOT fixed here (out of scope -- ST0RE-repo bugs, not
|
||||
// 0pt ones):
|
||||
// 4. `GET /v1/st0re/lakehouse/namespaces` ignores query-string filters
|
||||
// (`?name=...` has no effect) AND returns every tenant's namespaces
|
||||
// regardless of the caller's `X-Tenant-Id` header -- live-verified by
|
||||
// querying as tenant A and receiving tenant B's rows back too.
|
||||
// 5. `GET /v1/st0re/lakehouse/tables/:tableId` returned a table's data even
|
||||
// when `X-Tenant-Id` did not match the table's own `tenantId` (tested
|
||||
// live with a deliberately wrong tenant header).
|
||||
// Both #4 and #5 look like a missing tenant-scoping check on ST0RE's
|
||||
// lakehouse read paths (cross-tenant data exposure). Flagged, not silently
|
||||
// ignored or worked around by trusting the server -- this client filters
|
||||
// `listNamespaces` results client-side precisely because #4 means the server
|
||||
// response can't be trusted as already scoped.
|
||||
|
||||
export type IcebergTableFormat = "iceberg" | "delta" | "hudi";
|
||||
export type LakehouseObjectStatus = "active" | "deprecated" | "archived";
|
||||
export type TableSnapshotType = "append" | "overwrite" | "delete" | "replace" | "schema_change" | "compaction";
|
||||
|
||||
export interface St0reLakehouseNamespaceInput {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
name: string;
|
||||
ownerProduct: string;
|
||||
}
|
||||
|
||||
export interface St0reLakehouseNamespace extends St0reLakehouseNamespaceInput {
|
||||
namespaceId: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface St0reIcebergTableInput {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
namespace: string;
|
||||
tableName: string;
|
||||
tableFormat: IcebergTableFormat;
|
||||
storageUri: string;
|
||||
/** Opaque reference into the external Iceberg catalog -- ST0RE does not resolve it. */
|
||||
catalogRef: string;
|
||||
datasetId?: string;
|
||||
ownerProduct: string;
|
||||
schemaId?: string;
|
||||
partitionSpec?: readonly string[];
|
||||
retentionPolicy?: string;
|
||||
dataResidency?: string;
|
||||
piiLevel?: "none" | "low" | "medium" | "high";
|
||||
createdBy: string;
|
||||
}
|
||||
|
||||
export interface St0reIcebergTable extends St0reIcebergTableInput {
|
||||
tableId: string;
|
||||
currentSnapshotId?: string;
|
||||
status: LakehouseObjectStatus;
|
||||
createdAt: number;
|
||||
artifactId?: string;
|
||||
}
|
||||
|
||||
export interface St0reTableSnapshotInput {
|
||||
snapshotType: TableSnapshotType;
|
||||
schemaVersion: string;
|
||||
/** URI of the Iceberg manifest list/file for this snapshot -- 0pt/N0D writes the actual bytes; ST0RE only tracks the pointer. */
|
||||
manifestUri: string;
|
||||
createdByJobId?: string;
|
||||
createdByCapability?: string;
|
||||
recordCount?: number;
|
||||
sizeBytes?: number;
|
||||
aud0EventId?: string;
|
||||
}
|
||||
|
||||
export interface St0reTableSnapshot extends St0reTableSnapshotInput {
|
||||
snapshotId: string;
|
||||
tableId: string;
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
/** ST0RE requires X-Tenant-Id/X-Actor-Id on every /v1/st0re/lakehouse/* request (live-verified). */
|
||||
export interface St0reRequestContext {
|
||||
tenantId: string;
|
||||
actorId: string;
|
||||
}
|
||||
|
||||
export interface St0reLakehouseClient {
|
||||
registerNamespace(input: St0reLakehouseNamespaceInput, ctx: St0reRequestContext): Promise<St0reLakehouseNamespace>;
|
||||
/**
|
||||
* Lists namespaces. Live-verified 2026-07-13: ST0RE's GET
|
||||
* /v1/st0re/lakehouse/namespaces ignores query-string filters AND does not
|
||||
* scope the result to the caller's X-Tenant-Id header -- it returns every
|
||||
* tenant's namespaces regardless. Callers MUST filter the result
|
||||
* client-side (see `IcebergWriteService.findOrRegisterNamespace`); do not
|
||||
* trust this to already be scoped. Flagged as a likely ST0RE-side bug, not
|
||||
* fixed here (out of scope for this repo).
|
||||
*/
|
||||
listNamespaces(ctx: St0reRequestContext): Promise<St0reLakehouseNamespace[]>;
|
||||
registerTable(input: St0reIcebergTableInput, ctx: St0reRequestContext): Promise<St0reIcebergTable>;
|
||||
getTable(tableId: string, ctx: St0reRequestContext): Promise<St0reIcebergTable>;
|
||||
createSnapshot(tableId: string, input: St0reTableSnapshotInput, ctx: St0reRequestContext): Promise<St0reTableSnapshot>;
|
||||
}
|
||||
|
||||
export function createSt0reLakehouseClient(baseUrl?: string): St0reLakehouseClient {
|
||||
if (!baseUrl) return new MockSt0reLakehouseClient();
|
||||
return new HttpSt0reLakehouseClient(baseUrl);
|
||||
}
|
||||
|
||||
class MockSt0reLakehouseClient implements St0reLakehouseClient {
|
||||
private tables: Map<string, St0reIcebergTable> = new Map();
|
||||
private namespaces: St0reLakehouseNamespace[] = [];
|
||||
|
||||
async registerNamespace(input: St0reLakehouseNamespaceInput, _ctx: St0reRequestContext): Promise<St0reLakehouseNamespace> {
|
||||
// Mirrors ST0RE's real unique constraint on (tenantId, projectId, name),
|
||||
// live-verified 2026-07-13, so mock-backed tests exercise the same
|
||||
// lookup-or-create behavior the HTTP client needs.
|
||||
const existing = this.namespaces.find(
|
||||
(n) => n.tenantId === input.tenantId && n.projectId === input.projectId && n.name === input.name
|
||||
);
|
||||
if (existing) throw new Error(`ST0RE mock: duplicate key value violates unique constraint (namespace ${input.name} already exists)`);
|
||||
const namespace: St0reLakehouseNamespace = { ...input, namespaceId: `mock_ns_${Date.now()}_${this.namespaces.length}`, createdAt: Date.now() };
|
||||
this.namespaces.push(namespace);
|
||||
return namespace;
|
||||
}
|
||||
|
||||
async listNamespaces(_ctx: St0reRequestContext): Promise<St0reLakehouseNamespace[]> {
|
||||
return [...this.namespaces];
|
||||
}
|
||||
|
||||
async registerTable(input: St0reIcebergTableInput, _ctx: St0reRequestContext): Promise<St0reIcebergTable> {
|
||||
const table: St0reIcebergTable = {
|
||||
...input,
|
||||
tableId: `mock_table_${Date.now()}`,
|
||||
status: "active",
|
||||
piiLevel: input.piiLevel ?? "none",
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
this.tables.set(table.tableId, table);
|
||||
return table;
|
||||
}
|
||||
|
||||
async getTable(tableId: string, _ctx: St0reRequestContext): Promise<St0reIcebergTable> {
|
||||
const table = this.tables.get(tableId);
|
||||
if (!table) throw new Error(`ST0RE mock: table ${tableId} not found`);
|
||||
return table;
|
||||
}
|
||||
|
||||
async createSnapshot(tableId: string, input: St0reTableSnapshotInput, _ctx: St0reRequestContext): Promise<St0reTableSnapshot> {
|
||||
const table = this.tables.get(tableId);
|
||||
const snapshotId = `mock_snapshot_${Date.now()}`;
|
||||
if (table) table.currentSnapshotId = snapshotId;
|
||||
return {
|
||||
...input,
|
||||
snapshotId,
|
||||
tableId,
|
||||
tenantId: table?.tenantId ?? "unknown",
|
||||
projectId: table?.projectId ?? "unknown",
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class HttpSt0reLakehouseClient implements St0reLakehouseClient {
|
||||
constructor(private baseUrl: string) {}
|
||||
|
||||
private headers(ctx: St0reRequestContext): Record<string, string> {
|
||||
// Required on every /v1/st0re/lakehouse/* route -- live-verified 2026-07-13
|
||||
// (a request with no headers 400s: "Missing required header(s): X-Tenant-Id, X-Actor-Id").
|
||||
return {
|
||||
"Content-Type": "application/json",
|
||||
"X-Tenant-Id": ctx.tenantId,
|
||||
"X-Actor-Id": ctx.actorId,
|
||||
};
|
||||
}
|
||||
|
||||
async registerNamespace(input: St0reLakehouseNamespaceInput, ctx: St0reRequestContext): Promise<St0reLakehouseNamespace> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/st0re/lakehouse/namespaces`, {
|
||||
method: "POST",
|
||||
headers: this.headers(ctx),
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
if (!res.ok) throw new Error(`ST0RE lakehouse namespace error: ${res.status} ${await res.text().catch(() => "")}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async listNamespaces(ctx: St0reRequestContext): Promise<St0reLakehouseNamespace[]> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/st0re/lakehouse/namespaces`, {
|
||||
headers: this.headers(ctx),
|
||||
});
|
||||
if (!res.ok) throw new Error(`ST0RE lakehouse list-namespaces error: ${res.status} ${await res.text().catch(() => "")}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async registerTable(input: St0reIcebergTableInput, ctx: St0reRequestContext): Promise<St0reIcebergTable> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/st0re/lakehouse/tables`, {
|
||||
method: "POST",
|
||||
headers: this.headers(ctx),
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
if (!res.ok) throw new Error(`ST0RE lakehouse table error: ${res.status} ${await res.text().catch(() => "")}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async getTable(tableId: string, ctx: St0reRequestContext): Promise<St0reIcebergTable> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/st0re/lakehouse/tables/${tableId}`, {
|
||||
headers: this.headers(ctx),
|
||||
});
|
||||
if (!res.ok) throw new Error(`ST0RE lakehouse get-table error: ${res.status} ${await res.text().catch(() => "")}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async createSnapshot(tableId: string, input: St0reTableSnapshotInput, ctx: St0reRequestContext): Promise<St0reTableSnapshot> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/st0re/lakehouse/tables/${tableId}/snapshots`, {
|
||||
method: "POST",
|
||||
headers: this.headers(ctx),
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
if (!res.ok) throw new Error(`ST0RE lakehouse snapshot error: ${res.status} ${await res.text().catch(() => "")}`);
|
||||
return res.json();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user