Files
0pt/src/repositories/postgres-source-registry-repository.ts
T

298 lines
11 KiB
TypeScript

/**
* 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),
};
}