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
+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);
}
}