feat(data-os): Source Registry Postgres persistence + full HTTP route surface

Replaces the in-memory (per-instance, not even per-process-shared) Maps in
SourceService/SourceRegistryService with real Postgres persistence, and adds
the register/query/describe/health/rights/provenance/freshness HTTP routes
that never existed (grep for SourceRegistryService in app/ previously
returned nothing).

- sql/002_source_registry.sql: opt_sources, opt_source_rights,
  opt_source_provenance, opt_source_health_checks, opt_source_freshness.
  Numbered 002 (not 006) because 004's opt_source_rate_policies already
  forward-references opt_sources, which no sql/ file defined until now —
  fixes 004's pre-existing broken migration ordering (opt_datasets remains
  a separate, unrelated, still-open gap in 004, flagged not fixed).
- src/repositories/*: SourceRepository / SourceRegistryRepository seams,
  each with an in-memory implementation (business logic extracted verbatim)
  and a Postgres implementation, chosen via resolveStoreMode — production
  still fails hard with no DATABASE_URL (Master-DoD §3), but a configured
  production now actually works instead of always being blocked.
- SourceService / SourceRegistryService: storage moved behind the
  repository seam; getHealth/getFreshness are now async and tenant-scoped
  at the accessor itself (needed once they're reachable directly over HTTP,
  not only after an earlier caller's tenant check).
- src/services/source-registry.ts: shared singleton instances for the
  sources/* route group, fixing the "each route module owned its own
  private registry" defect (source-rate-policies and .../query previously
  couldn't see a source registered via POST /api/0pt/sources).
- New routes: POST/GET /api/0pt/sources, GET /api/0pt/sources/[id],
  GET+PUT .../rights, GET+PUT .../provenance, GET+POST .../health,
  GET .../freshness.
- Business logic unchanged: fail-closed purpose gate, cross-tenant
  NOT_FOUND (no existence oracle, §50), bounded 100-row health history.

Tested against a real Postgres container (not mocked) —
tests/p0/source-registry-postgres.realinfra.test.ts, env-gated on
SOURCE_REGISTRY_TEST_DATABASE_URL, skips honestly when unset. All 249
pre-existing P0 tests + 7 new realinfra tests pass; also smoke-tested the
full HTTP route surface end-to-end against next dev + live Postgres.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
Simon Axelsson
2026-09-01 20:42:41 +02:00
co-authored by Claude Sonnet 5
parent f8bb0d5ab9
commit 07b13bd833
26 changed files with 1578 additions and 177 deletions
+6 -2
View File
@@ -1,4 +1,8 @@
import type { SourceRatePolicy, SourceRatePolicyStatus, CreateSourceRatePolicyInput } from "../types/source-rate-policy";
import type {
SourceRatePolicy,
SourceRatePolicyStatus,
CreateSourceRatePolicyInput,
} from "../types/source-rate-policy";
import { createAud0Client, type Aud0Client } from "../clients/aud0-client";
import { SourceService } from "./source-service";
@@ -33,7 +37,7 @@ export class SourceRatePolicyService {
constructor(opts?: { aud0BaseUrl?: string; sourceService?: SourceService }) {
this.aud0 = createAud0Client(opts?.aud0BaseUrl);
this.sourceService = opts?.sourceService ?? new SourceService(opts?.aud0BaseUrl);
this.sourceService = opts?.sourceService ?? new SourceService({ aud0BaseUrl: opts?.aud0BaseUrl });
}
async createSourceRatePolicy(input: CreateSourceRatePolicyInput): Promise<SourceRatePolicy> {
+79 -48
View File
@@ -14,20 +14,33 @@
* Tenant isolation: every read path REQUIRES a tenant_id and filters on it —
* a source registered by tenant A is invisible to tenant B (tested in
* tests/p0/source-registry.test.ts, incl. the cross-tenant attack case §50).
* `getHealth`/`getFreshness` now take tenant_id directly and run the same
* `assertSourceTenant` gate every other accessor does — they are exposed as
* standalone HTTP routes now (app/api/0pt/sources/[sourceId]/health,
* .../freshness), so they can no longer rely on an earlier caller having
* already checked tenancy on their behalf.
*
* Purpose enforcement: `assertPurposeAllowed` is the single hook other 0pt
* capabilities call before using a source for a given purpose (SearchService
* and DatasetService both do). No rights record ⇒ fail closed (deny).
*
* Persistence: in-memory Maps behind the same "pure core, thin registry"
* shape as the sibling P0 services. Production boot is protected by
* `resolveStoreMode` in the composition root (app/api routes construct with
* the shared registry): with no database configured a production runtime
* throws DEPENDENCY_UNAVAILABLE instead of serving Maps (Master-DoD §3).
* Persistence: rights/provenance/health/freshness now live behind
* SourceRegistryRepository (src/repositories/source-registry-repository.ts)
* — real Postgres (`opt_source_rights`/`opt_source_provenance`/
* `opt_source_health_checks`/`opt_source_freshness`,
* sql/002_source_registry.sql) when DATABASE_URL is configured, in-memory
* Maps otherwise. `resolveStoreMode` still fails production boot hard with
* no DATABASE_URL (Master-DoD §3) — the difference from before is that a
* configured production now actually WORKS (opt_sources/etc. exist), not
* just fails safely.
*/
import { createAud0Client, type Aud0Client } from "../clients/aud0-client";
import { SiaxError } from "../platform/errors";
import { SourceService } from "./source-service";
import {
createSourceRegistryRepository,
type SourceRegistryRepository,
} from "../repositories/source-registry-repository";
import { SourceService, type SourceServiceOptions } from "./source-service";
import { SourceRatePolicyService } from "./source-rate-policy-service";
import type { CreateSourceInput, Source } from "../types/source";
import type {
@@ -46,21 +59,27 @@ export interface RegisterSourceInput extends CreateSourceInput {
}
export class SourceRegistryService {
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 repo: SourceRegistryRepository;
private readonly aud0: Aud0Client;
readonly sources: SourceService;
readonly ratePolicies: SourceRatePolicyService;
constructor(opts?: {
aud0BaseUrl?: string;
/** Explicit DATABASE_URL override — mainly for tests. Falls back to resolveStoreMode's own env lookup when omitted. */
databaseUrl?: string;
sourceService?: SourceService;
ratePolicyService?: SourceRatePolicyService;
/** Inject a repository directly (tests) — bypasses resolveStoreMode entirely. */
repository?: SourceRegistryRepository;
}) {
this.aud0 = createAud0Client(opts?.aud0BaseUrl);
this.sources = opts?.sourceService ?? new SourceService(opts?.aud0BaseUrl);
this.repo = opts?.repository ?? createSourceRegistryRepository(opts?.databaseUrl);
const sourceServiceOpts: SourceServiceOptions = {
aud0BaseUrl: opts?.aud0BaseUrl,
databaseUrl: opts?.databaseUrl,
};
this.sources = opts?.sourceService ?? new SourceService(sourceServiceOpts);
this.ratePolicies =
opts?.ratePolicyService ??
new SourceRatePolicyService({ aud0BaseUrl: opts?.aud0BaseUrl, sourceService: this.sources });
@@ -91,7 +110,7 @@ export class SourceRegistryService {
// -------------------------------------------------------------------------
async setRights(rights: SourceRights): Promise<SourceRights> {
await this.assertSourceTenant(rights.source_id, rights.tenant_id);
this.rights.set(rights.source_id, rights);
await this.repo.setRights(rights);
await this.emit("0pt.source_rights_set", rights.tenant_id, rights.source_id, {
license_id: rights.license_id,
allowed_purposes: rights.allowed_purposes,
@@ -102,7 +121,7 @@ export class SourceRegistryService {
async getRights(sourceId: string, tenantId: string): Promise<SourceRights | undefined> {
await this.assertSourceTenant(sourceId, tenantId);
return this.rights.get(sourceId);
return this.repo.getRights(sourceId);
}
/**
@@ -112,19 +131,19 @@ export class SourceRegistryService {
*/
async assertPurposeAllowed(sourceId: string, tenantId: string, purpose: string): Promise<SourceRights> {
await this.assertSourceTenant(sourceId, tenantId);
const rights = this.rights.get(sourceId);
const rights = await this.repo.getRights(sourceId);
if (!rights) {
throw new SiaxError(
"AUTHORIZATION_DENIED",
"0pt.source_registry",
`source ${sourceId} has no rights record — purpose "${purpose}" denied (fail closed)`
`source ${sourceId} has no rights record — purpose "${purpose}" denied (fail closed)`,
);
}
if (!rights.allowed_purposes.includes(purpose)) {
throw new SiaxError(
"AUTHORIZATION_DENIED",
"0pt.source_registry",
`purpose "${purpose}" is not in source ${sourceId}'s allowed purposes`
`purpose "${purpose}" is not in source ${sourceId}'s allowed purposes`,
);
}
return rights;
@@ -135,7 +154,7 @@ export class SourceRegistryService {
// -------------------------------------------------------------------------
async setProvenance(prov: SourceProvenance): Promise<SourceProvenance> {
await this.assertSourceTenant(prov.source_id, prov.tenant_id);
this.provenance.set(prov.source_id, prov);
await this.repo.setProvenance(prov);
await this.emit("0pt.source_provenance_set", prov.tenant_id, prov.source_id, {
method: prov.method,
authority: prov.authority,
@@ -146,18 +165,19 @@ export class SourceRegistryService {
async getProvenance(sourceId: string, tenantId: string): Promise<SourceProvenance | undefined> {
await this.assertSourceTenant(sourceId, tenantId);
return this.provenance.get(sourceId);
return this.repo.getProvenance(sourceId);
}
/** Record a successful data observation (drives freshness). */
async recordSuccess(sourceId: string, tenantId: string, atIso?: string): Promise<void> {
await this.assertSourceTenant(sourceId, tenantId);
this.lastSuccess.set(sourceId, atIso ?? new Date().toISOString());
await this.repo.recordSuccess(sourceId, tenantId, atIso ?? new Date().toISOString());
}
getFreshness(sourceId: string, now: Date = new Date()): SourceFreshness {
const prov = this.provenance.get(sourceId);
const last = this.lastSuccess.get(sourceId);
async getFreshness(sourceId: string, tenantId: string, now: Date = new Date()): Promise<SourceFreshness> {
await this.assertSourceTenant(sourceId, tenantId);
const prov = await this.repo.getProvenance(sourceId);
const last = await this.repo.getLastSuccess(sourceId);
const sla = prov?.freshness_sla_hours;
if (!last) {
return { source_id: sourceId, freshness_sla_hours: sla, fresh: sla === undefined };
@@ -177,24 +197,21 @@ export class SourceRegistryService {
// -------------------------------------------------------------------------
async recordHealthCheck(check: SourceHealthCheck): Promise<SourceHealth> {
await this.assertSourceTenant(check.source_id, check.tenant_id);
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);
await this.repo.appendHealthCheck(check);
if (check.status === "up") {
await this.recordSuccess(check.source_id, check.tenant_id, check.checked_at);
}
return this.getHealth(check.source_id);
return this.getHealth(check.source_id, check.tenant_id);
}
getHealth(sourceId: string): SourceHealth {
const list = this.healthChecks.get(sourceId) ?? [];
const last = list[list.length - 1];
async getHealth(sourceId: string, tenantId: string): Promise<SourceHealth> {
await this.assertSourceTenant(sourceId, tenantId);
// Newest-first (repository contract) — index 0 is the most recent check.
const list = await this.repo.listHealthChecks(sourceId);
const last = list[0];
let consecutiveFailures = 0;
for (let i = list.length - 1; i >= 0; i--) {
if (list[i].status === "down" || list[i].status === "degraded") consecutiveFailures++;
for (const check of list) {
if (check.status === "down" || check.status === "degraded") consecutiveFailures++;
else break;
}
const status: SourceHealthStatus = last?.status ?? "unknown";
@@ -223,27 +240,41 @@ export class SourceRegistryService {
source_type: filter.source_type,
status: filter.status,
});
if (filter.purpose !== undefined) {
results = results.filter((s) => {
const rights = this.rights.get(s.source_id);
return rights !== undefined && rights.allowed_purposes.includes(filter.purpose as string);
});
}
if (filter.redistribution !== undefined) {
results = results.filter((s) => this.rights.get(s.source_id)?.redistribution === filter.redistribution);
if (filter.purpose !== undefined || filter.redistribution !== undefined) {
const rightsEntries = await Promise.all(
results.map(async (s) => [s.source_id, await this.repo.getRights(s.source_id)] as const),
);
const rightsBySource = new Map(rightsEntries);
if (filter.purpose !== undefined) {
results = results.filter((s) => {
const rights = rightsBySource.get(s.source_id);
return rights !== undefined && rights.allowed_purposes.includes(filter.purpose as string);
});
}
if (filter.redistribution !== undefined) {
results = results.filter(
(s) => rightsBySource.get(s.source_id)?.redistribution === filter.redistribution,
);
}
}
return results;
}
async describeSource(sourceId: string, tenantId: string): Promise<SourceDescriptor> {
const source = await this.assertSourceTenant(sourceId, tenantId);
const policies = await this.ratePolicies.listSourceRatePolicies({ tenant_id: tenantId, source_id: sourceId });
const [policies, rights, provenance, health, freshness] = await Promise.all([
this.ratePolicies.listSourceRatePolicies({ tenant_id: tenantId, source_id: sourceId }),
this.repo.getRights(sourceId),
this.repo.getProvenance(sourceId),
this.getHealth(sourceId, tenantId),
this.getFreshness(sourceId, tenantId),
]);
return {
source,
rights: this.rights.get(sourceId),
provenance: this.provenance.get(sourceId),
health: this.getHealth(sourceId),
freshness: this.getFreshness(sourceId),
rights,
provenance,
health,
freshness,
rate_policy: policies[0],
};
}
@@ -276,7 +307,7 @@ export class SourceRegistryService {
eventType: string,
tenantId: string,
sourceId: string,
payload: Record<string, unknown>
payload: Record<string, unknown>,
): Promise<void> {
await this.aud0.ingestEvent({
event_id: `evt_${eventType}_${sourceId}_${Date.now()}`,
+30
View File
@@ -0,0 +1,30 @@
/**
* src/services/source-registry.ts
* =================================
* Shared singleton instances for the source-registry route group
* (app/api/0pt/sources/*), matching src/services/lakehouse-mapping-registry.ts's
* precedent.
*
* BEFORE_STATE.md §1 flagged this as materially worse than plain
* in-memory-per-module: each route file previously constructed its own
* `new SourceService()` (and `new SourceRatePolicyService()`), so a source
* registered via one route module was invisible to another within the same
* running process — "not even a shared process-wide singleton". Once
* DATABASE_URL is configured this stops mattering (state lives in Postgres,
* genuinely shared across processes/deploys — see src/repositories/*), but
* it still matters for the in-memory (no DATABASE_URL) dev/test mode, where
* state must be shared within one process to be usable at all. Constructing
* all three here once, wired together, and importing them everywhere fixes
* both call sites this repo already had (sources/rate-policies/*,
* sources/[sourceId]/query) plus every new route this pass adds.
*/
import { SourceService } from "./source-service";
import { SourceRatePolicyService } from "./source-rate-policy-service";
import { SourceRegistryService } from "./source-registry-service";
export const sourceService = new SourceService();
export const sourceRatePolicyService = new SourceRatePolicyService({ sourceService });
export const sourceRegistryService = new SourceRegistryService({
sourceService,
ratePolicyService: sourceRatePolicyService,
});
+43 -99
View File
@@ -7,107 +7,74 @@
* and `SourceRatePolicyService` (src/services/source-rate-policy-service.ts)
* both look a `source_id` up against — see docs/P0_QUERY_SOURCE_FLOW.md.
*
* Deliberately small and in-memory, same "pure core, thin registry" shape
* every other P0 service in this repo already uses; a real deployment backs
* this with `opt_sources`. In-memory scope: each `new SourceService()` owns
* its own registry — the pre-existing limitation docs/P0_QUERY_SOURCE_FLOW.md's
* "Known gaps" section documents (a Source registered via one API route module
* is not yet visible to another route module in the same running process).
* Callers that need a shared view pass an existing instance in via the
* `sourceService` constructor option, exactly like SourceQueryService and
* SourceRatePolicyService already do.
* Persistence: storage now lives behind SourceRepository
* (src/repositories/source-repository.ts) — real Postgres (`opt_sources`,
* sql/002_source_registry.sql) when DATABASE_URL is configured, an
* in-memory Map otherwise (non-production only; resolveStoreMode fails hard
* in production with no URL). This service still owns the business rules
* (validation, tenant-agnostic CRUD orchestration) and the AUD0 emission —
* only the storage moved.
*
* Registering a source emits a best-effort AUD0 `0pt.source_created` event —
* the same "no mutation without an evented trail" doctrine every other P0
* registry service follows. With no AUD0_URL configured that emission is a
* no-op (see aud0-client.ts), so this stays hermetic in tests and local dev.
* Callers that need a shared view across route modules should use the
* shared singleton in src/services/source-registry.ts rather than
* constructing a fresh `new SourceService()` per module — see that file's
* doc comment for the "each route owned its own registry" history this
* fixes.
*/
import { createAud0Client, type Aud0Client } from "../clients/aud0-client";
import {
createSourceRepository,
type SourceRepository,
type SourceListFilter,
} from "../repositories/source-repository";
import type { CreateSourceInput, Source, SourceStatus, SourceType } from "../types/source";
/**
* Storage shape: nullable columns, exactly as the eventual `opt_sources` table
* would hold them. `toSource()` converts back to the `Source` DTO (undefined
* rather than null) so callers never have to handle both.
*/
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;
export interface SourceServiceOptions {
aud0BaseUrl?: string;
/** Explicit DATABASE_URL override — mainly for tests pointing at a specific Postgres instance. Falls back to resolveStoreMode's own env lookup when omitted. */
databaseUrl?: string;
/** Inject a repository directly (tests) — bypasses resolveStoreMode entirely. */
repository?: SourceRepository;
}
export class SourceService {
private sources: Map<string, SourceRecord> = new Map();
private aud0: Aud0Client;
private readonly repo: SourceRepository;
private readonly aud0: Aud0Client;
constructor(aud0BaseUrl?: string) {
this.aud0 = createAud0Client(aud0BaseUrl);
constructor(opts?: SourceServiceOptions) {
this.aud0 = createAud0Client(opts?.aud0BaseUrl);
this.repo = opts?.repository ?? createSourceRepository(opts?.databaseUrl);
}
async createSource(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,
status: input.status ?? "active",
correlation_id: input.correlation_id ?? null,
created_at: now,
updated_at: null,
created_by: input.created_by ?? null,
};
this.sources.set(record.source_id, record);
const source = await this.repo.create(input);
await this.aud0.ingestEvent({
event_id: `evt_0pt_source_created_${record.source_id}`,
event_id: `evt_0pt_source_created_${source.source_id}`,
event_type: "0pt.source_created",
tenant_id: record.tenant_id,
project_id: record.project_id,
actor_id: record.created_by ?? "system",
tenant_id: source.tenant_id,
project_id: source.project_id,
actor_id: source.created_by ?? "system",
app_id: "0pt",
capability_id: "0pt.create_source",
resource_type: "source",
resource_id: record.source_id,
resource_id: source.source_id,
risk_level: "L2",
payload: {
source_type: record.source_type,
name: record.name,
adapter_id: record.adapter_id,
access: record.access,
source_type: source.source_type,
name: source.name,
adapter_id: source.adapter_id,
access: source.access,
},
created_at: now,
correlation_id: record.correlation_id ?? undefined,
created_at: source.created_at,
correlation_id: source.correlation_id,
});
return this.toSource(record);
return source;
}
async getSource(sourceId: string): Promise<Source> {
const record = this.sources.get(sourceId);
if (!record) throw new Error(`Source ${sourceId} not found`);
return this.toSource(record);
return this.repo.get(sourceId);
}
async listSources(filter?: {
@@ -116,29 +83,6 @@ export class SourceService {
source_type?: SourceType;
status?: SourceStatus;
}): 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((r) => this.toSource(r));
}
private 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,
};
return this.repo.list(filter as SourceListFilter | undefined);
}
}