fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
@@ -0,0 +1,232 @@
/**
* src/repositories/canonical-fact-repository.ts
* =============================================
* Storage seam for 0pt canonical entities/facts/relations (sql/022).
* Same split as source-repository.ts: one interface, an in-memory
* implementation (dev/test) and a Postgres implementation (production),
* chosen once via resolveStoreMode.
*
* Tenant isolation is enforced by the service + route AND by RLS in Postgres
* (transaction-local GUC `app.opt_canonical_tenant_id`, same pattern as
* 019_document_credit_rls.sql). The in-memory backend scopes by tenant_id in
* every read/write.
*/
import { randomUUID } from "crypto";
import { resolveStoreMode } from "../platform/dependency-mode";
import type {
CanonicalEntity,
CanonicalEntityInput,
CanonicalFact,
CanonicalFactInput,
CanonicalQuery,
CanonicalRelationInput,
} from "../types/canonical-facts";
import { getRepositorySql, repositoryDatabaseUrl, type RepositorySql } from "./db";
export interface CanonicalFactRepository {
upsertEntities(tenantId: string, inputs: CanonicalEntityInput[]): Promise<CanonicalEntity[]>;
insertFacts(tenantId: string, inputs: CanonicalFactInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }>;
insertRelations(tenantId: string, inputs: CanonicalRelationInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }>;
queryFacts(query: CanonicalQuery): Promise<CanonicalFact[]>;
}
/** PostgreSQL timestamptz arrives as Date; the API contract is RFC3339/ISO-8601. */
function iso(value: unknown): string {
return value instanceof Date ? value.toISOString() : String(value);
}
export function entityKey(e: CanonicalEntityInput): string {
return `${e.entity_type}\u0000${e.identity_namespace}\u0000${e.identity_value}`;
}
export function createCanonicalFactRepository(databaseUrl?: string): CanonicalFactRepository {
const mode = resolveStoreMode("0pt.canonical_facts", databaseUrl ?? repositoryDatabaseUrl());
if (mode.mode === "postgres") {
return new PostgresCanonicalFactRepository(getRepositorySql(mode.url));
}
return new InMemoryCanonicalFactRepository();
}
// ── in-memory (dev/test) ────────────────────────────────────────────────────
class InMemoryCanonicalFactRepository implements CanonicalFactRepository {
private entities = new Map<string, CanonicalEntity>();
private facts = new Map<string, CanonicalFact>();
async upsertEntities(tenantId: string, inputs: CanonicalEntityInput[]): Promise<CanonicalEntity[]> {
const now = new Date().toISOString();
return inputs.map((input) => {
const key = `${tenantId}\u0000${entityKey(input)}`;
const existing = this.entities.get(key);
if (existing) return existing;
const entity: CanonicalEntity = {
...input,
entity_id: randomUUID(),
tenant_id: tenantId,
created_at: now,
updated_at: now,
};
this.entities.set(key, entity);
return entity;
});
}
async insertFacts(tenantId: string, inputs: CanonicalFactInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }> {
let inserted = 0;
let duplicates = 0;
for (const input of inputs) {
const entityId = entityIds.get(entityKey(input.entity));
if (!entityId) continue;
const key = `${tenantId}\u0000${entityId}\u0000${input.predicate}\u0000${input.source_ref}\u0000${input.observed_at}`;
if (this.facts.has(key)) {
duplicates += 1;
continue;
}
this.facts.set(key, {
...input,
fact_id: randomUUID(),
tenant_id: tenantId,
entity_id: entityId,
created_at: new Date().toISOString(),
});
inserted += 1;
}
return { inserted, duplicates };
}
async insertRelations(): Promise<{ inserted: number; duplicates: number }> {
// Relations are not persisted in the in-memory backend beyond validation;
// tests assert the write path through facts + counts.
return { inserted: 0, duplicates: 0 };
}
async queryFacts(query: CanonicalQuery): Promise<CanonicalFact[]> {
const limit = query.limit ?? 100;
return [...this.facts.values()]
.filter((f) => f.tenant_id === query.tenant_id)
.filter((f) => (query.entity_id ? f.entity_id === query.entity_id : true))
.filter((f) => (query.predicate ? f.predicate === query.predicate : true))
.slice(0, limit);
}
}
// ── postgres (production) ───────────────────────────────────────────────────
class PostgresCanonicalFactRepository implements CanonicalFactRepository {
constructor(private readonly sql: RepositorySql) {}
private async tx<T>(tenantId: string, fn: (tx: RepositorySql) => Promise<T>): Promise<T> {
return this.sql.begin(async (tx) => {
await tx`SELECT set_config('app.opt_canonical_tenant_id', ${tenantId}, true)`;
return fn(tx as unknown as RepositorySql);
}) as Promise<T>;
}
async upsertEntities(tenantId: string, inputs: CanonicalEntityInput[]): Promise<CanonicalEntity[]> {
if (inputs.length === 0) return [];
return this.tx(tenantId, async (tx) => {
const out: CanonicalEntity[] = [];
for (const input of inputs) {
const rows = await tx`
INSERT INTO opt_canonical_entities (entity_id, tenant_id, entity_type, identity_namespace, identity_value)
VALUES (${randomUUID()}, ${tenantId}, ${input.entity_type}, ${input.identity_namespace}, ${input.identity_value})
ON CONFLICT (tenant_id, entity_type, identity_namespace, identity_value)
DO UPDATE SET updated_at = now()
RETURNING entity_id, tenant_id, entity_type, identity_namespace, identity_value, created_at, updated_at`;
const r = rows[0];
out.push({
entity_id: r.entity_id, tenant_id: r.tenant_id, entity_type: r.entity_type,
identity_namespace: r.identity_namespace, identity_value: r.identity_value,
created_at: String(r.created_at), updated_at: String(r.updated_at),
});
}
return out;
});
}
async insertFacts(tenantId: string, inputs: CanonicalFactInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }> {
if (inputs.length === 0) return { inserted: 0, duplicates: 0 };
return this.tx(tenantId, async (tx) => {
let inserted = 0;
for (const input of inputs) {
const entityId = entityIds.get(entityKey(input.entity));
if (!entityId) continue;
const rows = await tx`
INSERT INTO opt_canonical_facts (
fact_id, tenant_id, entity_id, predicate, value_json, value_type, value_unit,
source_ref, source_record_id, st0re_artifact_id, aud0_evidence_ref, run_ref,
extractor_version, observed_at, valid_from, valid_to, confidence, quality_status, status
) VALUES (
${randomUUID()}, ${tenantId}, ${entityId}, ${input.predicate}, ${JSON.stringify(input.value)}::jsonb,
${input.value_type ?? "json"}, ${input.value_unit ?? null}, ${input.source_ref},
${input.source_record_id ?? null}, ${input.st0re_artifact_id ?? null},
${input.aud0_evidence_ref ?? null}, ${input.run_ref ?? null}, ${input.extractor_version},
${input.observed_at}, ${input.valid_from ?? null}, ${input.valid_to ?? null},
${input.confidence ?? null}, ${input.quality_status ?? "unvalidated"}, ${input.status ?? "observed"}
)
ON CONFLICT (tenant_id, entity_id, predicate, source_ref, observed_at) DO NOTHING
RETURNING fact_id`;
if (rows.length > 0) inserted += 1;
}
return { inserted, duplicates: inputs.length - inserted };
});
}
async insertRelations(tenantId: string, inputs: CanonicalRelationInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }> {
if (inputs.length === 0) return { inserted: 0, duplicates: 0 };
return this.tx(tenantId, async (tx) => {
let inserted = 0;
for (const input of inputs) {
const subjectId = entityIds.get(entityKey(input.subject));
const objectId = entityIds.get(entityKey(input.object));
if (!subjectId || !objectId) continue;
const rows = await tx`
INSERT INTO opt_canonical_relations (
relation_id, tenant_id, subject_id, predicate, object_id, attributes_json,
source_ref, st0re_artifact_id, aud0_evidence_ref, run_ref, extractor_version,
observed_at, valid_from, valid_to, confidence
) VALUES (
${randomUUID()}, ${tenantId}, ${subjectId}, ${input.predicate}, ${objectId},
${JSON.stringify(input.attributes ?? {})}::jsonb, ${input.source_ref},
${input.st0re_artifact_id ?? null}, ${input.aud0_evidence_ref ?? null},
${input.run_ref ?? null}, ${input.extractor_version}, ${input.observed_at},
${input.valid_from ?? null}, ${input.valid_to ?? null}, ${input.confidence ?? null}
)
ON CONFLICT (tenant_id, subject_id, predicate, object_id, source_ref, observed_at) DO NOTHING
RETURNING relation_id`;
if (rows.length > 0) inserted += 1;
}
return { inserted, duplicates: inputs.length - inserted };
});
}
async queryFacts(query: CanonicalQuery): Promise<CanonicalFact[]> {
const limit = query.limit ?? 100;
return this.tx(query.tenant_id, async (tx) => {
const rows = await tx`
SELECT f.*, e.entity_type, e.identity_namespace, e.identity_value
FROM opt_canonical_facts f
JOIN opt_canonical_entities e ON e.entity_id = f.entity_id
WHERE f.tenant_id = ${query.tenant_id}
${query.entity_id ? tx`AND f.entity_id = ${query.entity_id}` : tx``}
${query.predicate ? tx`AND f.predicate = ${query.predicate}` : tx``}
${query.entity_type ? tx`AND e.entity_type = ${query.entity_type}` : tx``}
${query.identity_namespace ? tx`AND e.identity_namespace = ${query.identity_namespace}` : tx``}
${query.identity_value ? tx`AND e.identity_value = ${query.identity_value}` : tx``}
ORDER BY f.observed_at DESC
LIMIT ${limit}`;
return rows.map((r) => ({
fact_id: r.fact_id, tenant_id: r.tenant_id, entity_id: r.entity_id,
entity: { entity_type: r.entity_type, identity_namespace: r.identity_namespace, identity_value: r.identity_value },
predicate: r.predicate, value: r.value_json, value_type: r.value_type,
value_unit: r.value_unit ?? undefined, source_ref: r.source_ref,
source_record_id: r.source_record_id ?? undefined,
st0re_artifact_id: r.st0re_artifact_id ?? undefined,
aud0_evidence_ref: r.aud0_evidence_ref ?? undefined, run_ref: r.run_ref ?? undefined,
extractor_version: r.extractor_version, observed_at: iso(r.observed_at),
valid_from: r.valid_from ? iso(r.valid_from) : undefined,
valid_to: r.valid_to ? iso(r.valid_to) : undefined,
confidence: r.confidence === null ? undefined : Number(r.confidence),
quality_status: r.quality_status, status: r.status, created_at: iso(r.created_at),
})) as CanonicalFact[];
});
}
}
+149
View File
@@ -0,0 +1,149 @@
import { resolveStoreMode } from "../platform/dependency-mode";
import { SiaxError } from "../platform/errors";
import type { CreateDatasetInput, Dataset, DatasetStatus, DatasetType } from "../types/dataset";
import { getRepositorySql, repositoryDatabaseUrl, type RepositorySql } from "./db";
export interface DatasetListFilter {
tenant_id?: string;
project_id?: string;
dataset_type?: DatasetType;
status?: DatasetStatus;
}
export interface DatasetRepository {
create(input: CreateDatasetInput): Promise<Dataset>;
get(datasetId: string): Promise<Dataset>;
list(filter?: DatasetListFilter): Promise<Dataset[]>;
}
interface DatasetRow {
dataset_id: string;
tenant_id: string;
project_id: string;
name: string;
dataset_type: DatasetType;
status: DatasetStatus;
description: string | null;
correlation_id: string | null;
created_at: string | Date;
updated_at: string | Date | null;
created_by: string | null;
}
function iso(value: string | Date): string {
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
function toDataset(row: DatasetRow): Dataset {
return {
dataset_id: row.dataset_id,
tenant_id: row.tenant_id,
project_id: row.project_id,
name: row.name,
dataset_type: row.dataset_type,
status: row.status,
...(row.description ? { description: row.description } : {}),
...(row.correlation_id ? { correlation_id: row.correlation_id } : {}),
created_at: iso(row.created_at),
...(row.updated_at ? { updated_at: iso(row.updated_at) } : {}),
...(row.created_by ? { created_by: row.created_by } : {}),
};
}
function validate(input: CreateDatasetInput): void {
if (!input.dataset_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "dataset_id is required");
if (!input.tenant_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "tenant_id is required");
if (!input.project_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "project_id is required");
if (!input.name?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "name is required");
}
export class InMemoryDatasetRepository implements DatasetRepository {
private readonly rows = new Map<string, Dataset>();
async create(input: CreateDatasetInput): Promise<Dataset> {
validate(input);
if (this.rows.has(input.dataset_id)) {
throw new SiaxError("CONFLICT", "0pt.dataset", `dataset ${input.dataset_id} already exists`);
}
const dataset: Dataset = {
dataset_id: input.dataset_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
name: input.name,
dataset_type: input.dataset_type,
status: input.status ?? "active",
...(input.description ? { description: input.description } : {}),
...(input.correlation_id ? { correlation_id: input.correlation_id } : {}),
created_at: new Date().toISOString(),
...(input.created_by ? { created_by: input.created_by } : {}),
};
this.rows.set(dataset.dataset_id, dataset);
return { ...dataset };
}
async get(datasetId: string): Promise<Dataset> {
const dataset = this.rows.get(datasetId);
if (!dataset) throw new SiaxError("NOT_FOUND", "0pt.dataset", `dataset ${datasetId} not found`);
return { ...dataset };
}
async list(filter?: DatasetListFilter): Promise<Dataset[]> {
return [...this.rows.values()]
.filter((dataset) => !filter?.tenant_id || dataset.tenant_id === filter.tenant_id)
.filter((dataset) => !filter?.project_id || dataset.project_id === filter.project_id)
.filter((dataset) => !filter?.dataset_type || dataset.dataset_type === filter.dataset_type)
.filter((dataset) => !filter?.status || dataset.status === filter.status)
.map((dataset) => ({ ...dataset }));
}
}
export class PostgresDatasetRepository implements DatasetRepository {
constructor(private readonly sql: RepositorySql) {}
async create(input: CreateDatasetInput): Promise<Dataset> {
validate(input);
try {
const rows = await this.sql<DatasetRow[]>`
INSERT INTO opt_datasets
(dataset_id, tenant_id, project_id, name, dataset_type, status,
description, correlation_id, created_by)
VALUES
(${input.dataset_id}, ${input.tenant_id}, ${input.project_id}, ${input.name},
${input.dataset_type}, ${input.status ?? "active"}, ${input.description ?? null},
${input.correlation_id ?? null}, ${input.created_by ?? null})
RETURNING *`;
return toDataset(rows[0]);
} catch (error) {
if ((error as { code?: string })?.code === "23505") {
throw new SiaxError("CONFLICT", "0pt.dataset", `dataset ${input.dataset_id} already exists`);
}
throw error;
}
}
async get(datasetId: string): Promise<Dataset> {
const rows = await this.sql<DatasetRow[]>`
SELECT * FROM opt_datasets WHERE dataset_id = ${datasetId} LIMIT 1`;
if (!rows[0]) throw new SiaxError("NOT_FOUND", "0pt.dataset", `dataset ${datasetId} not found`);
return toDataset(rows[0]);
}
async list(filter?: DatasetListFilter): Promise<Dataset[]> {
const rows = await this.sql<DatasetRow[]>`
SELECT *
FROM opt_datasets
WHERE (${filter?.tenant_id ?? null}::text IS NULL OR tenant_id = ${filter?.tenant_id ?? null})
AND (${filter?.project_id ?? null}::text IS NULL OR project_id = ${filter?.project_id ?? null})
AND (${filter?.dataset_type ?? null}::text IS NULL OR dataset_type = ${filter?.dataset_type ?? null})
AND (${filter?.status ?? null}::text IS NULL OR status = ${filter?.status ?? null})
ORDER BY created_at DESC, dataset_id ASC`;
return rows.map(toDataset);
}
}
export function createDatasetRepository(databaseUrl?: string): DatasetRepository {
const mode = resolveStoreMode("0pt.datasets", databaseUrl ?? repositoryDatabaseUrl());
return mode.mode === "postgres"
? new PostgresDatasetRepository(getRepositorySql(mode.url))
: new InMemoryDatasetRepository();
}
@@ -0,0 +1,177 @@
import { resolveStoreMode } from "../platform/dependency-mode";
import { SiaxError } from "../platform/errors";
import type { CreateDatasetVersionInput, DatasetVersion } from "../types/dataset-version";
import { getRepositorySql, repositoryDatabaseUrl, type RepositorySql } from "./db";
export interface DatasetVersionRepository {
create(input: CreateDatasetVersionInput): Promise<DatasetVersion>;
list(datasetId: string, tenantId: string): Promise<DatasetVersion[]>;
get(datasetId: string, tenantId: string, version: number): Promise<DatasetVersion>;
}
interface VersionRow {
dataset_id: string;
version: number;
tenant_id: string;
project_id: string;
artifact_refs: string[];
schema_version: string;
record_count: string | number | null;
description: string | null;
created_at: string | Date;
created_by: string;
correlation_id: string | null;
idempotency_key: string | null;
}
function toVersion(row: VersionRow): DatasetVersion {
return {
dataset_id: row.dataset_id,
version: Number(row.version),
tenant_id: row.tenant_id,
project_id: row.project_id,
artifact_refs: [...row.artifact_refs],
schema_version: row.schema_version,
...(row.record_count == null ? {} : { record_count: Number(row.record_count) }),
...(row.description ? { description: row.description } : {}),
created_at: row.created_at instanceof Date ? row.created_at.toISOString() : new Date(row.created_at).toISOString(),
created_by: row.created_by,
...(row.correlation_id ? { correlation_id: row.correlation_id } : {}),
};
}
function normalizedCount(value: string | number | null | undefined): number | undefined {
return value == null ? undefined : Number(value);
}
function sameInput(row: VersionRow | DatasetVersion, input: CreateDatasetVersionInput): boolean {
return row.dataset_id === input.dataset_id
&& row.tenant_id === input.tenant_id
&& row.project_id === input.project_id
&& row.schema_version === input.schema_version
&& normalizedCount(row.record_count) === normalizedCount(input.record_count)
&& (row.description ?? undefined) === (input.description ?? undefined)
&& row.created_by === input.created_by
&& JSON.stringify(row.artifact_refs) === JSON.stringify(input.artifact_refs);
}
export class InMemoryDatasetVersionRepository implements DatasetVersionRepository {
private readonly versions = new Map<string, DatasetVersion[]>();
private readonly idempotency = new Map<string, DatasetVersion>();
async create(input: CreateDatasetVersionInput): Promise<DatasetVersion> {
if (input.idempotency_key) {
const existing = this.idempotency.get(`${input.tenant_id}:${input.idempotency_key}`);
if (existing) {
if (!sameInput(existing, input)) {
throw new SiaxError("CONFLICT", "0pt.dataset", "idempotency key reused with different dataset-version input");
}
return { ...existing, artifact_refs: [...existing.artifact_refs] };
}
}
const list = this.versions.get(input.dataset_id) ?? [];
const version: DatasetVersion = {
dataset_id: input.dataset_id,
version: (list[list.length - 1]?.version ?? 0) + 1,
tenant_id: input.tenant_id,
project_id: input.project_id,
artifact_refs: [...input.artifact_refs],
schema_version: input.schema_version,
...(input.record_count === undefined ? {} : { record_count: input.record_count }),
...(input.description ? { description: input.description } : {}),
created_at: new Date().toISOString(),
created_by: input.created_by,
...(input.correlation_id ? { correlation_id: input.correlation_id } : {}),
};
list.push(version);
this.versions.set(input.dataset_id, list);
if (input.idempotency_key) this.idempotency.set(`${input.tenant_id}:${input.idempotency_key}`, version);
return { ...version, artifact_refs: [...version.artifact_refs] };
}
async list(datasetId: string, tenantId: string): Promise<DatasetVersion[]> {
return (this.versions.get(datasetId) ?? [])
.filter((version) => version.tenant_id === tenantId)
.map((version) => ({ ...version, artifact_refs: [...version.artifact_refs] }));
}
async get(datasetId: string, tenantId: string, version: number): Promise<DatasetVersion> {
const found = (await this.list(datasetId, tenantId)).find((item) => item.version === version);
if (!found) throw new SiaxError("NOT_FOUND", "0pt.dataset", `dataset ${datasetId} has no version ${version}`);
return found;
}
}
export class PostgresDatasetVersionRepository implements DatasetVersionRepository {
constructor(private readonly sql: RepositorySql) {}
async create(input: CreateDatasetVersionInput): Promise<DatasetVersion> {
return this.sql.begin(async (tx) => {
const parent = await tx<{ dataset_id: string; tenant_id: string }[]>`
SELECT dataset_id, tenant_id
FROM opt_datasets
WHERE dataset_id = ${input.dataset_id}
FOR UPDATE`;
if (!parent[0] || parent[0].tenant_id !== input.tenant_id) {
throw new SiaxError("NOT_FOUND", "0pt.dataset", `dataset ${input.dataset_id} not found`);
}
if (input.idempotency_key) {
const existing = await tx<VersionRow[]>`
SELECT * FROM opt_dataset_versions
WHERE tenant_id = ${input.tenant_id}
AND idempotency_key = ${input.idempotency_key}
LIMIT 1`;
if (existing[0]) {
if (!sameInput(existing[0], input)) {
throw new SiaxError("CONFLICT", "0pt.dataset", "idempotency key reused with different dataset-version input");
}
return toVersion(existing[0]);
}
}
const next = await tx<{ version: number }[]>`
SELECT COALESCE(max(version), 0)::int + 1 AS version
FROM opt_dataset_versions
WHERE dataset_id = ${input.dataset_id}`;
const version = next[0]?.version ?? 1;
const rows = await tx<VersionRow[]>`
INSERT INTO opt_dataset_versions
(dataset_id, version, tenant_id, project_id, artifact_refs,
schema_version, record_count, description, created_by,
correlation_id, idempotency_key)
VALUES
(${input.dataset_id}, ${version}, ${input.tenant_id}, ${input.project_id},
${tx.array([...input.artifact_refs])}, ${input.schema_version}, ${input.record_count ?? null},
${input.description ?? null}, ${input.created_by}, ${input.correlation_id ?? null},
${input.idempotency_key ?? null})
RETURNING *`;
return toVersion(rows[0]);
});
}
async list(datasetId: string, tenantId: string): Promise<DatasetVersion[]> {
const rows = await this.sql<VersionRow[]>`
SELECT * FROM opt_dataset_versions
WHERE dataset_id = ${datasetId} AND tenant_id = ${tenantId}
ORDER BY version ASC`;
return rows.map(toVersion);
}
async get(datasetId: string, tenantId: string, version: number): Promise<DatasetVersion> {
const rows = await this.sql<VersionRow[]>`
SELECT * FROM opt_dataset_versions
WHERE dataset_id = ${datasetId} AND tenant_id = ${tenantId} AND version = ${version}
LIMIT 1`;
if (!rows[0]) throw new SiaxError("NOT_FOUND", "0pt.dataset", `dataset ${datasetId} has no version ${version}`);
return toVersion(rows[0]);
}
}
export function createDatasetVersionRepository(databaseUrl?: string): DatasetVersionRepository {
const mode = resolveStoreMode("0pt.dataset_versions", databaseUrl ?? repositoryDatabaseUrl());
return mode.mode === "postgres"
? new PostgresDatasetVersionRepository(getRepositorySql(mode.url))
: new InMemoryDatasetVersionRepository();
}
+61
View File
@@ -0,0 +1,61 @@
/**
* src/repositories/db.ts
* ========================
* Lazy Postgres connection for P0 capability repositories (src/repositories/*).
*
* Deliberately separate from lib/db.ts: that module is tuned for the
* Vercel-hosted edge Postgres behind app/api/orders + app/api/subscriptions
* (`ssl: "require"`, because that's what Vercel Postgres needs) and lives in
* lib/, which src/ (the blocking-typechecked capability layer,
* .dependency-cruiser.cjs's "no-src-importing-app-or-components" rule's
* sibling concern) does not depend on. The P0 capability layer's Postgres
* instance is the self-hosted VPS Postgres from docs/08-infrastructure.md
* (infra/docker-compose.yml's `postgres` service, same private docker network
* as the FastAPI engine, no TLS terminated in front of it) -- forcing
* `ssl: "require"` here would break every real connection to it. SSL is
* opt-in via PGSSL=require for deployments that do put TLS in front.
*
* Same lazy/env-guarded shape as lib/db.ts, and the same production-safety
* decision as every other P0 dependency: src/platform/dependency-mode.ts's
* `resolveStoreMode` is what actually decides postgres-vs-memory (and fails
* hard in production with no URL) -- this module only opens the connection
* once that decision has already been made.
*/
import postgres from "postgres";
export type RepositorySql = ReturnType<typeof postgres>;
/** DATABASE_URL, falling back to Vercel Postgres's env names -- same precedence lib/db.ts's dbUrl() uses, kept independent so src/ has no import on lib/. */
export function repositoryDatabaseUrl(env: NodeJS.ProcessEnv = process.env): string | undefined {
return env.DATABASE_URL || env.POSTGRES_URL || env.POSTGRES_PRISMA_URL;
}
let _sql: RepositorySql | null = null;
let _urlUsed: string | undefined;
/** Returns a memoized connection for `url`; re-opens if a different URL is requested (e.g. tests pointing at a fresh testcontainer). */
export function getRepositorySql(url: string): RepositorySql {
if (_sql && _urlUsed === url) return _sql;
_sql = postgres(url, {
prepare: false,
idle_timeout: 20,
max: 5,
ssl: process.env.PGSSL === "require" ? "require" : false,
});
_urlUsed = url;
return _sql;
}
/** Test-only escape hatch: force the next getRepositorySql call to open a fresh connection. */
export function resetRepositorySqlForTests(): void {
_sql = null;
_urlUsed = undefined;
}
/** Test-only: gracefully close the memoized connection (so a vitest run doesn't hang on an open socket) and clear it. */
export async function closeRepositorySqlForTests(): Promise<void> {
const sql = _sql;
_sql = null;
_urlUsed = undefined;
if (sql) await sql.end({ timeout: 5 });
}
@@ -0,0 +1,120 @@
/**
* src/repositories/in-memory-ingestion-repository.ts
* ====================================================
* Non-production implementation of IngestionRepository (hermetic tests, local
* dev). Semantics are kept IDENTICAL to the Postgres implementation on every
* point the runner depends on:
* - checkpoints are upserted per (source, partition),
* - ledger verdicts are new/changed/duplicate against the LAST accepted
* payload hash for the key,
* - quarantine is append-only, newest-first on read,
* - schemas are keyed by (source, version) and "latest" means highest version,
* - lineage edges are deduplicated by edge_id.
*
* Any divergence between the two implementations is a bug in one of them;
* tests/p0/ingestion-repository-parity.test.ts is what keeps them honest for
* the in-memory side, and tests/p0/ingestion-plane-postgres.realinfra.test.ts
* runs the same expectations against real Postgres.
*/
import type { LineageEdge, LineageQuery } from "../lineage/lineage-edge";
import type { RecordSchema } from "../schema/record-schema";
import type { IngestionCheckpoint, LedgerDecision, QuarantineRecord } from "../types/ingestion";
import type { IngestionRepository, LedgerEntry } from "./ingestion-repository";
function checkpointKey(sourceId: string, partitionKey: string): string {
return `${sourceId}|${partitionKey}`;
}
export class InMemoryIngestionRepository implements IngestionRepository {
private readonly checkpoints = new Map<string, IngestionCheckpoint>();
/** source_id -> record_key -> last accepted payload hash. */
private readonly ledger = new Map<string, Map<string, string>>();
private readonly quarantined = new Map<string, QuarantineRecord[]>();
private readonly schemas = new Map<string, RecordSchema[]>();
private readonly lineage = new Map<string, LineageEdge>();
async getCheckpoint(sourceId: string, partitionKey: string): Promise<IngestionCheckpoint | undefined> {
return this.checkpoints.get(checkpointKey(sourceId, partitionKey));
}
async commitCheckpoint(checkpoint: IngestionCheckpoint): Promise<void> {
this.checkpoints.set(checkpointKey(checkpoint.source_id, checkpoint.partition_key), { ...checkpoint });
}
async listCheckpoints(sourceId: string): Promise<IngestionCheckpoint[]> {
return [...this.checkpoints.values()]
.filter((c) => c.source_id === sourceId)
.sort((a, b) => a.partition_key.localeCompare(b.partition_key));
}
async peekDeliveries(sourceId: string, entries: LedgerEntry[]): Promise<LedgerDecision[]> {
const keys = this.ledger.get(sourceId);
return entries.map((entry) => {
const prior = keys?.get(entry.record_key);
return {
record_key: entry.record_key,
verdict: prior === undefined ? "new" : prior === entry.payload_hash ? "duplicate" : "changed",
} as LedgerDecision;
});
}
async commitDeliveries(sourceId: string, _tenantId: string, entries: LedgerEntry[]): Promise<void> {
let keys = this.ledger.get(sourceId);
if (!keys) {
keys = new Map<string, string>();
this.ledger.set(sourceId, keys);
}
for (const entry of entries) keys.set(entry.record_key, entry.payload_hash);
}
async countLedger(sourceId: string): Promise<number> {
return this.ledger.get(sourceId)?.size ?? 0;
}
async quarantine(record: QuarantineRecord): Promise<void> {
const list = this.quarantined.get(record.source_id) ?? [];
list.push(record);
this.quarantined.set(record.source_id, list);
}
async listQuarantine(sourceId: string, limit = 100): Promise<QuarantineRecord[]> {
const list = this.quarantined.get(sourceId) ?? [];
return [...list].reverse().slice(0, limit);
}
async putSchema(schema: RecordSchema): Promise<void> {
const list = this.schemas.get(schema.source_id) ?? [];
const existing = list.findIndex((s) => s.schema_version === schema.schema_version);
if (existing >= 0) list[existing] = { ...schema };
else list.push({ ...schema });
list.sort((a, b) => a.schema_version - b.schema_version);
this.schemas.set(schema.source_id, list);
}
async getSchema(sourceId: string, version: number): Promise<RecordSchema | undefined> {
return this.schemas.get(sourceId)?.find((s) => s.schema_version === version);
}
async getLatestSchema(sourceId: string): Promise<RecordSchema | undefined> {
const list = this.schemas.get(sourceId);
return list && list.length > 0 ? list[list.length - 1] : undefined;
}
async listSchemas(sourceId: string): Promise<RecordSchema[]> {
return [...(this.schemas.get(sourceId) ?? [])];
}
async appendLineageEdges(edges: LineageEdge[]): Promise<void> {
for (const edge of edges) this.lineage.set(edge.edge_id, { ...edge });
}
async queryLineage(query: LineageQuery): Promise<LineageEdge[]> {
const limit = query.limit ?? 200;
return [...this.lineage.values()]
.filter((e) => e.tenant_id === query.tenant_id)
.filter((e) => (query.output_name ? e.output_name === query.output_name : true))
.filter((e) => (query.input_name ? e.input_name === query.input_name : true))
.sort((a, b) => b.event_time.localeCompare(a.event_time))
.slice(0, limit);
}
}
@@ -0,0 +1,83 @@
/**
* src/repositories/in-memory-source-registry-repository.ts
* ============================================================
* The original SourceRegistryService storage (four Maps: rights,
* provenance, healthChecks, lastSuccess), extracted verbatim behind the
* SourceRegistryRepository seam. Health-check bounding (latest 100
* observations) is preserved exactly; `listHealthChecks` returns
* newest-first to match the Postgres implementation's `ORDER BY checked_at
* DESC` contract (the original Map-based `getHealth` read `list[list.length
* - 1]` for "most recent" and scanned backward for consecutive failures --
* callers now get the same data pre-ordered instead).
*/
import type {
SourceAuthorization,
SourceHealthCheck,
SourceProvenance,
SourceRights,
SourceSchedule,
} from "../types/source-registry";
import type { SourceRegistryRepository } from "./source-registry-repository";
export class InMemorySourceRegistryRepository implements SourceRegistryRepository {
private readonly rights = new Map<string, SourceRights>();
private readonly provenance = new Map<string, SourceProvenance>();
private readonly healthChecks = new Map<string, SourceHealthCheck[]>();
private readonly lastSuccess = new Map<string, string>();
private readonly authorizations = new Map<string, SourceAuthorization>();
private readonly schedules = new Map<string, SourceSchedule>();
async setRights(rights: SourceRights): Promise<void> {
this.rights.set(rights.source_id, rights);
}
async getRights(sourceId: string): Promise<SourceRights | undefined> {
return this.rights.get(sourceId);
}
async setProvenance(prov: SourceProvenance): Promise<void> {
this.provenance.set(prov.source_id, prov);
}
async getProvenance(sourceId: string): Promise<SourceProvenance | undefined> {
return this.provenance.get(sourceId);
}
async recordSuccess(sourceId: string, _tenantId: string, atIso: string): Promise<void> {
this.lastSuccess.set(sourceId, atIso);
}
async getLastSuccess(sourceId: string): Promise<string | undefined> {
return this.lastSuccess.get(sourceId);
}
async setAuthorization(auth: SourceAuthorization): Promise<void> {
this.authorizations.set(auth.source_id, auth);
}
async getAuthorization(sourceId: string): Promise<SourceAuthorization | undefined> {
return this.authorizations.get(sourceId);
}
async setSchedule(schedule: SourceSchedule): Promise<void> {
this.schedules.set(schedule.source_id, schedule);
}
async getSchedule(sourceId: string): Promise<SourceSchedule | undefined> {
return this.schedules.get(sourceId);
}
async appendHealthCheck(check: SourceHealthCheck): Promise<void> {
const list = this.healthChecks.get(check.source_id) ?? [];
list.push(check);
// Bounded history -- health is an operational signal, not an audit log
// (AUD0 owns history); keep the latest 100 observations.
if (list.length > 100) list.splice(0, list.length - 100);
this.healthChecks.set(check.source_id, list);
}
async listHealthChecks(sourceId: string, limit = 100): Promise<SourceHealthCheck[]> {
const list = this.healthChecks.get(sourceId) ?? [];
return [...list].reverse().slice(0, limit);
}
}
@@ -0,0 +1,110 @@
/**
* src/repositories/in-memory-source-repository.ts
* ==================================================
* The original SourceService storage, extracted verbatim behind the
* SourceRepository seam (src/repositories/source-repository.ts) so
* PostgresSourceRepository can run the exact same business rules
* ("already exists", "name is required", "not found", filter semantics)
* against real Postgres instead. Used outside production when no
* DATABASE_URL is configured (resolveStoreMode), and directly by tests that
* want a hermetic, dependency-free SourceService.
*/
import type { CreateSourceInput, Source, SourceStatus, SourceType } from "../types/source";
import type { SourceListFilter, SourceRepository } from "./source-repository";
/** Storage shape: nullable columns, exactly mirroring `opt_sources`. */
interface SourceRecord {
source_id: string;
tenant_id: string;
project_id: string;
source_type: string;
name: string;
adapter_id: string | null;
access: string | null;
description: string | null;
status: string;
correlation_id: string | null;
created_at: string;
updated_at: string | null;
created_by: string | null;
owner_id: string | null;
}
export class InMemorySourceRepository implements SourceRepository {
private sources: Map<string, SourceRecord> = new Map();
async create(input: CreateSourceInput): Promise<Source> {
if (this.sources.has(input.source_id)) {
throw new Error(`Source ${input.source_id} already exists`);
}
if (!input.name) {
throw new Error("name is required");
}
const now = new Date().toISOString();
const record: SourceRecord = {
source_id: input.source_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
source_type: input.source_type,
name: input.name,
adapter_id: input.adapter_id ?? null,
access: input.access ?? null,
description: input.description ?? null,
// P060: "pending", not "active". A source with no rights, no provenance
// and no authorization used to be live the instant it was registered;
// reaching "active" now goes through
// SourceRegistryService.activateSource's classification gate.
status: input.status ?? "pending",
correlation_id: input.correlation_id ?? null,
created_at: now,
updated_at: null,
created_by: input.created_by ?? null,
owner_id: input.owner_id ?? null,
};
this.sources.set(record.source_id, record);
return toSource(record);
}
async get(sourceId: string): Promise<Source> {
const record = this.sources.get(sourceId);
if (!record) throw new Error(`Source ${sourceId} not found`);
return toSource(record);
}
async updateStatus(sourceId: string, status: SourceStatus): Promise<Source> {
const record = this.sources.get(sourceId);
if (!record) throw new Error(`Source ${sourceId} not found`);
record.status = status;
record.updated_at = new Date().toISOString();
return toSource(record);
}
async list(filter?: SourceListFilter): Promise<Source[]> {
let results = Array.from(this.sources.values());
if (filter?.tenant_id) results = results.filter((r) => r.tenant_id === filter.tenant_id);
if (filter?.project_id) results = results.filter((r) => r.project_id === filter.project_id);
if (filter?.source_type) results = results.filter((r) => r.source_type === filter.source_type);
if (filter?.status) results = results.filter((r) => r.status === filter.status);
return results.map(toSource);
}
}
function toSource(r: SourceRecord): Source {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
project_id: r.project_id,
source_type: r.source_type as SourceType,
name: r.name,
adapter_id: r.adapter_id ?? undefined,
access: (r.access as Source["access"]) ?? undefined,
description: r.description ?? undefined,
status: r.status as SourceStatus,
correlation_id: r.correlation_id ?? undefined,
created_at: r.created_at,
updated_at: r.updated_at ?? undefined,
created_by: r.created_by ?? undefined,
owner_id: r.owner_id ?? undefined,
};
}
+91
View File
@@ -0,0 +1,91 @@
/**
* src/repositories/ingestion-repository.ts
* ==========================================
* The storage seam for the P060-P068 ingestion plane: checkpoints (P060/P062),
* the idempotency ledger (P068), quarantine (P064), the schema registry
* (P060/P063) and the queryable lineage projection (P067).
*
* WHY ONE INTERFACE AND NOT FIVE. These five tables are written by ONE
* caller — IngestionRunner — inside one run, and their correctness is
* relative to each other (a checkpoint that advanced past records the ledger
* never accepted is a silent gap; a quarantined record whose checkpoint moved
* on is a silently dropped record). Splitting them into five factories would
* let a future caller wire four of them to Postgres and one to memory and
* still typecheck, which is exactly the failure this plane must not have.
* They are chosen once, together, by one `resolveStoreMode` call.
*
* Same production posture as every other 0pt store: `resolveStoreMode` fails
* hard in production with no DATABASE_URL rather than silently serving Maps
* (src/platform/dependency-mode.ts, Master-DoD §3/§10).
*/
import { resolveStoreMode } from "../platform/dependency-mode";
import type { LineageEdge, LineageQuery } from "../lineage/lineage-edge";
import type { RecordSchema } from "../schema/record-schema";
import type { IngestionCheckpoint, LedgerDecision, QuarantineRecord } from "../types/ingestion";
import { getRepositorySql, repositoryDatabaseUrl } from "./db";
import { InMemoryIngestionRepository } from "./in-memory-ingestion-repository";
import { PostgresIngestionRepository } from "./postgres-ingestion-repository";
/** One record offered to the ledger. */
export interface LedgerEntry {
record_key: string;
/** Stable hash of the payload — see hashPayload() in src/ingestion/ingestion-ledger.ts. */
payload_hash: string;
}
export interface IngestionRepository {
// --- checkpoints (P060 registry field, P062 durable resume) --------------
getCheckpoint(sourceId: string, partitionKey: string): Promise<IngestionCheckpoint | undefined>;
commitCheckpoint(checkpoint: IngestionCheckpoint): Promise<void>;
listCheckpoints(sourceId: string): Promise<IngestionCheckpoint[]>;
// --- idempotency ledger (P068) ------------------------------------------
/**
* READ-ONLY verdicts, in input order:
* "new" — this record_key has never been accepted for this source,
* "changed" — it has, but with different content (a real update),
* "duplicate" — it has, with byte-identical content (a replay).
*
* Deliberately separate from {@link commitDeliveries}. An earlier draft of
* this interface combined them into one atomic check-and-record, which was
* WRONG in the way that matters: the runner has to consult the ledger
* BEFORE the sink (to filter replays) and commit AFTER it (so a crash
* between the two re-delivers rather than loses). A combined call marked a
* record "delivered" that the sink never received, and the resumed run then
* skipped it as a duplicate — permanent, silent data loss. That is not a
* hypothetical: tests/p0/ingestion-runner.test.ts caught it, and the
* "resumes with NO gap" case is what pins the fix.
*/
peekDeliveries(sourceId: string, entries: LedgerEntry[]): Promise<LedgerDecision[]>;
/**
* Record that these records were successfully delivered. Called only after
* the sink resolved. Idempotent: re-committing the same entry bumps the
* delivery count and leaves the verdict unchanged.
*/
commitDeliveries(sourceId: string, tenantId: string, entries: LedgerEntry[]): Promise<void>;
countLedger(sourceId: string): Promise<number>;
// --- quarantine (P064) --------------------------------------------------
quarantine(record: QuarantineRecord): Promise<void>;
listQuarantine(sourceId: string, limit?: number): Promise<QuarantineRecord[]>;
// --- schema registry (P060 registry field, P063 evolution) --------------
putSchema(schema: RecordSchema): Promise<void>;
getSchema(sourceId: string, version: number): Promise<RecordSchema | undefined>;
getLatestSchema(sourceId: string): Promise<RecordSchema | undefined>;
listSchemas(sourceId: string): Promise<RecordSchema[]>;
// --- lineage projection (P067) ------------------------------------------
appendLineageEdges(edges: LineageEdge[]): Promise<void>;
queryLineage(query: LineageQuery): Promise<LineageEdge[]>;
}
export function createIngestionRepository(databaseUrl?: string): IngestionRepository {
const mode = resolveStoreMode("0pt.ingestion", databaseUrl ?? repositoryDatabaseUrl());
if (mode.mode === "postgres") {
return new PostgresIngestionRepository(getRepositorySql(mode.url));
}
return new InMemoryIngestionRepository();
}
@@ -0,0 +1,308 @@
/**
* src/repositories/postgres-ingestion-repository.ts
* ==================================================
* Real Postgres backing for IngestionRepository (sql/007_ingestion_plane.sql).
*
* THE LEDGER IS THE INTERESTING ONE (P068), and it is deliberately SPLIT:
* `peekDeliveries` reads verdicts, `commitDeliveries` records them. The
* runner peeks before the sink and commits after it, so a crash in between
* re-delivers on resume instead of losing the record. An earlier version of
* this file combined the two into one atomic check-and-record statement; that
* was measurably wrong (see the interface's doc comment) and the crash/resume
* test in tests/p0/ingestion-runner.test.ts is what proved it.
*
* KNOWN LIMIT, stated rather than papered over: the split means two runs on
* the SAME (source_id, partition) can both peek "new" and both emit. The
* delivery guarantee is therefore AT-LEAST-ONCE, which is what the
* deterministic `envelope_id` (src/ingestion/envelope.ts) exists to make
* survivable downstream. Exactly-once across concurrent runs needs a run lock
* per (source, partition); there is none yet. That is a real open gap, not a
* solved one — do not describe this plane as exactly-once.
*/
import type { LineageEdge, LineageQuery } from "../lineage/lineage-edge";
import type {
CompatibilityPolicy,
RecordSchema,
RecordSchemaFields,
} from "../schema/record-schema";
import type {
IngestionCheckpoint,
IngestionEnvelope,
LedgerDecision,
QuarantineRecord,
} from "../types/ingestion";
import type { RepositorySql } from "./db";
import type { IngestionRepository, LedgerEntry } from "./ingestion-repository";
/** postgres.js's `sql.json()` parameter type, named locally so the two JSONB columns can be passed without importing postgres' internals. */
type JsonValue = Parameters<RepositorySql["json"]>[0];
function toIso(v: string | Date): string {
return v instanceof Date ? v.toISOString() : v;
}
interface CheckpointRow {
source_id: string;
tenant_id: string;
partition_key: string;
cursor: string | null;
sequence: string | number;
records_committed: string | number;
committed_at: string | Date;
}
function toCheckpoint(r: CheckpointRow): IngestionCheckpoint {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
partition_key: r.partition_key,
cursor: r.cursor ?? undefined,
sequence: Number(r.sequence),
records_committed: Number(r.records_committed),
committed_at: toIso(r.committed_at),
};
}
export class PostgresIngestionRepository implements IngestionRepository {
constructor(private readonly sql: RepositorySql) {}
// --- checkpoints ---------------------------------------------------------
async getCheckpoint(sourceId: string, partitionKey: string): Promise<IngestionCheckpoint | undefined> {
const rows = await this.sql<CheckpointRow[]>`
SELECT source_id, tenant_id, partition_key, cursor, sequence, records_committed, committed_at
FROM opt_ingestion_checkpoints
WHERE source_id = ${sourceId} AND partition_key = ${partitionKey}
LIMIT 1`;
return rows[0] ? toCheckpoint(rows[0]) : undefined;
}
async commitCheckpoint(cp: IngestionCheckpoint): Promise<void> {
await this.sql`
INSERT INTO opt_ingestion_checkpoints
(source_id, partition_key, tenant_id, cursor, sequence, records_committed, committed_at)
VALUES
(${cp.source_id}, ${cp.partition_key}, ${cp.tenant_id}, ${cp.cursor ?? null},
${cp.sequence}, ${cp.records_committed}, ${cp.committed_at})
ON CONFLICT (source_id, partition_key) DO UPDATE
SET cursor = EXCLUDED.cursor,
sequence = EXCLUDED.sequence,
records_committed = EXCLUDED.records_committed,
committed_at = EXCLUDED.committed_at,
tenant_id = EXCLUDED.tenant_id`;
}
async listCheckpoints(sourceId: string): Promise<IngestionCheckpoint[]> {
const rows = await this.sql<CheckpointRow[]>`
SELECT source_id, tenant_id, partition_key, cursor, sequence, records_committed, committed_at
FROM opt_ingestion_checkpoints
WHERE source_id = ${sourceId}
ORDER BY partition_key ASC`;
return rows.map(toCheckpoint);
}
// --- ledger --------------------------------------------------------------
async peekDeliveries(sourceId: string, entries: LedgerEntry[]): Promise<LedgerDecision[]> {
if (entries.length === 0) return [];
const keys = entries.map((e) => e.record_key);
const rows = await this.sql<{ record_key: string; payload_hash: string }[]>`
SELECT record_key, payload_hash FROM opt_ingestion_ledger
WHERE source_id = ${sourceId} AND record_key = ANY(${this.sql.array(keys)})`;
const priorByKey = new Map(rows.map((r) => [r.record_key, r.payload_hash]));
return entries.map((entry) => {
const prior = priorByKey.get(entry.record_key);
return {
record_key: entry.record_key,
verdict: prior === undefined ? "new" : prior === entry.payload_hash ? "duplicate" : "changed",
} as LedgerDecision;
});
}
async commitDeliveries(sourceId: string, tenantId: string, entries: LedgerEntry[]): Promise<void> {
for (const entry of entries) {
await this.sql`
INSERT INTO opt_ingestion_ledger (source_id, record_key, tenant_id, payload_hash)
VALUES (${sourceId}, ${entry.record_key}, ${tenantId}, ${entry.payload_hash})
ON CONFLICT (source_id, record_key) DO UPDATE
SET last_seen_at = now(),
delivery_count = opt_ingestion_ledger.delivery_count + 1,
payload_hash = EXCLUDED.payload_hash`;
}
}
async countLedger(sourceId: string): Promise<number> {
const rows = await this.sql<{ n: string }[]>`
SELECT count(*)::text AS n FROM opt_ingestion_ledger WHERE source_id = ${sourceId}`;
return Number(rows[0]?.n ?? 0);
}
// --- quarantine ----------------------------------------------------------
async quarantine(record: QuarantineRecord): Promise<void> {
await this.sql`
INSERT INTO opt_quality_quarantine
(quarantine_id, source_id, tenant_id, run_id, record_key, violations, envelope, quarantined_at)
VALUES
(${record.quarantine_id}, ${record.source_id}, ${record.tenant_id}, ${record.run_id},
${record.record_key}, ${this.sql.json(record.violations as unknown as JsonValue)},
${this.sql.json(record.envelope as unknown as JsonValue)},
${record.quarantined_at})
ON CONFLICT (quarantine_id) DO NOTHING`;
}
async listQuarantine(sourceId: string, limit = 100): Promise<QuarantineRecord[]> {
const rows = await this.sql<
{
quarantine_id: string;
source_id: string;
tenant_id: string;
run_id: string;
record_key: string;
violations: QuarantineRecord["violations"];
envelope: IngestionEnvelope;
quarantined_at: string | Date;
}[]
>`
SELECT quarantine_id, source_id, tenant_id, run_id, record_key, violations, envelope, quarantined_at
FROM opt_quality_quarantine
WHERE source_id = ${sourceId}
ORDER BY quarantined_at DESC, quarantine_id DESC
LIMIT ${limit}`;
return rows.map((r) => ({
quarantine_id: r.quarantine_id,
source_id: r.source_id,
tenant_id: r.tenant_id,
run_id: r.run_id,
record_key: r.record_key,
violations: r.violations,
envelope: r.envelope,
quarantined_at: toIso(r.quarantined_at),
}));
}
// --- schema registry -----------------------------------------------------
async putSchema(schema: RecordSchema): Promise<void> {
await this.sql`
INSERT INTO opt_source_schemas
(source_id, schema_version, tenant_id, fields, compatibility, registered_at, registered_by)
VALUES
(${schema.source_id}, ${schema.schema_version}, ${schema.tenant_id},
${this.sql.json(schema.fields as unknown as JsonValue)}, ${schema.compatibility},
${schema.registered_at}, ${schema.registered_by ?? null})
ON CONFLICT (source_id, schema_version) DO UPDATE
SET fields = EXCLUDED.fields,
compatibility = EXCLUDED.compatibility,
registered_at = EXCLUDED.registered_at,
registered_by = EXCLUDED.registered_by`;
}
async getSchema(sourceId: string, version: number): Promise<RecordSchema | undefined> {
const rows = await this.sql<SchemaRow[]>`
SELECT source_id, schema_version, tenant_id, fields, compatibility, registered_at, registered_by
FROM opt_source_schemas
WHERE source_id = ${sourceId} AND schema_version = ${version}
LIMIT 1`;
return rows[0] ? toSchema(rows[0]) : undefined;
}
async getLatestSchema(sourceId: string): Promise<RecordSchema | undefined> {
const rows = await this.sql<SchemaRow[]>`
SELECT source_id, schema_version, tenant_id, fields, compatibility, registered_at, registered_by
FROM opt_source_schemas
WHERE source_id = ${sourceId}
ORDER BY schema_version DESC
LIMIT 1`;
return rows[0] ? toSchema(rows[0]) : undefined;
}
async listSchemas(sourceId: string): Promise<RecordSchema[]> {
const rows = await this.sql<SchemaRow[]>`
SELECT source_id, schema_version, tenant_id, fields, compatibility, registered_at, registered_by
FROM opt_source_schemas
WHERE source_id = ${sourceId}
ORDER BY schema_version ASC`;
return rows.map(toSchema);
}
// --- lineage -------------------------------------------------------------
async appendLineageEdges(edges: LineageEdge[]): Promise<void> {
for (const e of edges) {
await this.sql`
INSERT INTO opt_lineage_edges
(edge_id, tenant_id, run_id, capability_id, input_namespace, input_name, input_ref,
output_namespace, output_name, output_ref, event_time, correlation_id)
VALUES
(${e.edge_id}, ${e.tenant_id}, ${e.run_id}, ${e.capability_id}, ${e.input_namespace},
${e.input_name}, ${e.input_ref ?? null}, ${e.output_namespace}, ${e.output_name},
${e.output_ref ?? null}, ${e.event_time}, ${e.correlation_id ?? null})
ON CONFLICT (edge_id) DO NOTHING`;
}
}
async queryLineage(query: LineageQuery): Promise<LineageEdge[]> {
const limit = query.limit ?? 200;
const rows = await this.sql<LineageRow[]>`
SELECT edge_id, tenant_id, run_id, capability_id, input_namespace, input_name, input_ref,
output_namespace, output_name, output_ref, event_time, correlation_id
FROM opt_lineage_edges
WHERE tenant_id = ${query.tenant_id}
${query.output_name ? this.sql`AND output_name = ${query.output_name}` : this.sql``}
${query.input_name ? this.sql`AND input_name = ${query.input_name}` : this.sql``}
ORDER BY event_time DESC, edge_id DESC
LIMIT ${limit}`;
return rows.map((r) => ({
edge_id: r.edge_id,
tenant_id: r.tenant_id,
run_id: r.run_id,
capability_id: r.capability_id,
input_namespace: r.input_namespace,
input_name: r.input_name,
input_ref: r.input_ref ?? undefined,
output_namespace: r.output_namespace,
output_name: r.output_name,
output_ref: r.output_ref ?? undefined,
event_time: toIso(r.event_time),
correlation_id: r.correlation_id ?? undefined,
}));
}
}
interface SchemaRow {
source_id: string;
schema_version: number;
tenant_id: string;
fields: RecordSchemaFields;
compatibility: string;
registered_at: string | Date;
registered_by: string | null;
}
function toSchema(r: SchemaRow): RecordSchema {
return {
source_id: r.source_id,
schema_version: Number(r.schema_version),
tenant_id: r.tenant_id,
fields: r.fields,
compatibility: r.compatibility as CompatibilityPolicy,
registered_at: toIso(r.registered_at),
registered_by: r.registered_by ?? undefined,
};
}
interface LineageRow {
edge_id: string;
tenant_id: string;
run_id: string;
capability_id: string;
input_namespace: string;
input_name: string;
input_ref: string | null;
output_namespace: string;
output_name: string;
output_ref: string | null;
event_time: string | Date;
correlation_id: string | null;
}
@@ -0,0 +1,297 @@
/**
* src/repositories/postgres-source-registry-repository.ts
* ==========================================================
* Real Postgres backing for SourceRegistryRepository, against
* `opt_source_rights` / `opt_source_provenance` / `opt_source_health_checks`
* / `opt_source_freshness` (sql/002_source_registry.sql). Rights and
* provenance are one-row-per-source, upserted (matching the Map.set
* replace-in-place semantics they replace); health checks are append-only,
* bounded to the latest 100 rows per source_id after every insert; freshness
* is a single upserted "last success" row per source.
*/
import type {
AuthorizationBasis,
SourceAuthorization,
SourceHealthCheck,
SourceHealthStatus,
SourceProvenance,
SourceRights,
SourceSchedule,
} from "../types/source-registry";
import type { RepositorySql } from "./db";
import type { SourceRegistryRepository } from "./source-registry-repository";
function toIsoString(v: string | Date): string {
return v instanceof Date ? v.toISOString() : v;
}
interface RightsRow {
source_id: string;
tenant_id: string;
license_id: string;
license_url: string | null;
allowed_purposes: string[];
pii_allowed: boolean;
redistribution: string;
attribution: string | null;
verified_at: string;
verified_by: string;
notes: string | null;
}
function toRights(r: RightsRow): SourceRights {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
license_id: r.license_id,
license_url: r.license_url ?? undefined,
allowed_purposes: r.allowed_purposes ?? [],
pii_allowed: r.pii_allowed,
redistribution: r.redistribution as SourceRights["redistribution"],
attribution: r.attribution ?? undefined,
verified_at: r.verified_at,
verified_by: r.verified_by,
notes: r.notes ?? undefined,
};
}
interface ProvenanceRow {
source_id: string;
tenant_id: string;
method: string;
authority: string | null;
compliance_evidence_ref: string | null;
cadence: string | null;
freshness_sla_hours: string | number | null;
updated_at: string | Date;
}
function toProvenance(r: ProvenanceRow): SourceProvenance {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
method: r.method as SourceProvenance["method"],
authority: r.authority ?? undefined,
compliance_evidence_ref: r.compliance_evidence_ref ?? undefined,
cadence: r.cadence ?? undefined,
freshness_sla_hours: r.freshness_sla_hours === null ? undefined : Number(r.freshness_sla_hours),
updated_at: toIsoString(r.updated_at),
};
}
interface HealthCheckRow {
source_id: string;
tenant_id: string;
status: string;
checked_at: string | Date;
latency_ms: number | null;
detail: string | null;
}
function toHealthCheck(r: HealthCheckRow): SourceHealthCheck {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
status: r.status as SourceHealthStatus,
checked_at: toIsoString(r.checked_at),
latency_ms: r.latency_ms ?? undefined,
detail: r.detail ?? undefined,
};
}
export class PostgresSourceRegistryRepository implements SourceRegistryRepository {
constructor(private readonly sql: RepositorySql) {}
async setRights(rights: SourceRights): Promise<void> {
await this.sql`
INSERT INTO opt_source_rights
(source_id, tenant_id, license_id, license_url, allowed_purposes, pii_allowed, redistribution, attribution, verified_at, verified_by, notes, updated_at)
VALUES
(${rights.source_id}, ${rights.tenant_id}, ${rights.license_id}, ${rights.license_url ?? null},
${this.sql.array(rights.allowed_purposes)}, ${rights.pii_allowed}, ${rights.redistribution},
${rights.attribution ?? null}, ${rights.verified_at}, ${rights.verified_by}, ${rights.notes ?? null}, now())
ON CONFLICT (source_id) DO UPDATE SET
tenant_id = EXCLUDED.tenant_id,
license_id = EXCLUDED.license_id,
license_url = EXCLUDED.license_url,
allowed_purposes = EXCLUDED.allowed_purposes,
pii_allowed = EXCLUDED.pii_allowed,
redistribution = EXCLUDED.redistribution,
attribution = EXCLUDED.attribution,
verified_at = EXCLUDED.verified_at,
verified_by = EXCLUDED.verified_by,
notes = EXCLUDED.notes,
updated_at = now()`;
}
async getRights(sourceId: string): Promise<SourceRights | undefined> {
const rows = await this.sql<RightsRow[]>`
SELECT source_id, tenant_id, license_id, license_url, allowed_purposes, pii_allowed, redistribution, attribution, verified_at, verified_by, notes
FROM opt_source_rights WHERE source_id = ${sourceId} LIMIT 1`;
return rows[0] ? toRights(rows[0]) : undefined;
}
async setProvenance(prov: SourceProvenance): Promise<void> {
await this.sql`
INSERT INTO opt_source_provenance
(source_id, tenant_id, method, authority, compliance_evidence_ref, cadence, freshness_sla_hours, updated_at)
VALUES
(${prov.source_id}, ${prov.tenant_id}, ${prov.method}, ${prov.authority ?? null},
${prov.compliance_evidence_ref ?? null}, ${prov.cadence ?? null}, ${prov.freshness_sla_hours ?? null}, ${prov.updated_at})
ON CONFLICT (source_id) DO UPDATE SET
tenant_id = EXCLUDED.tenant_id,
method = EXCLUDED.method,
authority = EXCLUDED.authority,
compliance_evidence_ref = EXCLUDED.compliance_evidence_ref,
cadence = EXCLUDED.cadence,
freshness_sla_hours = EXCLUDED.freshness_sla_hours,
updated_at = EXCLUDED.updated_at`;
}
async getProvenance(sourceId: string): Promise<SourceProvenance | undefined> {
const rows = await this.sql<ProvenanceRow[]>`
SELECT source_id, tenant_id, method, authority, compliance_evidence_ref, cadence, freshness_sla_hours, updated_at
FROM opt_source_provenance WHERE source_id = ${sourceId} LIMIT 1`;
return rows[0] ? toProvenance(rows[0]) : undefined;
}
async recordSuccess(sourceId: string, tenantId: string, atIso: string): Promise<void> {
await this.sql`
INSERT INTO opt_source_freshness (source_id, tenant_id, last_success_at)
VALUES (${sourceId}, ${tenantId}, ${atIso})
ON CONFLICT (source_id) DO UPDATE SET
last_success_at = EXCLUDED.last_success_at,
tenant_id = EXCLUDED.tenant_id`;
}
async getLastSuccess(sourceId: string): Promise<string | undefined> {
const rows = await this.sql<{ last_success_at: string | Date }[]>`
SELECT last_success_at FROM opt_source_freshness WHERE source_id = ${sourceId} LIMIT 1`;
return rows[0] ? toIsoString(rows[0].last_success_at) : undefined;
}
// --- P060 authorization / schedule ---------------------------------------
async setAuthorization(auth: SourceAuthorization): Promise<void> {
await this.sql`
INSERT INTO opt_source_authorization
(source_id, tenant_id, basis, granted_by, granted_at, expires_at, evidence_ref, notes)
VALUES
(${auth.source_id}, ${auth.tenant_id}, ${auth.basis}, ${auth.granted_by}, ${auth.granted_at},
${auth.expires_at ?? null}, ${auth.evidence_ref ?? null}, ${auth.notes ?? null})
ON CONFLICT (source_id) DO UPDATE
SET tenant_id = EXCLUDED.tenant_id,
basis = EXCLUDED.basis,
granted_by = EXCLUDED.granted_by,
granted_at = EXCLUDED.granted_at,
expires_at = EXCLUDED.expires_at,
evidence_ref = EXCLUDED.evidence_ref,
notes = EXCLUDED.notes,
updated_at = now()`;
}
async getAuthorization(sourceId: string): Promise<SourceAuthorization | undefined> {
const rows = await this.sql<AuthorizationRow[]>`
SELECT source_id, tenant_id, basis, granted_by, granted_at, expires_at, evidence_ref, notes
FROM opt_source_authorization WHERE source_id = ${sourceId} LIMIT 1`;
return rows[0] ? toAuthorization(rows[0]) : undefined;
}
async setSchedule(schedule: SourceSchedule): Promise<void> {
await this.sql`
INSERT INTO opt_source_schedule
(source_id, tenant_id, mode, interval_seconds, cron, enabled, updated_at)
VALUES
(${schedule.source_id}, ${schedule.tenant_id}, ${schedule.mode},
${schedule.interval_seconds ?? null}, ${schedule.cron ?? null}, ${schedule.enabled},
${schedule.updated_at})
ON CONFLICT (source_id) DO UPDATE
SET tenant_id = EXCLUDED.tenant_id,
mode = EXCLUDED.mode,
interval_seconds = EXCLUDED.interval_seconds,
cron = EXCLUDED.cron,
enabled = EXCLUDED.enabled,
updated_at = EXCLUDED.updated_at`;
}
async getSchedule(sourceId: string): Promise<SourceSchedule | undefined> {
const rows = await this.sql<ScheduleRow[]>`
SELECT source_id, tenant_id, mode, interval_seconds, cron, enabled, updated_at
FROM opt_source_schedule WHERE source_id = ${sourceId} LIMIT 1`;
return rows[0] ? toSchedule(rows[0]) : undefined;
}
async appendHealthCheck(check: SourceHealthCheck): Promise<void> {
await this.sql`
INSERT INTO opt_source_health_checks (source_id, tenant_id, status, checked_at, latency_ms, detail)
VALUES (${check.source_id}, ${check.tenant_id}, ${check.status}, ${check.checked_at}, ${check.latency_ms ?? null}, ${check.detail ?? null})`;
// Bounded history -- keep only the latest 100 observations per source
// (health is an operational signal, not an audit log; AUD0 owns history),
// same bound InMemorySourceRegistryRepository enforces on write.
await this.sql`
DELETE FROM opt_source_health_checks
WHERE source_id = ${check.source_id}
AND health_check_id NOT IN (
SELECT health_check_id FROM opt_source_health_checks
WHERE source_id = ${check.source_id}
ORDER BY checked_at DESC, health_check_id DESC
LIMIT 100
)`;
}
async listHealthChecks(sourceId: string, limit = 100): Promise<SourceHealthCheck[]> {
const rows = await this.sql<HealthCheckRow[]>`
SELECT source_id, tenant_id, status, checked_at, latency_ms, detail
FROM opt_source_health_checks
WHERE source_id = ${sourceId}
ORDER BY checked_at DESC, health_check_id DESC
LIMIT ${limit}`;
return rows.map(toHealthCheck);
}
}
interface AuthorizationRow {
source_id: string;
tenant_id: string;
basis: string;
granted_by: string;
granted_at: string | Date;
expires_at: string | Date | null;
evidence_ref: string | null;
notes: string | null;
}
function toAuthorization(r: AuthorizationRow): SourceAuthorization {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
basis: r.basis as AuthorizationBasis,
granted_by: r.granted_by,
granted_at: toIsoString(r.granted_at),
expires_at: r.expires_at ? toIsoString(r.expires_at) : undefined,
evidence_ref: r.evidence_ref ?? undefined,
notes: r.notes ?? undefined,
};
}
interface ScheduleRow {
source_id: string;
tenant_id: string;
mode: string;
interval_seconds: number | string | null;
cron: string | null;
enabled: boolean;
updated_at: string | Date;
}
function toSchedule(r: ScheduleRow): SourceSchedule {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
mode: r.mode as SourceSchedule["mode"],
interval_seconds: r.interval_seconds === null ? undefined : Number(r.interval_seconds),
cron: r.cron ?? undefined,
enabled: r.enabled,
updated_at: toIsoString(r.updated_at),
};
}
@@ -0,0 +1,112 @@
/**
* src/repositories/postgres-source-repository.ts
* =================================================
* Real Postgres backing for SourceRepository, against `opt_sources`
* (sql/002_source_registry.sql). Same validation/error semantics as
* InMemorySourceRepository ("already exists", "name is required", "not
* found" -- exact message text preserved so every existing caller/test that
* matches on those strings keeps working unmodified).
*/
import type { CreateSourceInput, Source, SourceStatus, SourceType } from "../types/source";
import type { RepositorySql } from "./db";
import type { SourceListFilter, SourceRepository } from "./source-repository";
interface SourceRow {
source_id: string;
tenant_id: string;
project_id: string;
source_type: string;
name: string;
adapter_id: string | null;
access: string | null;
description: string | null;
status: string;
correlation_id: string | null;
created_at: string | Date;
updated_at: string | Date | null;
created_by: string | null;
owner_id: string | null;
}
function toIsoString(v: string | Date): string {
return v instanceof Date ? v.toISOString() : v;
}
function toSource(r: SourceRow): Source {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
project_id: r.project_id,
source_type: r.source_type as SourceType,
name: r.name,
adapter_id: r.adapter_id ?? undefined,
access: (r.access as Source["access"]) ?? undefined,
description: r.description ?? undefined,
status: r.status as SourceStatus,
correlation_id: r.correlation_id ?? undefined,
created_at: toIsoString(r.created_at),
updated_at: r.updated_at ? toIsoString(r.updated_at) : undefined,
created_by: r.created_by ?? undefined,
owner_id: r.owner_id ?? undefined,
};
}
export class PostgresSourceRepository implements SourceRepository {
constructor(private readonly sql: RepositorySql) {}
async create(input: CreateSourceInput): Promise<Source> {
if (!input.name) throw new Error("name is required");
const existing = await this.sql<{ source_id: string }[]>`
SELECT source_id FROM opt_sources WHERE source_id = ${input.source_id} LIMIT 1`;
if (existing.length > 0) {
throw new Error(`Source ${input.source_id} already exists`);
}
const rows = await this.sql<SourceRow[]>`
INSERT INTO opt_sources
(source_id, tenant_id, project_id, source_type, name, adapter_id, access, description, status, correlation_id, created_by, owner_id)
VALUES
(${input.source_id}, ${input.tenant_id}, ${input.project_id}, ${input.source_type}, ${input.name},
${input.adapter_id ?? null}, ${input.access ?? null}, ${input.description ?? null},
${input.status ?? "pending"}, ${input.correlation_id ?? null}, ${input.created_by ?? null},
${input.owner_id ?? null})
RETURNING source_id, tenant_id, project_id, source_type, name, adapter_id, access, description,
status, correlation_id, created_at, updated_at, created_by, owner_id`;
return toSource(rows[0]);
}
async get(sourceId: string): Promise<Source> {
const rows = await this.sql<SourceRow[]>`
SELECT source_id, tenant_id, project_id, source_type, name, adapter_id, access, description,
status, correlation_id, created_at, updated_at, created_by, owner_id
FROM opt_sources WHERE source_id = ${sourceId} LIMIT 1`;
if (!rows[0]) throw new Error(`Source ${sourceId} not found`);
return toSource(rows[0]);
}
async updateStatus(sourceId: string, status: SourceStatus): Promise<Source> {
const rows = await this.sql<SourceRow[]>`
UPDATE opt_sources
SET status = ${status}, updated_at = now()
WHERE source_id = ${sourceId}
RETURNING source_id, tenant_id, project_id, source_type, name, adapter_id, access, description,
status, correlation_id, created_at, updated_at, created_by, owner_id`;
if (!rows[0]) throw new Error(`Source ${sourceId} not found`);
return toSource(rows[0]);
}
async list(filter?: SourceListFilter): Promise<Source[]> {
const rows = await this.sql<SourceRow[]>`
SELECT source_id, tenant_id, project_id, source_type, name, adapter_id, access, description,
status, correlation_id, created_at, updated_at, created_by, owner_id
FROM opt_sources
WHERE 1=1
${filter?.tenant_id ? this.sql`AND tenant_id = ${filter.tenant_id}` : this.sql``}
${filter?.project_id ? this.sql`AND project_id = ${filter.project_id}` : this.sql``}
${filter?.source_type ? this.sql`AND source_type = ${filter.source_type}` : this.sql``}
${filter?.status ? this.sql`AND status = ${filter.status}` : this.sql``}
ORDER BY created_at ASC`;
return rows.map(toSource);
}
}
@@ -0,0 +1,186 @@
import { resolveStoreMode } from "../platform/dependency-mode";
import { SiaxError } from "../platform/errors";
import type { SearchIndexDefinition, SearchFieldType } from "../search/search-types";
import { getRepositorySql, repositoryDatabaseUrl, type RepositorySql } from "./db";
export interface SearchDefinitionSaveResult {
definition: SearchIndexDefinition;
created: boolean;
created_at: string;
created_by?: string;
}
export interface SearchDefinitionRepository {
save(definition: SearchIndexDefinition, actorId?: string): Promise<SearchDefinitionSaveResult>;
latest(indexName: string): Promise<SearchIndexDefinition | undefined>;
listLatest(): Promise<SearchIndexDefinition[]>;
}
interface DefinitionRow {
index_name: string;
version: number;
fields: Record<string, SearchFieldType>;
default_search_fields: string[];
created_at: string | Date;
created_by: string | null;
}
function iso(value: string | Date): string {
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
function toDefinition(row: DefinitionRow): SearchIndexDefinition {
return {
index_name: row.index_name,
version: Number(row.version),
fields: { ...row.fields },
default_search_fields: [...row.default_search_fields],
};
}
function toSaveResult(row: DefinitionRow, created: boolean): SearchDefinitionSaveResult {
return {
definition: toDefinition(row),
created,
created_at: iso(row.created_at),
...(row.created_by ? { created_by: row.created_by } : {}),
};
}
function fingerprint(definition: SearchIndexDefinition): string {
return JSON.stringify({
index_name: definition.index_name,
version: definition.version,
fields: Object.fromEntries(Object.entries(definition.fields).sort(([a], [b]) => a.localeCompare(b))),
default_search_fields: [...definition.default_search_fields],
});
}
interface MemoryRecord {
definition: SearchIndexDefinition;
created_at: string;
created_by?: string;
}
export class InMemorySearchDefinitionRepository implements SearchDefinitionRepository {
private readonly versions = new Map<string, MemoryRecord[]>();
async save(definition: SearchIndexDefinition, actorId?: string): Promise<SearchDefinitionSaveResult> {
const list = this.versions.get(definition.index_name) ?? [];
const existing = list.find((item) => item.definition.version === definition.version);
if (existing) {
if (fingerprint(existing.definition) !== fingerprint(definition)) {
throw new SiaxError("CONFLICT", "0pt.search", "search definition version reused with different schema");
}
return {
definition: {
...existing.definition,
fields: { ...existing.definition.fields },
default_search_fields: [...existing.definition.default_search_fields],
},
created: false,
created_at: existing.created_at,
...(existing.created_by ? { created_by: existing.created_by } : {}),
};
}
const expected = (list[list.length - 1]?.definition.version ?? 0) + 1;
if (definition.version !== expected) {
throw new SiaxError("CONFLICT", "0pt.search", `next search definition version must be ${expected}`);
}
const copy = {
...definition,
fields: { ...definition.fields },
default_search_fields: [...definition.default_search_fields],
};
const record: MemoryRecord = {
definition: copy,
created_at: new Date().toISOString(),
...(actorId ? { created_by: actorId } : {}),
};
list.push(record);
this.versions.set(definition.index_name, list);
return { definition: copy, created: true, created_at: record.created_at, ...(actorId ? { created_by: actorId } : {}) };
}
async latest(indexName: string): Promise<SearchIndexDefinition | undefined> {
const list = this.versions.get(indexName) ?? [];
const item = list[list.length - 1]?.definition;
return item ? { ...item, fields: { ...item.fields }, default_search_fields: [...item.default_search_fields] } : undefined;
}
async listLatest(): Promise<SearchIndexDefinition[]> {
const result: SearchIndexDefinition[] = [];
for (const key of this.versions.keys()) {
const latest = await this.latest(key);
if (latest) result.push(latest);
}
return result.sort((a, b) => a.index_name.localeCompare(b.index_name));
}
}
export class PostgresSearchDefinitionRepository implements SearchDefinitionRepository {
constructor(private readonly sql: RepositorySql) {}
async save(definition: SearchIndexDefinition, actorId?: string): Promise<SearchDefinitionSaveResult> {
return this.sql.begin(async (tx) => {
await tx`SELECT pg_advisory_xact_lock(hashtext(${`0pt-search:${definition.index_name}`}))`;
const same = await tx<DefinitionRow[]>`
SELECT index_name, version, fields, default_search_fields, created_at, created_by
FROM opt_search_index_definitions
WHERE index_name = ${definition.index_name} AND version = ${definition.version}
LIMIT 1`;
if (same[0]) {
const existing = toDefinition(same[0]);
if (fingerprint(existing) !== fingerprint(definition)) {
throw new SiaxError("CONFLICT", "0pt.search", "search definition version reused with different schema");
}
return toSaveResult(same[0], false);
}
const latest = await tx<{ version: number }[]>`
SELECT COALESCE(max(version), 0)::int AS version
FROM opt_search_index_definitions
WHERE index_name = ${definition.index_name}`;
const expected = (latest[0]?.version ?? 0) + 1;
if (definition.version !== expected) {
throw new SiaxError("CONFLICT", "0pt.search", `next search definition version must be ${expected}`);
}
const rows = await tx<DefinitionRow[]>`
INSERT INTO opt_search_index_definitions
(index_name, version, fields, default_search_fields, created_by)
VALUES
(${definition.index_name}, ${definition.version},
${tx.json(definition.fields as Parameters<RepositorySql["json"]>[0])},
${tx.array(definition.default_search_fields)}, ${actorId ?? null})
RETURNING index_name, version, fields, default_search_fields, created_at, created_by`;
return toSaveResult(rows[0], true);
});
}
async latest(indexName: string): Promise<SearchIndexDefinition | undefined> {
const rows = await this.sql<DefinitionRow[]>`
SELECT index_name, version, fields, default_search_fields, created_at, created_by
FROM opt_search_index_definitions
WHERE index_name = ${indexName}
ORDER BY version DESC
LIMIT 1`;
return rows[0] ? toDefinition(rows[0]) : undefined;
}
async listLatest(): Promise<SearchIndexDefinition[]> {
const rows = await this.sql<DefinitionRow[]>`
SELECT DISTINCT ON (index_name)
index_name, version, fields, default_search_fields, created_at, created_by
FROM opt_search_index_definitions
ORDER BY index_name, version DESC`;
return rows.map(toDefinition);
}
}
export function createSearchDefinitionRepository(databaseUrl?: string): SearchDefinitionRepository {
const mode = resolveStoreMode("0pt.search_definitions", databaseUrl ?? repositoryDatabaseUrl());
return mode.mode === "postgres"
? new PostgresSearchDefinitionRepository(getRepositorySql(mode.url))
: new InMemorySearchDefinitionRepository();
}
@@ -0,0 +1,59 @@
/**
* src/repositories/source-registry-repository.ts
* =================================================
* Storage seam for the four Maps src/services/source-registry-service.ts
* used to hold rights, provenance, health checks, and last-success
* timestamps. Same split as source-repository.ts: one interface, an
* in-memory implementation (extracted verbatim) and a Postgres
* implementation (sql/002_source_registry.sql's `opt_source_rights`,
* `opt_source_provenance`, `opt_source_health_checks`, `opt_source_freshness`
* tables), chosen once via `resolveStoreMode`.
*
* Tenant isolation is NOT this layer's job -- exactly as before, when these
* were bare Maps keyed only by source_id. SourceRegistryService's
* `assertSourceTenant` gate is what enforces the cross-tenant NOT_FOUND
* posture (§50), and it runs before every call into this repository. This
* layer trusts the caller, same as the Maps did.
*/
import { resolveStoreMode } from "../platform/dependency-mode";
import type {
SourceAuthorization,
SourceHealthCheck,
SourceProvenance,
SourceRights,
SourceSchedule,
} from "../types/source-registry";
import { getRepositorySql, repositoryDatabaseUrl } from "./db";
import { InMemorySourceRegistryRepository } from "./in-memory-source-registry-repository";
import { PostgresSourceRegistryRepository } from "./postgres-source-registry-repository";
export interface SourceRegistryRepository {
setRights(rights: SourceRights): Promise<void>;
getRights(sourceId: string): Promise<SourceRights | undefined>;
setProvenance(prov: SourceProvenance): Promise<void>;
getProvenance(sourceId: string): Promise<SourceProvenance | undefined>;
recordSuccess(sourceId: string, tenantId: string, atIso: string): Promise<void>;
getLastSuccess(sourceId: string): Promise<string | undefined>;
/** P060 authorization — the recorded decision that 0pt may connect at all. */
setAuthorization(auth: SourceAuthorization): Promise<void>;
getAuthorization(sourceId: string): Promise<SourceAuthorization | undefined>;
/** P060 schedule — ingestion mode + cadence. */
setSchedule(schedule: SourceSchedule): Promise<void>;
getSchedule(sourceId: string): Promise<SourceSchedule | undefined>;
appendHealthCheck(check: SourceHealthCheck): Promise<void>;
/** Newest-first, bounded to the latest `limit` observations (default 100) -- health is an operational signal, not an audit log; AUD0 owns history. */
listHealthChecks(sourceId: string, limit?: number): Promise<SourceHealthCheck[]>;
}
export function createSourceRegistryRepository(databaseUrl?: string): SourceRegistryRepository {
const mode = resolveStoreMode("0pt.source_registry.metadata", databaseUrl ?? repositoryDatabaseUrl());
if (mode.mode === "postgres") {
return new PostgresSourceRegistryRepository(getRepositorySql(mode.url));
}
return new InMemorySourceRegistryRepository();
}
+50
View File
@@ -0,0 +1,50 @@
/**
* src/repositories/source-repository.ts
* =======================================
* Storage seam for src/services/source-service.ts (0pt.source.schema.v1).
* Extracted from what used to be a bare `new Map()` inside SourceService
* itself so the same business logic (validation, "already exists"/"not
* found" semantics, filtering) can run against either an in-memory Map
* (tests, local dev, non-production with no DATABASE_URL) or real Postgres
* (sql/002_source_registry.sql's `opt_sources` table) without the service
* layer knowing which.
*
* `createSourceRepository` is the single choice point, delegating to
* `resolveStoreMode` (src/platform/dependency-mode.ts) -- same
* production-safety contract as every other P0 store: no DATABASE_URL in a
* production runtime throws DEPENDENCY_UNAVAILABLE at construction rather
* than silently serving the in-memory fallback.
*/
import { resolveStoreMode } from "../platform/dependency-mode";
import type { CreateSourceInput, Source, SourceStatus, SourceType } from "../types/source";
import { getRepositorySql, repositoryDatabaseUrl } from "./db";
import { InMemorySourceRepository } from "./in-memory-source-repository";
import { PostgresSourceRepository } from "./postgres-source-repository";
export interface SourceListFilter {
tenant_id?: string;
project_id?: string;
source_type?: SourceType;
status?: SourceStatus;
}
export interface SourceRepository {
create(input: CreateSourceInput): Promise<Source>;
/** Throws (message contains "not found") when no such source exists -- matches the pre-migration Map behavior every caller already handles. */
get(sourceId: string): Promise<Source>;
list(filter?: SourceListFilter): Promise<Source[]>;
/**
* P060: the only way a source's lifecycle status changes. Deliberately NOT
* a general `update` -- status is the field the activation gate protects,
* and a generic patch method would be the obvious way around it.
*/
updateStatus(sourceId: string, status: SourceStatus): Promise<Source>;
}
export function createSourceRepository(databaseUrl?: string): SourceRepository {
const mode = resolveStoreMode("0pt.source_registry.sources", databaseUrl ?? repositoryDatabaseUrl());
if (mode.mode === "postgres") {
return new PostgresSourceRepository(getRepositorySql(mode.url));
}
return new InMemorySourceRepository();
}