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
@@ -0,0 +1,27 @@
/**
* app/api/0pt/sources/[sourceId]/freshness/route.ts
* =====================================================
* Freshness view derived from provenance's freshness_sla_hours + the last
* successful observation (recorded via POST .../health with status "up",
* or SourceRegistryService.recordSuccess directly). Read-only — there is no
* separate write path here by design; freshness is a derived signal, not
* its own record.
*/
import { NextRequest, NextResponse } from "next/server";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const freshness = await sourceRegistryService.getFreshness(sourceId, tenantId);
return NextResponse.json(freshness);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
@@ -0,0 +1,50 @@
/**
* app/api/0pt/sources/[sourceId]/health/route.ts
* ==================================================
* source.health — record a health observation (POST) and read the
* aggregate view (GET): status, last check, consecutive failures. Bounded
* history (latest 100 observations) — this is an operational signal, not
* an audit log; AUD0 owns history.
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, recordSourceHealthCheckSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const health = await sourceRegistryService.getHealth(sourceId, tenantId);
return NextResponse.json(health);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function POST(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const __raw = await request.json();
const __parsed = parseBody(recordSourceHealthCheckSchema, __raw);
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const health = await sourceRegistryService.recordHealthCheck({
source_id: sourceId,
tenant_id: body.tenant_id,
status: body.status,
checked_at: body.checked_at ?? new Date().toISOString(),
latency_ms: body.latency_ms,
detail: body.detail,
});
return NextResponse.json(health, { status: 201 });
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
@@ -0,0 +1,52 @@
/**
* app/api/0pt/sources/[sourceId]/provenance/route.ts
* ======================================================
* Per-SOURCE provenance/method metadata (Master-DoD §10) — HOW a source is
* obtained (official_api | bulk_download | authorized_web | licensed_feed |
* manual_upload), not per-field bridge_provenance. See BEFORE_STATE.md §3
* for that distinction: this route does not, and cannot, close the
* bridge_provenance gap — it only surfaces what SourceRegistryService
* already models at the source level.
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, setSourceProvenanceSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const provenance = await sourceRegistryService.getProvenance(sourceId, tenantId);
if (!provenance) {
return NextResponse.json({ error: `source ${sourceId} has no provenance record` }, { status: 404 });
}
return NextResponse.json(provenance);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function PUT(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const __raw = await request.json();
const __parsed = parseBody(setSourceProvenanceSchema, __raw);
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const provenance = await sourceRegistryService.setProvenance({
...body,
source_id: sourceId,
updated_at: new Date().toISOString(),
});
return NextResponse.json(provenance);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
+14 -17
View File
@@ -4,27 +4,24 @@
* 0pt.query_source — bounded synchronous query execution for a registered
* Source. Additive: does not modify sibling ../route.ts or ../../route.ts.
*
* NOTE — in-memory scope: this module instantiates its own SourceService,
* matching the existing sources/route.ts and sources/[sourceId]/route.ts
* pattern (each API route module owns a fresh in-memory registry, so state
* is not shared across route modules yet — see the "Singleton note" in
* src/services/document-capture-service.ts for prior art on this same repo
* limitation). A source registered via POST /api/0pt/sources will not be
* resolvable here until SourceService is backed by shared persistence.
* Correction: this comment previously claimed `sql/002_p0_dataset_quality.sql`
* already defined an `opt_sources` table for that. That file does not exist
* and never has (git log --all: zero commits, any branch, ever). sql/ today
* has only 001_init.sql and 004_iceberg_write_boundary.sql. The real fix —
* backing SourceService with real persistence — is still open; no migration
* for it exists yet.
* Details: docs/P0_QUERY_SOURCE_FLOW.md.
* UPDATED (Source Registry Postgres-persistence pass): now imports the
* shared `sourceService` singleton from src/services/source-registry.ts
* instead of constructing its own SourceService, closing the "not even a
* shared process-wide singleton" gap BEFORE_STATE.md §1 flagged (a source
* registered via POST /api/0pt/sources used to be invisible here). With
* DATABASE_URL configured this is doubly fixed — state lives in Postgres
* (sql/002_source_registry.sql), genuinely shared across processes, not
* just within one. Details: docs/P0_QUERY_SOURCE_FLOW.md.
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, sourceQuerySchema } from "@/src/validation/0pt-schemas";
import { SourceService } from "@/src/services/source-service";
import { SourceQueryService, SourceQueryTimeoutError, SourceQueryUnsupportedError } from "@/src/services/source-query-service";
import { sourceService } from "@/src/services/source-registry";
import {
SourceQueryService,
SourceQueryTimeoutError,
SourceQueryUnsupportedError,
} from "@/src/services/source-query-service";
const sourceService = new SourceService();
const queryService = new SourceQueryService({ sourceService });
export async function POST(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
@@ -0,0 +1,45 @@
/**
* app/api/0pt/sources/[sourceId]/rights/route.ts
* ==================================================
* Rights / license / purpose metadata (Master-DoD §10). PUT is an upsert
* (SourceRegistryService.setRights), matching the fail-closed purpose gate:
* no rights record at all denies every purpose until one is set here.
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, setSourceRightsSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const rights = await sourceRegistryService.getRights(sourceId, tenantId);
if (!rights) {
return NextResponse.json({ error: `source ${sourceId} has no rights record` }, { status: 404 });
}
return NextResponse.json(rights);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function PUT(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const __raw = await request.json();
const __parsed = parseBody(setSourceRightsSchema, __raw);
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const rights = await sourceRegistryService.setRights({ ...body, source_id: sourceId });
return NextResponse.json(rights);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
+26
View File
@@ -0,0 +1,26 @@
/**
* app/api/0pt/sources/[sourceId]/route.ts
* ==========================================
* source.describe — full SourceDescriptor (base + rights + provenance +
* health + freshness + rate policy). Cross-tenant probes get 404 NOT_FOUND
* (no existence oracle, §50) via SourceRegistryService.describeSource's
* assertSourceTenant gate.
*/
import { NextRequest, NextResponse } from "next/server";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const descriptor = await sourceRegistryService.describeSource(sourceId, tenantId);
return NextResponse.json(descriptor);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
@@ -1,9 +1,10 @@
import { NextResponse } from "next/server";
import { SourceRatePolicyService } from "@/src/services/source-rate-policy-service";
import { sourceRatePolicyService as service } from "@/src/services/source-registry";
const service = new SourceRatePolicyService();
export async function GET(_request: Request, { params }: { params: Promise<{ sourceRatePolicyId: string }> }) {
export async function GET(
_request: Request,
{ params }: { params: Promise<{ sourceRatePolicyId: string }> },
) {
try {
const { sourceRatePolicyId } = await params;
const policy = await service.getSourceRatePolicy(sourceRatePolicyId);
+1 -3
View File
@@ -1,8 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { parseBody, createSourceRatePolicySchema } from "@/src/validation/0pt-schemas";
import { SourceRatePolicyService } from "@/src/services/source-rate-policy-service";
const service = new SourceRatePolicyService();
import { sourceRatePolicyService as service } from "@/src/services/source-registry";
export async function POST(request: NextRequest) {
try {
+55
View File
@@ -0,0 +1,55 @@
/**
* app/api/0pt/sources/route.ts
* ==============================
* source.register (POST) + source.query (GET) — the P0 Source Registry
* route surface BEFORE_STATE.md §1 found entirely missing
* (`grep -rl "SourceRegistryService" app/` returned nothing). Backed by
* SourceRegistryService, which now persists to Postgres when DATABASE_URL
* is configured (src/repositories/*, sql/002_source_registry.sql).
*
* Uses the shared singleton from src/services/source-registry.ts, not a
* fresh `new SourceRegistryService()` per route module — see that file's
* doc comment.
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, registerSourceSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import type { SourceStatus, SourceType } from "@/src/types/source";
import type { SourceRights } from "@/src/types/source-registry";
export async function POST(request: NextRequest) {
try {
const __raw = await request.json();
const __parsed = parseBody(registerSourceSchema, __raw);
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
const descriptor = await sourceRegistryService.registerSource(body);
return NextResponse.json(descriptor, { status: 201 });
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const sources = await sourceRegistryService.querySources({
tenant_id: tenantId,
project_id: searchParams.get("project_id") ?? undefined,
source_type: (searchParams.get("source_type") as SourceType) ?? undefined,
status: (searchParams.get("status") as SourceStatus) ?? undefined,
purpose: searchParams.get("purpose") ?? undefined,
redistribution: (searchParams.get("redistribution") as SourceRights["redistribution"]) ?? undefined,
});
return NextResponse.json(sources);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}