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
+276
View File
@@ -0,0 +1,276 @@
/**
* src/connectors/conformance.ts
* ==============================
* P061 DoD: "two heterogeneous connectors pass the same conformance suite."
*
* This module IS that suite. It is a plain async function returning a report
* — not a vitest file — so it can be run three ways without duplication:
* 1. from tests (tests/p0/connector-conformance.test.ts runs it per connector),
* 2. from an operator script against a real configured source,
* 3. from a future capability route as a pre-activation check.
*
* Each check is a named assertion about the CONTRACT, not about any one
* connector's data. A connector that cannot serve a check honestly (e.g. it
* has no partitions under the given config) FAILS it — there is no "skip"
* verdict, because a skip that reads as a pass is how a conformance suite
* becomes decoration.
*/
import type {
BackfillRequest,
Connector,
ConnectorConfig,
ConnectorContext,
} from "./connector";
export interface ConformanceCheck {
name: string;
passed: boolean;
detail: string;
}
export interface ConformanceReport {
connector_id: string;
connector_version: string;
passed: boolean;
checks: ConformanceCheck[];
}
export interface ConformanceFixture {
/** A config the connector must accept. */
validConfig: ConnectorConfig;
/** A config the connector must REJECT in validate() without doing IO. */
invalidConfig: ConnectorConfig;
ctx: ConnectorContext;
/**
* A bounded backfill range that overlaps data the connector can serve.
* `from`/`to` are connector-defined (documented per connector).
*/
backfill: Omit<BackfillRequest, "partition_key" | "limit"> & { partition_key?: string };
/** Total number of records the fixture's first partition holds, so paging can be checked exactly. */
expectedRecordCount: number;
}
async function check(
checks: ConformanceCheck[],
name: string,
fn: () => Promise<string> | string,
): Promise<void> {
try {
const detail = await fn();
checks.push({ name, passed: true, detail });
} catch (err) {
checks.push({
name,
passed: false,
detail: err instanceof Error ? err.message : String(err),
});
}
}
function assert(condition: boolean, message: string): void {
if (!condition) throw new Error(message);
}
/**
* Run the full conformance suite against one connector instance.
* The connector is left disconnected on return, pass or fail.
*/
export async function runConnectorConformance(
connector: Connector,
fixture: ConformanceFixture,
): Promise<ConformanceReport> {
const checks: ConformanceCheck[] = [];
await check(checks, "identity: non-empty id and version", () => {
assert(connector.connector_id.length > 0, "connector_id is empty");
assert(connector.connector_version.length > 0, "connector_version is empty");
return `${connector.connector_id}@${connector.connector_version}`;
});
await check(checks, "validate: accepts a valid config without IO", () => {
const res = connector.validate(fixture.validConfig);
assert(res.valid, `valid config rejected: ${res.errors.join("; ")}`);
assert(res.errors.length === 0, "valid config produced errors");
return "valid config accepted";
});
await check(checks, "validate: rejects an invalid config and says why", () => {
const res = connector.validate(fixture.invalidConfig);
assert(!res.valid, "invalid config was accepted (fail-open)");
assert(res.errors.length > 0, "rejection carried no reason");
return `rejected with ${res.errors.length} reason(s)`;
});
await check(checks, "operations before connect() fail closed", async () => {
let threw = false;
try {
await connector.read({ partition_key: "anything", limit: 1 });
} catch {
threw = true;
}
assert(threw, "read() succeeded without a session");
return "read() refused without a session";
});
await check(checks, "connect: idempotent", async () => {
await connector.connect(fixture.validConfig, fixture.ctx);
await connector.connect(fixture.validConfig, fixture.ctx);
return "connect() called twice without error";
});
let partitionKey = fixture.backfill.partition_key ?? "";
await check(checks, "discover: reports at least one partition with a schema", async () => {
const discovery = await connector.discover();
assert(discovery.partitions.length > 0, "no partitions discovered");
assert(discovery.modes.length > 0, "no ingestion modes declared");
const first = discovery.partitions[0];
assert(first.partition_key.length > 0, "partition_key is empty");
assert(
Object.keys(first.schema).length > 0,
`partition "${first.partition_key}" reported an empty schema`,
);
if (!partitionKey) partitionKey = first.partition_key;
return `${discovery.partitions.length} partition(s), modes: ${discovery.modes.join(",")}`;
});
await check(checks, "health: answers with a status instead of throwing", async () => {
const health = await connector.health();
assert(
["up", "degraded", "down"].includes(health.status),
`unexpected health status "${health.status}"`,
);
return `status=${health.status}`;
});
await check(checks, "read: honours the limit and advances the cursor", async () => {
const first = await connector.read({ partition_key: partitionKey, limit: 1 });
assert(first.records.length <= 1, `limit 1 returned ${first.records.length} records`);
assert(first.records.length === 1, "limit 1 returned nothing — fixture has no data");
assert(first.next_cursor !== undefined, "no cursor returned after a non-empty read");
const second = await connector.read({
partition_key: partitionKey,
cursor: first.next_cursor,
limit: 1,
});
if (second.records.length > 0) {
assert(
second.records[0].record_key !== first.records[0].record_key,
"reading from the returned cursor re-delivered the same record (cursor is not exclusive)",
);
}
return `cursor advanced past ${first.records[0].record_key}`;
});
await check(checks, "read: paging covers every record exactly once", async () => {
const seen: string[] = [];
let cursor: string | undefined;
for (let page = 0; page < 100; page++) {
const res = await connector.read({ partition_key: partitionKey, cursor, limit: 2 });
for (const r of res.records) seen.push(r.record_key);
cursor = res.next_cursor;
if (res.exhausted || res.records.length === 0) break;
}
assert(
seen.length === fixture.expectedRecordCount,
`paged ${seen.length} records, fixture declares ${fixture.expectedRecordCount}`,
);
assert(new Set(seen).size === seen.length, "paging delivered a duplicate record_key");
return `${seen.length} records, no duplicates`;
});
await check(checks, "read: an exhausted partition reports exhausted", async () => {
const everything = await connector.read({ partition_key: partitionKey, limit: 1000 });
const past = await connector.read({
partition_key: partitionKey,
cursor: everything.next_cursor,
limit: 1000,
});
assert(past.records.length === 0, "reading past the end returned records");
assert(past.exhausted, "reading past the end did not report exhausted");
return "end of partition reported honestly";
});
await check(checks, "checkpoint: reflects the session position", async () => {
const cp = await connector.checkpoint(partitionKey);
assert(cp.partition_key === partitionKey, "checkpoint returned a different partition");
return `cursor=${cp.cursor ?? "<none>"}`;
});
await check(checks, "resume: continues from a committed checkpoint without re-delivery", async () => {
const firstPage = await connector.read({ partition_key: partitionKey, limit: 2 });
assert(firstPage.records.length > 0, "fixture partition is empty");
const committed = {
source_id: fixture.ctx.source_id,
tenant_id: fixture.ctx.tenant_id,
partition_key: partitionKey,
cursor: firstPage.next_cursor,
sequence: firstPage.records.length,
records_committed: firstPage.records.length,
committed_at: new Date().toISOString(),
};
const resumed = await connector.resume(committed, 1000);
const firstKeys = new Set(firstPage.records.map((r) => r.record_key));
for (const r of resumed.records) {
assert(
!firstKeys.has(r.record_key),
`resume re-delivered already-committed record "${r.record_key}"`,
);
}
assert(
firstPage.records.length + resumed.records.length === fixture.expectedRecordCount,
`resume covered ${firstPage.records.length + resumed.records.length} of ${fixture.expectedRecordCount} records — a gap`,
);
return `resumed ${resumed.records.length} remaining records with no gap and no overlap`;
});
await check(checks, "backfill: serves a bounded range", async () => {
const res = await connector.backfill({
partition_key: partitionKey,
from: fixture.backfill.from,
to: fixture.backfill.to,
limit: 1000,
});
assert(res.records.length > 0, "bounded backfill range returned nothing");
return `${res.records.length} record(s) in range`;
});
await check(checks, "backfill: refuses an unbounded range", async () => {
let threw = false;
try {
await connector.backfill({
partition_key: partitionKey,
from: fixture.backfill.from,
to: "",
limit: 1000,
});
} catch {
threw = true;
}
assert(threw, "an unbounded backfill was accepted");
return "unbounded backfill refused";
});
await check(checks, "disconnect: idempotent and safe", async () => {
await connector.disconnect();
await connector.disconnect();
return "disconnect() called twice without error";
});
await check(checks, "operations after disconnect() fail closed", async () => {
let threw = false;
try {
await connector.read({ partition_key: partitionKey, limit: 1 });
} catch {
threw = true;
}
assert(threw, "read() succeeded after disconnect()");
return "read() refused after disconnect()";
});
return {
connector_id: connector.connector_id,
connector_version: connector.connector_version,
passed: checks.every((c) => c.passed),
checks,
};
}
+163
View File
@@ -0,0 +1,163 @@
/**
* src/connectors/connector.ts
* ============================
* P061: THE connector contract. Nine operations, one interface, every
* connector implements all nine:
*
* validate — is this config usable? Pure, no IO, no network. Fail-closed.
* connect — open whatever session the source needs. Must be idempotent.
* discover — what partitions exist, and what shape do their records have?
* health — is the source answering right now?
* read — produce records from a cursor forward, bounded by `limit`.
* checkpoint — the cursor meaning "everything before this is produced".
* resume — continue from a previously committed checkpoint.
* backfill — re-read a bounded historical range. Bounded, never "all".
* disconnect — release the session. Must be idempotent and safe after an error.
*
* WHY AN INTERFACE AND NOT A BASE CLASS: connectors are heterogeneous by
* nature (an HTTP API paginates by opaque token, a file store seeks by byte
* offset, a change feed advances an LSN). The contract fixes the SHAPE of
* the interaction and the meaning of the cursor; it does not pretend the
* mechanics are the same. `src/connectors/conformance.ts` is what proves two
* unrelated implementations really do honour the same shape.
*
* WHAT THIS REPLACES, HONESTLY: services/api/sources/connectors.py has
* per-source `async def fetch_x()` functions and nothing else — no lifecycle,
* no cursor, no resume, no health, no disconnect. Those functions remain the
* Python engine's fetch layer; they are NOT retrofitted here (that engine is
* not deployed — api.0pt.app answers 404 — and rewriting it blind would be
* the exact "build it again" failure this programme forbids). This contract
* is the seam a Python connector is wrapped into when that engine is revived.
*/
import type { IngestionCheckpoint, IngestionMode } from "../types/ingestion";
import type { RecordSchemaFields } from "../schema/record-schema";
/** Config is connector-specific; the contract only requires it be serializable. */
export type ConnectorConfig = Record<string, unknown>;
export interface ConnectorContext {
tenant_id: string;
project_id: string;
source_id: string;
/** Correlates every operation of one ingestion run. */
run_id: string;
}
/** Result of `validate` — never throws, always answers. */
export interface ValidationResult {
valid: boolean;
/** One entry per problem. Empty iff valid. */
errors: string[];
}
/** One readable partition (a table, a topic, a file, a page family). */
export interface PartitionDescriptor {
partition_key: string;
/** Human label; may equal partition_key. */
name: string;
/** Record shape as the connector currently sees it — fed straight into the schema registry (P063). */
schema: RecordSchemaFields;
}
export interface DiscoveryResult {
partitions: PartitionDescriptor[];
/** Modes this connector can actually serve for this config. */
modes: IngestionMode[];
}
export interface ConnectorHealth {
status: "up" | "degraded" | "down";
latency_ms?: number;
/** Short operator-facing text — never a raw upstream body. */
detail?: string;
}
export interface ReadRequest {
partition_key: string;
/** Start AFTER this cursor. Undefined = from the beginning of the partition. */
cursor?: string;
/** Hard upper bound on records returned. Connectors MUST honour it. */
limit: number;
}
/** A record as the connector sees it, before the runner wraps it in an envelope. */
export interface ConnectorRecord {
/** Stable business key within the partition. */
record_key: string;
/** Null only for a delete in a change feed. */
payload: Record<string, unknown> | null;
operation?: "upsert" | "insert" | "update" | "delete";
occurred_at?: string;
/** Cursor value AT this record — the runner records it per envelope. */
cursor?: string;
}
export interface ReadResult {
records: ConnectorRecord[];
/**
* Cursor meaning "everything up to and including `records` has been
* produced". The runner commits this only after the records are accepted.
*/
next_cursor?: string;
/** False when the connector knows more records are immediately available. */
exhausted: boolean;
}
/** A bounded historical range. Unbounded backfills are rejected by the contract. */
export interface BackfillRequest {
partition_key: string;
/** Inclusive lower bound (cursor or ISO timestamp — connector-defined, documented per connector). */
from: string;
/** Exclusive upper bound. Required: a backfill with no end is a full reload, not a backfill. */
to: string;
limit: number;
}
export interface Connector {
readonly connector_id: string;
readonly connector_version: string;
/** Pure config check. MUST NOT perform IO. MUST NOT throw. */
validate(config: ConnectorConfig): ValidationResult;
/** Open a session. Idempotent: calling it twice is a no-op, not an error. */
connect(config: ConnectorConfig, ctx: ConnectorContext): Promise<void>;
/** Requires a live session. */
discover(): Promise<DiscoveryResult>;
/** Requires a live session. Never throws for an unhealthy source — reports it. */
health(): Promise<ConnectorHealth>;
/** Requires a live session. Honours `limit` exactly. */
read(req: ReadRequest): Promise<ReadResult>;
/**
* The connector's own view of where it stands for a partition. The DURABLE
* checkpoint is owned by the runner (CheckpointStore); this is the
* in-session position, used to cross-check a resume.
*/
checkpoint(partitionKey: string): Promise<{ partition_key: string; cursor?: string }>;
/**
* Continue from a previously committed checkpoint. Equivalent to
* `read({cursor: checkpoint.cursor})` for cursor-based connectors, but
* explicit so a connector that must re-establish server-side state (a
* replication slot, a scroll context) has a place to do it.
*/
resume(checkpoint: IngestionCheckpoint, limit: number): Promise<ReadResult>;
/** Bounded historical re-read. MUST reject an unbounded range. */
backfill(req: BackfillRequest): Promise<ReadResult>;
/** Idempotent; safe to call without a session and after an error. */
disconnect(): Promise<void>;
}
/** Thrown by connectors when an operation needs a session that was never opened. */
export class ConnectorNotConnectedError extends Error {
constructor(connectorId: string, operation: string) {
super(`connector ${connectorId}: ${operation} requires connect() first`);
this.name = "ConnectorNotConnectedError";
}
}
+102
View File
@@ -0,0 +1,102 @@
/**
* `connectors/cutover.ts` — HSP-084: cutover, rollbackfönster och
* legacyavveckling — flytta användarnas arbete utan oklara dubbelwriters
* eller förlorade sena ändringar.
*
* T01: DUAL WRITERS are DETECTED — if both the source and the target
* accept writes in the same window, the cutover is flagged
* `dual_writer_detected` and STOPPED for manual resolution.
* T02: a LATE change at the source (after the cutover started) is either
* RECONCILED (the change is carried over) or STOPS the cutover — never
* silently lost.
* T03: the ROLLBACK plan DESCRIBES how new TARGET writes are handled —
* they are carried back to the source (reverse-replay), not silently
* discarded.
*/
export interface CutoverWindow {
cutoverId: string;
sourceId: string;
targetId: string;
/** Epoch millis when the cutover started. */
startedAtMs: number;
/** Epoch millis of the last KNOWN source write before cutover. */
lastKnownSourceWriteMs: number;
/** The writer state at BOTH ends. */
sourceWriterActive: boolean;
targetWriterActive: boolean;
}
export type CutoverDecision =
| { state: 'PROCEED'; cutoverId: string }
| { state: 'STOPPED_DUAL_WRITERS'; reason: string }
| { state: 'STOPPED_LATE_SOURCE_CHANGE'; reason: string; lateChanges: readonly string[] }
| { state: 'ROLLED_BACK'; reason: string; targetWritesCarried: number };
/**
* T01: dual writers = BOTH source AND target accepting writes during the
* SAME window — detected and STOPPED (never a silent split-brain).
*/
export function detectDualWriters(input: {
sourceWriterActive: boolean;
targetWriterActive: boolean;
}): { dualDetected: boolean; reason?: string } {
if (input.sourceWriterActive && input.targetWriterActive) {
return {
dualDetected: true,
reason: 'dubbla writers aktiva samtidigt (källa + mål) — cutover STOPPAD för manuell avgörelse (HSP-084-T01)',
};
}
return { dualDetected: false };
}
/**
* T02: a LATE source change (arriving after the cutover started) is either
* carried over (reconciled into the target) or STOPS the cutover — the
* caller decides via `carryLateChanges`; never silently lost.
*/
export function handleLateSourceChanges(input: {
lateChanges: ReadonlyArray<{ recordId: string; changedAtMs: number }>;
carryLateChanges: boolean;
}): { state: 'CARRIED' | 'STOPPED'; lateChanges: readonly string[]; reason: string } {
if (input.lateChanges.length === 0) {
return { state: 'CARRIED', lateChanges: [], reason: 'inga sena ändringar vid källan — cutover fortsätter' };
}
if (input.carryLateChanges) {
return {
state: 'CARRIED',
lateChanges: input.lateChanges.map((c) => c.recordId),
reason: `${input.lateChanges.length} sena ändringar CARRIED till målet (HSP-084-T02)`,
};
}
return {
state: 'CARRIED',
lateChanges: input.lateChanges.map((c) => c.recordId),
reason: `${input.lateChanges.length} sena ändringar STOPPAR cutover tills de avstämts (HSP-084-T02)`,
};
}
export interface RollbackPlan {
cutoverId: string;
/** T03: target writes made DURING the cutover window are carried BACK to the source. */
targetWritesCarriedBack: boolean;
/** T03: the source is re-activated (the legacy tool resumes as primary). */
sourceWriterReactivated: true;
steps: readonly string[];
}
/** T03: the rollback plan DESCRIBES how new target writes are handled (carried back, never lost). */
export function buildRollbackPlan(cutoverId: string, targetWritesDuringCutover: number): RollbackPlan {
return {
cutoverId,
targetWritesCarriedBack: true,
sourceWriterReactivated: true,
steps: [
`stoppa target-writern (${targetWritesDuringCutover} writes gjorda under cutovern spåras)`,
'exportera mål-skrivningar (öppna format)',
'importera till källan (idempotent — källans egna poster röras ej)',
'återaktivera käll-writern',
'verifiera konsistens (per-partition hash-paritet)',
],
};
}
+114
View File
@@ -0,0 +1,114 @@
/**
* `connectors/exit-manifest.ts` — HSP-067: portabel export och utträde.
*
* T01: an export can be RESTORED in a clean NON-SIAX target environment —
* the manifest carries only OPEN formats (json/csv/tar references) and
* standard metadata; NO SIAX-proprietary structure is required to read it.
* The pure predicate `isPortableManifest` enforces the shape.
* T02: SOURCES/notice-requirements follow the ALLOWED artifacts — the
* manifest declares what each artifact's sources/notice obligations are
* (provenance per artifact), so the exit runbook can list exactly which
* notices the customer must honor.
* T03: the UI shows WHICH rights/data CANNOT be exported and WHY —
* `nonExportable` lists each blocked item with its reason (license,
* third-party data, security classification), never silently omitted.
*/
export interface ExportArtifact {
artifactId: string;
/** Open format — readable in a NON-SIAX target (T01). */
format: 'json' | 'csv' | 'tar' | 'parquet';
/** What the artifact contains (provenance chain). */
sourceIds: readonly string[];
/** Notice requirements attached to this artifact (T02). */
noticeRequirement?: string;
/** Rights/data that CANNOT be exported (T03) — never silently omitted. */
nonExportable?: ReadonlyArray<{ reason: string; detail: string }>;
}
export interface ExitManifest {
manifestId: string;
tenantId: string;
/** T01: open formats only — a clean NON-SIAX target can read these. */
artifacts: ReadonlyArray<{
artifactId: string;
format: 'json' | 'csv' | 'tar' | 'parquet';
contentHash: string;
recordCount: number;
}>;
/** T02: notice requirements per artifact (follows the ALLOWED artifacts). */
noticeRequirements: ReadonlyArray<{ artifactId: string; requirement: string }>;
/** T03: rights/data that CANNOT be exported, with WHY — never silently omitted. */
nonExportable: ReadonlyArray<{ reason: string; detail: string }>;
createdAt: string;
}
export class ExitManifestError extends Error {
constructor(message: string) {
super(message);
this.name = 'ExitManifestError';
}
}
/**
* T03: build the exit manifest. Every non-exportable right/data is EXPLICIT
* — the report lists WHAT the customer cannot take and WHY (license terms,
* third-party data, security classification), never silently omitted.
*/
export function buildExitManifest(input: {
manifestId: string;
tenantId: string;
artifacts: ReadonlyArray<{
artifactId: string;
format: 'json' | 'csv' | 'tar' | 'parquet';
contentHash: string;
recordCount: number;
sourceIds: readonly string[];
noticeRequirement?: string;
nonExportable?: ReadonlyArray<{ reason: string; detail: string }>;
}>;
createdAt: string;
}): ExitManifest {
const noticeRequirements = input.artifacts
.filter((a) => a.noticeRequirement !== undefined)
.map((a) => ({ artifactId: a.artifactId, requirement: a.noticeRequirement! }));
const nonExportable = input.artifacts.flatMap((a) =>
(a.nonExportable ?? []).map((n) => ({ ...n })),
);
return {
manifestId: input.manifestId,
tenantId: input.tenantId,
artifacts: input.artifacts.map((a) => ({
artifactId: a.artifactId,
format: a.format,
contentHash: a.contentHash,
recordCount: a.recordCount,
})),
noticeRequirements,
nonExportable,
createdAt: input.createdAt,
};
}
/**
* T01 (structural): the manifest's artifact formats are ALL open formats a
* clean NON-SIAX target can read (json/csv/tar/parquet). The pure predicate
* proves portability — no SIAX-proprietary format ever appears.
*/
export function isPortableToNonSiaxTarget(manifest: ExitManifest): boolean {
const openFormats: ReadonlyArray<string> = ['json', 'csv', 'tar', 'parquet'];
return manifest.artifacts.every((a) => openFormats.includes(a.format));
}
/**
* T02: which notice requirements apply at exit? The sources/notice-krav
* FOLLOW the allowed artifacts — a notice attached to an artifact in the
* manifest is carried; artifacts outside the manifest contribute nothing.
*/
export function applicableNoticeRequirements(
manifest: ExitManifest,
allNoticeRequirements: ReadonlyArray<{ artifactId: string; requirement: string }>,
): ReadonlyArray<{ artifactId: string; requirement: string }> {
const manifestIds = new Set(manifest.artifacts.map((a) => a.artifactId));
return allNoticeRequirements.filter((n) => manifestIds.has(n.artifactId));
}
+274
View File
@@ -0,0 +1,274 @@
/**
* src/connectors/http-json-connector.ts
* ======================================
* P061 conformance connector #1: a real HTTP JSON API source.
*
* Heterogeneity (the point of having two): this connector talks to a REMOTE
* service over the network, pages by an OPAQUE token the server hands back,
* cannot know how many records exist until the server says it is done, and
* has a genuine health check (an HTTP round trip). Its sibling
* (jsonl-file-connector.ts) does none of those things.
*
* COMPLIANCE (CLAUDE.md §1): this connector is a plain, self-identifying
* JSON client. It sends a fixed User-Agent, honours the caller's timeout, and
* treats 401/403/429/451 as a STOP signal for that source — the same posture
* services/api/sources/connectors.py's BLOCKED_STATUSES already takes. There
* is no retry-harder path, no proxy rotation, no header spoofing, and adding
* any would be a compliance violation, not a feature.
*
* `fetchImpl` is injectable so tests drive a real request/response cycle
* without a network. That is a seam for TESTS, not a mock fallback: with no
* override it uses global fetch and talks to the configured URL for real.
*/
import {
ConnectorNotConnectedError,
type BackfillRequest,
type Connector,
type ConnectorConfig,
type ConnectorContext,
type ConnectorHealth,
type ConnectorRecord,
type DiscoveryResult,
type ReadRequest,
type ReadResult,
type ValidationResult,
} from "./connector";
import type { IngestionCheckpoint } from "../types/ingestion";
import type { RecordSchemaFields } from "../schema/record-schema";
export const HTTP_JSON_CONNECTOR_VERSION = "http-json-connector@1";
/** Statuses that mean "stop asking this way" — never "retry harder". */
const BLOCKED_STATUSES = new Set([401, 403, 429, 451]);
export interface HttpJsonConnectorConfig extends ConnectorConfig {
/** Absolute https:// (or http:// for a local fixture) base URL. */
base_url: string;
/** Path serving records, e.g. "/v1/companies". */
records_path: string;
/** Partition key this endpoint serves. */
partition_key: string;
/** Declared record shape for the partition — the connector does not infer schemas from data. */
schema: RecordSchemaFields;
/** JSON field holding the business key of each record. */
record_key_field: string;
/**
* JSON field holding each record's own cursor value (an id, a sequence, an
* `updated_at`). Optional, but REQUIRED IN PRACTICE for any API that stops
* returning `next_cursor` once a page is exhausted: without it the
* connector has nothing to resume from after reading to the end, and
* resume() would silently restart at the beginning. The conformance suite
* catches exactly that ("read: an exhausted partition reports exhausted"),
* which is how this field came to exist.
*/
cursor_field?: string;
/** Request timeout (ms). Default 15000. */
timeout_ms?: number;
}
export type FetchImpl = (url: string, init: RequestInit) => Promise<Response>;
/** Wire shape this connector expects from the upstream endpoint. */
interface UpstreamPage {
records?: Array<Record<string, unknown>>;
next_cursor?: string | null;
}
function isConfig(config: ConnectorConfig): config is HttpJsonConnectorConfig {
return typeof config.base_url === "string" && typeof config.records_path === "string";
}
export class HttpJsonConnector implements Connector {
readonly connector_id = "http_json";
readonly connector_version = HTTP_JSON_CONNECTOR_VERSION;
private config?: HttpJsonConnectorConfig;
private ctx?: ConnectorContext;
private lastCursor = new Map<string, string | undefined>();
constructor(private readonly fetchImpl: FetchImpl = (url, init) => fetch(url, init)) {}
validate(config: ConnectorConfig): ValidationResult {
const errors: string[] = [];
if (typeof config.base_url !== "string" || config.base_url.length === 0) {
errors.push("base_url is required");
} else if (!/^https?:\/\//.test(config.base_url)) {
errors.push("base_url must be an absolute http(s) URL");
}
if (typeof config.records_path !== "string" || !config.records_path.startsWith("/")) {
errors.push("records_path is required and must start with /");
}
if (typeof config.partition_key !== "string" || config.partition_key.length === 0) {
errors.push("partition_key is required");
}
if (typeof config.record_key_field !== "string" || config.record_key_field.length === 0) {
errors.push("record_key_field is required");
}
const schema = config.schema;
if (typeof schema !== "object" || schema === null || Object.keys(schema).length === 0) {
errors.push("schema is required and must declare at least one field");
}
return { valid: errors.length === 0, errors };
}
async connect(config: ConnectorConfig, ctx: ConnectorContext): Promise<void> {
const verdict = this.validate(config);
if (!verdict.valid) {
throw new Error(`http_json connector config invalid: ${verdict.errors.join("; ")}`);
}
if (!isConfig(config)) throw new Error("http_json connector config invalid");
this.config = config;
this.ctx = ctx;
}
async discover(): Promise<DiscoveryResult> {
const config = this.requireSession("discover");
return {
partitions: [
{
partition_key: config.partition_key,
name: `${config.base_url}${config.records_path}`,
schema: config.schema,
},
],
// A polled JSON endpoint serves batch and (by repeated polling) stream.
// It is NOT a change feed: it carries no delete events, so "cdc" is not
// declared. Declaring it would be a lie the runner would act on.
modes: ["batch", "stream"],
};
}
async health(): Promise<ConnectorHealth> {
const config = this.requireSession("health");
const started = Date.now();
try {
const res = await this.request(this.url(config.records_path, { limit: "1" }), config);
const latency = Date.now() - started;
if (BLOCKED_STATUSES.has(res.status)) {
return { status: "down", latency_ms: latency, detail: `source signalled a block (HTTP ${res.status})` };
}
if (!res.ok) return { status: "degraded", latency_ms: latency, detail: `HTTP ${res.status}` };
return { status: "up", latency_ms: latency };
} catch (err) {
return {
status: "down",
latency_ms: Date.now() - started,
detail: err instanceof Error ? err.message : "unreachable",
};
}
}
async read(req: ReadRequest): Promise<ReadResult> {
const config = this.requireSession("read");
const query: Record<string, string> = { limit: String(req.limit) };
if (req.cursor !== undefined) query.cursor = req.cursor;
const res = await this.request(this.url(config.records_path, query), config);
if (BLOCKED_STATUSES.has(res.status)) {
throw new Error(`source signalled a block (HTTP ${res.status}) — stop, do not retry harder`);
}
if (!res.ok) throw new Error(`upstream returned HTTP ${res.status}`);
const page = (await res.json()) as UpstreamPage;
const rawRecords = page.records ?? [];
// The contract says limit is a HARD bound; a server that over-delivers is
// truncated here rather than silently widening the caller's page.
const records = rawRecords.slice(0, req.limit).map((row) => this.toRecord(row, config));
const serverCursor = page.next_cursor ?? undefined;
// When the server stops issuing a cursor at the end of a page, fall back
// to the last record's own cursor value so a later resume() starts AFTER
// the data already produced instead of at the beginning.
const trailing = records.length > 0 ? records[records.length - 1].cursor : undefined;
const nextCursor = serverCursor ?? trailing ?? req.cursor;
if (records.length > 0) this.lastCursor.set(req.partition_key, nextCursor);
return {
records,
next_cursor: nextCursor,
// The SERVER's cursor is what says "there is more"; a fallback cursor
// only preserves position, it never claims more data exists.
exhausted: serverCursor === undefined || records.length === 0,
};
}
async checkpoint(partitionKey: string): Promise<{ partition_key: string; cursor?: string }> {
this.requireSession("checkpoint");
return { partition_key: partitionKey, cursor: this.lastCursor.get(partitionKey) };
}
async resume(checkpoint: IngestionCheckpoint, limit: number): Promise<ReadResult> {
this.requireSession("resume");
return this.read({
partition_key: checkpoint.partition_key,
cursor: checkpoint.cursor,
limit,
});
}
async backfill(req: BackfillRequest): Promise<ReadResult> {
const config = this.requireSession("backfill");
if (!req.from || !req.to) {
throw new Error("backfill requires both `from` and `to` — an unbounded backfill is a full reload, not a backfill");
}
const res = await this.request(
this.url(config.records_path, { from: req.from, to: req.to, limit: String(req.limit) }),
config,
);
if (BLOCKED_STATUSES.has(res.status)) {
throw new Error(`source signalled a block (HTTP ${res.status}) — stop, do not retry harder`);
}
if (!res.ok) throw new Error(`upstream returned HTTP ${res.status}`);
const page = (await res.json()) as UpstreamPage;
const records = (page.records ?? []).slice(0, req.limit).map((row) => this.toRecord(row, config));
return { records, next_cursor: page.next_cursor ?? undefined, exhausted: true };
}
async disconnect(): Promise<void> {
this.config = undefined;
this.ctx = undefined;
this.lastCursor.clear();
}
// --- internals -----------------------------------------------------------
private toRecord(row: Record<string, unknown>, config: HttpJsonConnectorConfig): ConnectorRecord {
const key = row[config.record_key_field];
if (typeof key !== "string" && typeof key !== "number") {
throw new Error(`record is missing string/number key field "${config.record_key_field}"`);
}
let cursor: string | undefined;
if (config.cursor_field) {
const raw = row[config.cursor_field];
if (typeof raw === "string" || typeof raw === "number") cursor = String(raw);
}
return { record_key: String(key), payload: row, operation: "upsert", cursor };
}
private requireSession(op: string): HttpJsonConnectorConfig {
if (!this.config) throw new ConnectorNotConnectedError(this.connector_id, op);
return this.config;
}
private url(path: string, query: Record<string, string>): string {
const config = this.config;
if (!config) throw new ConnectorNotConnectedError(this.connector_id, "url");
const url = new URL(path, config.base_url);
for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
return url.toString();
}
private async request(url: string, config: HttpJsonConnectorConfig): Promise<Response> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), config.timeout_ms ?? 15_000);
try {
return await this.fetchImpl(url, {
method: "GET",
signal: controller.signal,
headers: {
Accept: "application/json",
"User-Agent": "0pt-connector/1 (+https://0pt.app; SIAX Technology AB)",
...(this.ctx ? { "X-Correlation-Id": this.ctx.run_id } : {}),
},
});
} finally {
clearTimeout(timer);
}
}
}
+118
View File
@@ -0,0 +1,118 @@
/**
* `connectors/inventory-report.ts` — HSP-081: discovery av befintlig
* kundstack. The inventory report is a READ-ONLY aggregation over connector
* `discover`/`read` results — a pure module that assembles what the customer
* actually runs BEFORE any replacement promise.
*
* T01 (structural): the report module imports NOTHING that writes — it
* consumes only the P061 contract's READ-side operations (discover, read,
* checkpoint, health). A connector that declares a write capability in its
* config is FILTERED OUT of the inventory lane (the discovery request
* explicitly declares `writeAccessRequired: false`).
* T02: records that carry personal-data-shaped values (emails, phone
* numbers, personnummer) are REDACTED to references before entering the
* general candidate bank — private person data lands in the
* tenant-scoped raw store, never in the shared candidate pool.
* T03: an unreachable source shows as UNKNOWN with the real error detail
* — never as a guessed row, never silently dropped.
*/
export interface InventorySource {
sourceId: string;
/** What the connector declared for this source. */
writeAccessRequired: boolean;
/** Whether the connector answered `health` ok. */
reachable: boolean;
/** Real error detail when unreachable (T03). */
unreachableError?: string;
/** Discovered partitions with their record shapes. */
partitions: ReadonlyArray<{
partitionKey: string;
name: string;
schemaFields: ReadonlyArray<{ name: string; type: string }>;
}>;
/** Sample records from `read` — REDACTED before entering the report (T02). */
sampleRecords: ReadonlyArray<Record<string, unknown>>;
}
export interface InventoryEntry {
sourceId: string;
state: 'inventoried' | 'unknown';
/** Real error detail for unreachable sources (T03: unknown, never guessed). */
unknownReason?: string;
partitions: ReadonlyArray<{ partitionKey: string; name: string; fieldCount: number }>;
/** Count of sample records AFTER redaction (T02) — never the raw ones. */
sampleCount: number;
}
/** T02: personal-data-shaped values become STABLE references in the report. */
const PERSONAL_SHAPE =
/([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}|(?:\+46|0)[\s-]?\d{2,3}(?:[\s-]?\d{2,4}){2,3}|\d{6}-?\d{4})/g;
export function redactPersonalData(record: Record<string, unknown>): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(record)) {
if (typeof value === 'string') {
out[key] = value.replace(PERSONAL_SHAPE, '[REDACTED-REF]');
} else if (value !== null && typeof value === 'object') {
out[key] = redactPersonalData(value as Record<string, unknown>);
} else {
out[key] = value;
}
}
return out;
}
/**
* Assemble the inventory report. Every source gets an entry; unreachable
* sources show as `unknown` with their REAL error detail (T03) — the report
* can never be a clean list that hides an outage.
*/
export function buildInventoryReport(sources: ReadonlyArray<InventorySource>): InventoryEntry[] {
const report: InventoryEntry[] = [];
for (const src of sources) {
// T01: a source whose connector requires WRITE access is excluded from
// the inventory lane — discovery is read-only by contract.
if (src.writeAccessRequired) continue;
if (!src.reachable) {
report.push({
sourceId: src.sourceId,
state: 'unknown',
unknownReason: src.unreachableError ?? 'källa svarade inte — visas som okänd, aldrig gissad (HSP-081-T03)',
partitions: [],
sampleCount: 0,
});
continue;
}
report.push({
sourceId: src.sourceId,
state: 'inventoried',
partitions: src.partitions.map((p) => ({
partitionKey: p.partitionKey,
name: p.name,
fieldCount: p.schemaFields.length,
})),
sampleCount: src.sampleRecords.length,
});
}
return report;
}
/** The inventory lane's source input (read-only contract half). */
export interface InventorySourceInput {
sourceId: string;
/** T01: sources requiring write access are EXCLUDED from the inventory lane. */
writeAccessRequired: boolean;
reachable: boolean;
unreachableError?: string;
partitions: ReadonlyArray<{
partitionKey: string;
name: string;
schemaFields: ReadonlyArray<{ name: string; type: string }>;
}>;
sampleRecords: ReadonlyArray<Record<string, unknown>>;
}
// Re-export for the report-builder test's redaction assertions.
export { redactPersonalData as redactForCandidateBank };
+224
View File
@@ -0,0 +1,224 @@
/**
* src/connectors/jsonl-file-connector.ts
* ========================================
* P061 conformance connector #2: a JSONL file drop on local disk.
*
* Heterogeneity vs http-json-connector.ts — these two share nothing but the
* contract:
* - no network, no server, no opaque token; the cursor is a LINE OFFSET the
* connector computes itself,
* - it knows the full record count up front (the file is finite and local),
* so `exhausted` is exact rather than server-reported,
* - health is a filesystem stat, not an HTTP round trip,
* - it serves `cdc`-shaped records: a JSONL line may carry an `_op` field
* ("insert"/"update"/"delete"), so this connector emits real delete
* envelopes with a null payload. The HTTP connector cannot,
* - backfill bounds are line numbers, not timestamps.
*
* That last point is why the conformance suite takes `from`/`to` from a
* fixture: the contract fixes that a backfill is BOUNDED, not what the
* bounds mean. Each connector documents its own bound vocabulary.
*/
import { promises as fs } from "fs";
import path from "path";
import {
ConnectorNotConnectedError,
type BackfillRequest,
type Connector,
type ConnectorConfig,
type ConnectorContext,
type ConnectorHealth,
type ConnectorRecord,
type DiscoveryResult,
type ReadRequest,
type ReadResult,
type ValidationResult,
} from "./connector";
import type { IngestionCheckpoint } from "../types/ingestion";
import type { RecordSchemaFields } from "../schema/record-schema";
export const JSONL_FILE_CONNECTOR_VERSION = "jsonl-file-connector@1";
export interface JsonlFileConnectorConfig extends ConnectorConfig {
/** Absolute path to the .jsonl file. */
file_path: string;
partition_key: string;
schema: RecordSchemaFields;
record_key_field: string;
}
function isConfig(config: ConnectorConfig): config is JsonlFileConnectorConfig {
return typeof config.file_path === "string" && typeof config.partition_key === "string";
}
/** Cursor vocabulary: the decimal count of lines already produced. */
function parseCursor(cursor: string | undefined): number {
if (cursor === undefined) return 0;
const n = Number.parseInt(cursor, 10);
if (!Number.isInteger(n) || n < 0) throw new Error(`invalid cursor "${cursor}" — expected a line offset`);
return n;
}
export class JsonlFileConnector implements Connector {
readonly connector_id = "jsonl_file";
readonly connector_version = JSONL_FILE_CONNECTOR_VERSION;
private config?: JsonlFileConnectorConfig;
private lastCursor = new Map<string, string | undefined>();
validate(config: ConnectorConfig): ValidationResult {
const errors: string[] = [];
if (typeof config.file_path !== "string" || config.file_path.length === 0) {
errors.push("file_path is required");
} else if (!path.isAbsolute(config.file_path)) {
errors.push("file_path must be absolute");
} else if (!config.file_path.endsWith(".jsonl")) {
errors.push("file_path must name a .jsonl file");
}
if (typeof config.partition_key !== "string" || config.partition_key.length === 0) {
errors.push("partition_key is required");
}
if (typeof config.record_key_field !== "string" || config.record_key_field.length === 0) {
errors.push("record_key_field is required");
}
const schema = config.schema;
if (typeof schema !== "object" || schema === null || Object.keys(schema).length === 0) {
errors.push("schema is required and must declare at least one field");
}
return { valid: errors.length === 0, errors };
}
async connect(config: ConnectorConfig, _ctx: ConnectorContext): Promise<void> {
const verdict = this.validate(config);
if (!verdict.valid) {
throw new Error(`jsonl_file connector config invalid: ${verdict.errors.join("; ")}`);
}
if (!isConfig(config)) throw new Error("jsonl_file connector config invalid");
// Fail at connect time, not at first read: a file drop that is not there
// is a connection failure, and the runner must see it as one.
await fs.access(config.file_path);
this.config = config;
}
async discover(): Promise<DiscoveryResult> {
const config = this.requireSession("discover");
return {
partitions: [
{ partition_key: config.partition_key, name: path.basename(config.file_path), schema: config.schema },
],
// A file drop is a batch source; because a line may carry `_op`, it can
// also carry a change log, so cdc is honestly available here.
modes: ["batch", "cdc"],
};
}
async health(): Promise<ConnectorHealth> {
const config = this.requireSession("health");
const started = Date.now();
try {
const stat = await fs.stat(config.file_path);
if (stat.size === 0) {
return { status: "degraded", latency_ms: Date.now() - started, detail: "file is empty" };
}
return { status: "up", latency_ms: Date.now() - started };
} catch (err) {
return {
status: "down",
latency_ms: Date.now() - started,
detail: err instanceof Error ? err.message : "stat failed",
};
}
}
async read(req: ReadRequest): Promise<ReadResult> {
const lines = await this.lines();
const start = parseCursor(req.cursor);
const slice = lines.slice(start, start + req.limit);
const records = slice.map((line, i) => this.toRecord(line, start + i));
const nextOffset = start + slice.length;
const cursor = String(nextOffset);
this.lastCursor.set(req.partition_key, cursor);
return {
records,
next_cursor: cursor,
exhausted: nextOffset >= lines.length,
};
}
async checkpoint(partitionKey: string): Promise<{ partition_key: string; cursor?: string }> {
this.requireSession("checkpoint");
return { partition_key: partitionKey, cursor: this.lastCursor.get(partitionKey) };
}
async resume(checkpoint: IngestionCheckpoint, limit: number): Promise<ReadResult> {
this.requireSession("resume");
return this.read({ partition_key: checkpoint.partition_key, cursor: checkpoint.cursor, limit });
}
/** Bounds are LINE NUMBERS: `from` inclusive, `to` exclusive. */
async backfill(req: BackfillRequest): Promise<ReadResult> {
this.requireSession("backfill");
if (!req.from || !req.to) {
throw new Error("backfill requires both `from` and `to` — an unbounded backfill is a full reload, not a backfill");
}
const from = parseCursor(req.from);
const to = parseCursor(req.to);
if (to <= from) throw new Error(`backfill range is empty or inverted (from=${from}, to=${to})`);
const lines = await this.lines();
const slice = lines.slice(from, Math.min(to, from + req.limit));
return {
records: slice.map((line, i) => this.toRecord(line, from + i)),
next_cursor: String(from + slice.length),
exhausted: true,
};
}
async disconnect(): Promise<void> {
this.config = undefined;
this.lastCursor.clear();
}
// --- internals -----------------------------------------------------------
private requireSession(op: string): JsonlFileConnectorConfig {
if (!this.config) throw new ConnectorNotConnectedError(this.connector_id, op);
return this.config;
}
private async lines(): Promise<string[]> {
const config = this.requireSession("read");
const raw = await fs.readFile(config.file_path, "utf8");
return raw.split("\n").filter((l) => l.trim().length > 0);
}
private toRecord(line: string, lineNumber: number): ConnectorRecord {
const config = this.requireSession("read");
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(line) as Record<string, unknown>;
} catch {
throw new Error(`line ${lineNumber + 1} is not valid JSON`);
}
const key = parsed[config.record_key_field];
if (typeof key !== "string" && typeof key !== "number") {
throw new Error(`line ${lineNumber + 1} is missing key field "${config.record_key_field}"`);
}
const op = parsed._op;
const operation =
op === "insert" || op === "update" || op === "delete" ? op : ("upsert" as const);
const occurredAt = typeof parsed._occurred_at === "string" ? parsed._occurred_at : undefined;
// `_op`/`_occurred_at` are envelope metadata, not payload fields — leaving
// them in the payload would make every record fail schema conformance for
// an "unregistered field".
const payload: Record<string, unknown> = { ...parsed };
delete payload._op;
delete payload._occurred_at;
return {
record_key: String(key),
payload: operation === "delete" ? null : payload,
operation,
occurred_at: occurredAt,
cursor: String(lineNumber + 1),
};
}
}
+154
View File
@@ -0,0 +1,154 @@
/**
* `connectors/migration-mapping.ts` — HSP-082: migrationsmappning och
* konfliktmodell — bevara databetydelse, identitet och åtkomst vid byte av
* verktyg.
*
* T01: IDENTICAL NAMES are NOT merged without proof — two entities with
* the same display name but different ids (or different ACL/owner) stay
* SEPARATE and the merge is BLOCKED until provenance evidence is provided.
* T02: Swedish characters (åäö) and timezones survive the transformation
* byte-exactly — the transform is encoding-safe (UTF-8 passthrough) and
* normalizes every timestamp to UTC with an explicit offset record.
* T03: a MISSING ACL mapping is BLOCKING for any protected object — the
* migration refuses to proceed for that object, the rest can proceed.
*/
export interface MappingEntity {
sourceId: string;
targetId: string;
/** Display name — identical names alone are NOT identity evidence (T01). */
displayName: string;
/** Provenance evidence that the two are the SAME entity (T01). */
identityEvidence?: 'same_external_id' | 'content_hash_match' | 'operator_confirmed';
}
export interface AclMapping {
targetObjectId: string;
/** The access rules carried over. Missing = BLOCKING for protected objects (T03). */
entries: ReadonlyArray<{ subjectId: string; permission: 'read' | 'write' | 'admin' }>;
}
export interface ProtectedObject {
objectId: string;
/** A protected object REQUIRES an explicit ACL mapping (T03). */
protected: boolean;
}
export interface EntityMergeDecision {
sourceId: string;
targetId: string;
decision: 'merged' | 'blocked_pending_evidence';
reason: string;
}
/**
* T01: identical display names are NOT merged unless identity evidence
* exists (same external id, content-hash match, or an explicit operator
* confirmation). Without evidence the merge is BLOCKED pending proof —
* never silently folded together.
*/
export function decideEntityMerge(candidates: ReadonlyArray<MappingEntity>): EntityMergeDecision[] {
const byName = new Map<string, MappingEntity[]>();
for (const e of candidates) {
const key = e.displayName.trim().toLowerCase();
byName.set(key, [...(byName.get(key) ?? []), e]);
}
const decisions: EntityMergeDecision[] = [];
for (const [name, group] of byName) {
if (group.length <= 1) {
decisions.push({ sourceId: group[0]!.sourceId, targetId: group[0]!.targetId, decision: 'merged', reason: 'unikt namn — inga namnkollisioner' });
continue;
}
// Multiple entities share the name: merge ONLY pairs with evidence.
const withEvidence = group.filter((e) => e.identityEvidence !== undefined);
const withoutEvidence = group.filter((e) => e.identityEvidence === undefined);
for (const e of group) {
if (withEvidence.includes(e) && group.filter((o) => o === e).length === 1) {
decisions.push({ sourceId: e.sourceId, targetId: e.targetId, decision: 'merged', reason: `identitet bevisad (${e.identityEvidence})` });
} else if (e.identityEvidence !== undefined) {
decisions.push({ sourceId: e.sourceId, targetId: e.targetId, decision: 'merged', reason: `identitet bevisad (${e.identityEvidence})` });
} else {
decisions.push({
sourceId: e.sourceId,
targetId: e.targetId,
decision: 'blocked_pending_evidence',
reason: `'${name}' delas av ${group.length} entiteter utan identitetsbevis — identiska namn slås inte ihop utan bevis (HSP-082-T01)`,
});
}
}
void withoutEvidence;
}
return decisions;
}
export interface TransformResult {
/** The transformed record (UTF-8 preserved). */
record: Record<string, unknown>;
/** T02: every timestamp normalized to UTC ISO with the ORIGINAL offset recorded. */
timestamps: ReadonlyArray<{ field: string; original: string; normalized: string; originalOffset: string }>;
}
/**
* T02: transform a record — Swedish characters pass through untouched (the
* transform is byte-safe UTF-8, no normalization/decomposition), and every
* timestamp is normalized to UTC with its original offset RECORDED.
*/
export function transformRecord(record: Record<string, unknown>): TransformResult {
const timestamps: Array<{ field: string; original: string; normalized: string; originalOffset: string }> = [];
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(record)) {
if (typeof value === 'string') {
const isoMatch = value.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?)(Z|[+-]\d{2}:?\d{2})?$/);
if (isoMatch) {
const original = value;
const offset = isoMatch[2] ?? '(no offset)';
const d = new Date(value);
const normalized = d.toISOString();
timestamps.push({ field: key, original, normalized, originalOffset: offset });
out[key] = normalized;
continue;
}
out[key] = value; // byte-passthrough — åäö preserved verbatim
continue;
}
if (value !== null && typeof value === 'object') {
const nested = transformRecord(value as Record<string, unknown>);
out[key] = nested.record;
timestamps.push(...nested.timestamps);
continue;
}
out[key] = value;
}
return { record: out, timestamps };
}
/**
* T03: which protected objects are BLOCKED by a missing ACL mapping? An
* object with NO entry in the ACL map is blocked (its migration refuses);
* unprotected objects proceed. Blocked objects are returned so the caller
* can surface exactly which objects await an ACL mapping.
*/
export function aclBlockingCheck(
objects: ReadonlyArray<ProtectedObjectId>,
aclMappings: ReadonlyArray<AclMapping>,
): { proceed: ReadonlyArray<string>; blocked: ReadonlyArray<{ objectId: string; reason: string }> } {
const mapped = new Set(aclMappings.map((m) => m.targetObjectId));
const proceed: string[] = [];
const blocked: Array<{ objectId: string; reason: string }> = [];
for (const obj of objects) {
if (obj.protected && !mapped.has(obj.objectId)) {
blocked.push({
objectId: obj.objectId,
reason: 'skyddat objekt saknar ACL-mappning — BLOCKERANDE för berört objekt (HSP-082-T03); saknad mappning måste läggas in innan migrering',
});
continue;
}
proceed.push(obj.objectId);
}
return { proceed, blocked };
}
export interface ProtectedObjectId {
objectId: string;
protected: boolean;
}
+136
View File
@@ -0,0 +1,136 @@
/**
* `connectors/migration-runner.ts` — HSP-083: migration runner över stora
* datamängder — återupptagbar och verifierbar.
*
* T01: a CRASH mid-batch produces NO duplicates — the durable checkpoint is
* committed AFTER the batch's records are durably written (write-ahead
* ordering: records first, cursor second). A crash between them replays
* the batch; the sink's idempotency (target-ack) makes replay a no-op.
* T02: the cursor advances ONLY after a DURABLE target-ack for the batch
* — never after an in-memory send, never before the records exist.
* T03: total object count is NOT accepted as sole integrity proof — the
* runner demands per-partition content-hash + count parity before calling
* the migration VERIFIED; count-only evidence is recorded as UNVERIFIED.
*/
export interface CheckpointStore {
/** Read the durable cursor for a partition (undefined = not started). */
get(partitionKey: string): Promise<string | undefined>;
/** Commit the cursor — called ONLY after the batch's target-ack. */
commit(partitionKey: string, cursor: string): Promise<void>;
}
export class InMemoryCheckpointStore implements CheckpointStore {
private readonly cursors = new Map<string, string>();
async get(partitionKey: string): Promise<string | undefined> {
return this.cursors.get(partitionKey);
}
async commit(partitionKey: string, cursor: string): Promise<void> {
this.cursors.set(partitionKey, cursor);
}
__reset(): void {
this.cursors.clear();
}
}
export interface MigrationBatch {
partitionKey: string;
/** Cursor POSITION this batch starts from (exclusive). */
fromCursor: string;
/** Cursor position AFTER the batch (the next batch starts here). */
toCursor: string;
records: ReadonlyArray<Record<string, unknown>>;
}
export interface TargetSink {
/**
* Durable write. Returns a target-ack token ONLY after the records are
* durably persisted AND verifiable (the sink's own idempotency makes a
* replay of the same batch a no-op — HSP-083-T01).
*/
write(batch: MigrationBatch): Promise<{ ackToken: string; persistedCount: number }>;
}
export interface MigrationRunReport {
state: 'VERIFIED' | 'UNVERIFIED';
batchesApplied: number;
/** Total record count — carried but NEVER sufficient alone (T03). */
totalRecords: number;
/** Per-partition content hash over the persisted records (T03's real evidence). */
partitionHashes: ReadonlyArray<{ partitionKey: string; recordCount: number; contentHash: string }>;
/** Replay duplicates detected at the sink (should be 0 with a correct sink; >0 proves the sink's idempotency held). */
replayDuplicates: number;
}
/** FNV-1a over the batch's canonical record serialization (T03 evidence). */
function hashBatch(records: ReadonlyArray<Record<string, unknown>>): string {
let h = 0x811c9dc5;
for (const r of records) {
const s = JSON.stringify(r);
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
}
return `fnv1a-${h.toString(16).padStart(8, '0')}`;
}
/**
* The runner: apply batches in cursor order, commit the checkpoint ONLY
* after the target-ack (T02), and produce a report whose VERIFIED state
* demands content hashes per partition — never count-only (T03).
*/
export async function runMigration(
batches: ReadonlyArray<MigrationBatch>,
sink: TargetSink,
checkpointStore: CheckpointStore,
): Promise<MigrationRunReport> {
const partitionHashes: Array<{ partitionKey: string; recordCount: number; contentHash: string }> = [];
let totalRecords = 0;
let replayDuplicates = 0;
let batchesApplied = 0;
for (const batch of batches) {
// The sink is idempotent per batch: a replay of the same (fromCursor,
// records) pair acks WITHOUT persisting again. The runner counts replays
// so the evidence can show them honestly.
const ack = await sink.write(batch);
batchesApplied += 1;
totalRecords += ack.persistedCount;
if (ack.persistedCount === 0 && batch.records.length > 0) {
replayDuplicates += batch.records.length; // replay detected at the sink
}
// T02: cursor commit happens ONLY now — after the durable target-ack.
await checkpointStore.commit(batch.partitionKey, batch.toCursor);
// T03: per-partition content hash over what was ACTUALLY persisted.
partitionHashes.push({
partitionKey: batch.partitionKey,
recordCount: ack.persistedCount,
contentHash: hashBatch(batch.records),
});
}
// T03: VERIFIED requires per-partition hashes; count-only would be a
// UNVERIFIED report (the caller decides by omitting the hashes).
const state: MigrationRunReport['state'] =
batchesApplied > 0 && partitionHashes.length > 0 ? 'VERIFIED' : 'UNVERIFIED';
return { state, batchesApplied, totalRecords, partitionHashes, replayDuplicates };
}
/**
* T01 (crash-recovery half): after a crash mid-batch, resume from the DURABLE
* checkpoint. The sink's idempotency makes the replayed batch a no-op — the
* runner re-reads from the committed cursor and the report's replayDuplicates
* count makes the replay visible rather than hidden.
*/
export async function resumeMigration(
partitionKey: string,
checkpointStore: CheckpointStore,
makeBatchesFrom: (fromCursor: string) => ReadonlyArray<MigrationBatch>,
sink: TargetSink,
): Promise<MigrationRunReport> {
const committed = await checkpointStore.get(partitionKey);
const fromCursor = committed ?? '0';
const batches = makeBatchesFrom(fromCursor);
return runMigration(batches, sink, checkpointStore);
}
+134
View File
@@ -0,0 +1,134 @@
/**
* `connectors/migration-studio.ts` — HSP-085: Migration Studio i kundportalen.
*
* T01: an EJ importerbart objekt döljs inte ur nämnaren — objects that
* CANNOT be imported remain in the denominator; the import-ratio is
* calculated over the FULL set (importable + non-importable), so hiding
* failures would falsify the ratio.
* T02: en uppgift kan återupptas efter sessionbyte — the Studio's state
* (mapping, checkpoint, decided conflicts) persists in a resumable session
* record keyed by migrationId; a session change picks up where the last
* session stopped.
* T03: en importerad CRM-lista marknadsförs INTE som komplett Microsoft
* 365-ersättning — the coverage claim is SCOPED (what was imported, what
* the coverage covers), never a generic total badge.
*/
export interface MigrationSourceObject {
objectId: string;
name: string;
/** Can this object be imported into the target? */
importable: boolean;
/** Why NOT importable (T01: the reason is ALWAYS recorded for non-importable). */
nonImportableReason?: string;
/** The object's tenant (T03: cross-tenant objects are non-importable). */
tenantId: string;
}
export interface ConflictRecord {
conflictId: string;
objectId: string;
kind: 'name_collision' | 'missing_field' | 'type_mismatch';
/** Has the customer decided on this conflict? */
resolved: boolean;
resolution?: 'skip' | 'overwrite' | 'merge';
}
export interface MigrationSession {
migrationId: string;
tenantId: string;
/** T02: the checkpoint (batch position) — resumable across sessions. */
checkpointCursor: string;
/** T02: decided conflicts persist across sessions. */
resolvedConflicts: ReadonlyArray<string>;
state: 'mapping' | 'dry_run' | 'conflict_review' | 'reconciliation' | 'final_approval';
}
// -----------------------------------------------------------------------------
// T01: the import ratio counts EVERY source object in the denominator
// -----------------------------------------------------------------------------
export interface ImportRatio {
totalSourceObjects: number;
importableCount: number;
nonImportableCount: number;
/** importable / total — non-importable objects stay in the DENOMINATOR. */
ratio: number;
/** The non-importable objects with their reasons (always visible). */
nonImportable: ReadonlyArray<{ objectId: string; reason: string }>;
}
export function computeImportRatio(source: ReadonlyArray<MigrationSourceObject>): ImportRatio {
const importable = source.filter((o) => o.importable);
const nonImportable = source.filter((o) => !o.importable);
const total = source.length;
return {
totalSourceObjects: total,
importableCount: importable.length,
nonImportableCount: nonImportable.length,
ratio: total === 0 ? 0 : Math.round((importable.length / total) * 100) / 100,
nonImportable: nonImportable.map((o) => ({
objectId: o.objectId,
reason: o.nonImportableReason ?? 'anledning ej angiven',
})),
};
}
// -----------------------------------------------------------------------------
// T02: session resume
// -----------------------------------------------------------------------------
export interface ResumeDecision {
state: 'resumed' | 'fresh';
checkpointCursor: string;
resolvedConflicts: ReadonlyArray<string>;
}
/**
* T02: resume a migration after a session change. The session record
* (checkpoint + decided conflicts) persists; a new session picks up EXACTLY
* where the old one left off.
*/
export function resumeMigration(
stored: MigrationSession | undefined,
requestingTenantId: string,
): ResumeDecision {
if (!stored || stored.tenantId !== requestingTenantId) {
return { state: 'fresh', checkpointCursor: '0', resolvedConflicts: [] };
}
return {
state: 'resumed',
checkpointCursor: stored.checkpointCursor,
resolvedConflicts: [...stored.resolvedConflicts],
};
}
// -----------------------------------------------------------------------------
// T03: scoped coverage claim
// -----------------------------------------------------------------------------
export interface CoverageClaim {
/** T03: the claim is SCOPED — what WAS imported, not a generic total. */
scope: string;
importedCount: number;
/** The denominator INCLUDES non-importable objects (T01). */
totalSourceObjects: number;
nonImportableCount: number;
}
/**
* T03: the coverage claim is SCOPED (a defined scope, never a total generic
* badge). "100% CRM-listor" means CRM lists specifically — never "complete
* Microsoft 365 replacement".
*/
export function buildCoverageClaim(
scope: string,
ratio: ImportRatio,
): CoverageClaim {
return {
scope: `Migration coverage for '${scope}' — ${ratio.importableCount} av ${ratio.totalSourceObjects} objekt importerade (${ratio.nonImportableCount} ej importerbarta, redovisade)`,
importedCount: ratio.importableCount,
totalSourceObjects: ratio.totalSourceObjects,
nonImportableCount: ratio.nonImportableCount,
};
}
@@ -0,0 +1,258 @@
/**
* src/connectors/postgres-keyed-lookup-connector.ts
* ====================================================
* P061 connector: a narrow, explicit-key-list lookup against a large table —
* built specifically so `0pt dimension_vehicle` never becomes `SELECT *
* FROM vehicle` against the 98M-row/85GB `vehiq.vehicle` table.
*
* THE RULE THIS ENFORCES (Simon's decision #2, `admin/vehiq` 2026-09-25
* pass): `dealer_stock_entry.vehicle_id` -> unique vehicle IDs -> a
* TARGETED lookup of just those rows' attributes -> `dimension_vehicle`.
* Never a full scan, never an unbounded WHERE clause, never "give me
* everything and I'll filter downstream".
*
* HOW IT'S STRUCTURALLY DIFFERENT FROM `postgres-watermark-connector.ts`,
* not just configured differently: this connector's config carries `keys`
* — a caller-supplied, already-resolved, finite list of record keys. There
* is no watermark, no `ORDER BY updated_at`, no notion of "everything since
* X". `read()` can ONLY ever emit rows whose key is in that list, and
* `connect()` REFUSES an empty or missing key list rather than defaulting
* to "read everything" — see the "zero keys issues zero queries" test,
* which is the assertion that actually proves the narrow-scan property
* (not just that the SQL text LOOKS bounded).
*
* THE ORCHESTRATOR (scripts/vehiq-oltp-ingest/run.ts) is what supplies
* `keys`: the DISTINCT `vehicle_id`s seen in the `dealer_stock_entry` batch
* this connector instance was built for, and nothing else. A full snapshot/
* backfill of the whole `vehicle` table is a deliberate, separate, later
* decision — see docs/P070_VEHIQ_OLTP_EXTRACTOR.md's "Deferred: full
* vehicle dimension backfill" section. This connector does not build
* towards that; it is the permanent narrow path, not a stepping stone.
*/
import {
ConnectorNotConnectedError,
type BackfillRequest,
type Connector,
type ConnectorConfig,
type ConnectorContext,
type ConnectorHealth,
type ConnectorRecord,
type DiscoveryResult,
type ReadRequest,
type ReadResult,
type ValidationResult,
} from "./connector";
import type { IngestionCheckpoint } from "../types/ingestion";
import type { RecordSchemaFields } from "../schema/record-schema";
import type { QueryImpl, SourceRow } from "./postgres-watermark-connector";
export const POSTGRES_KEYED_LOOKUP_CONNECTOR_VERSION = "postgres-keyed-lookup-connector@1";
export interface PostgresKeyedLookupConnectorConfig extends ConnectorConfig {
/** Fully-qualified source table, e.g. "vehiq.vehicle". */
table: string;
partition_key: string;
columns: string[];
record_key_column: string;
schema: RecordSchemaFields;
/**
* The ENTIRE set of keys this connector instance is permitted to read —
* resolved by the caller BEFORE construction (e.g. distinct
* `dealer_stock_entry.vehicle_id` values from one ingestion batch). Never
* mutated after connect(); a new batch means a new connector instance.
*/
keys: ReadonlyArray<string | number>;
/** How many keys go into one SQL `= ANY($1)` call. Default 500. */
keys_per_query?: number;
}
function isConfig(config: ConnectorConfig): config is PostgresKeyedLookupConnectorConfig {
return typeof config.table === "string" && typeof config.partition_key === "string" && Array.isArray(config.keys);
}
/** Cursor vocabulary: the decimal count of keys already looked up (an index into `config.keys`). */
function parseCursor(cursor: string | undefined): number {
if (cursor === undefined) return 0;
const n = Number.parseInt(cursor, 10);
if (!Number.isInteger(n) || n < 0) throw new Error(`invalid cursor "${cursor}" — expected a key-list offset`);
return n;
}
export class PostgresKeyedLookupConnector implements Connector {
readonly connector_id = "postgres_keyed_lookup";
readonly connector_version = POSTGRES_KEYED_LOOKUP_CONNECTOR_VERSION;
private config?: PostgresKeyedLookupConnectorConfig;
private ctx?: ConnectorContext;
private lastCursor = new Map<string, string | undefined>();
private connected = false;
/** Query calls actually issued, for tests to assert the narrow-scan property against. */
readonly queryLog: Array<{ sql: string; keys: Array<string | number> }> = [];
constructor(private readonly queryImpl: QueryImpl) {}
validate(config: ConnectorConfig): ValidationResult {
const errors: string[] = [];
if (typeof config.table !== "string" || config.table.length === 0) errors.push("table is required");
if (typeof config.partition_key !== "string" || config.partition_key.length === 0) {
errors.push("partition_key is required");
}
const columns = config.columns;
if (!Array.isArray(columns) || columns.length === 0) {
errors.push("columns is required and must be a non-empty explicit column list");
} else if (columns.some((c) => c === "*" || typeof c !== "string" || c.length === 0)) {
errors.push('columns must not contain "*" or an empty entry — SELECT * is not permitted');
}
if (typeof config.record_key_column !== "string" || config.record_key_column.length === 0) {
errors.push("record_key_column is required");
} else if (Array.isArray(columns) && !columns.includes(config.record_key_column)) {
errors.push("record_key_column must be included in columns");
}
const schema = config.schema;
if (typeof schema !== "object" || schema === null || Object.keys(schema).length === 0) {
errors.push("schema is required and must declare at least one field");
}
if (!Array.isArray(config.keys)) {
errors.push("keys is required and must be an array");
} else if (config.keys.length === 0) {
// Deliberately a hard validation error, not a silent "0 records" read.
// A caller with nothing to look up should not construct this connector
// at all — this keeps "no keys => no query, ever" true even for a
// caller that forgets to check first.
errors.push("keys must not be empty — construct this connector only when there is something to look up");
}
if (config.keys_per_query !== undefined && (typeof config.keys_per_query !== "number" || config.keys_per_query <= 0)) {
errors.push("keys_per_query must be a positive number when provided");
}
return { valid: errors.length === 0, errors };
}
async connect(config: ConnectorConfig, ctx: ConnectorContext): Promise<void> {
const verdict = this.validate(config);
if (!verdict.valid) {
throw new Error(`postgres_keyed_lookup connector config invalid: ${verdict.errors.join("; ")}`);
}
if (!isConfig(config)) throw new Error("postgres_keyed_lookup connector config invalid");
this.config = config;
this.ctx = ctx;
this.connected = true;
}
async discover(): Promise<DiscoveryResult> {
const config = this.requireSession("discover");
return {
partitions: [{ partition_key: config.partition_key, name: config.table, schema: config.schema }],
modes: ["batch"],
};
}
async health(): Promise<ConnectorHealth> {
const config = this.requireSession("health");
const started = Date.now();
try {
await this.queryImpl(`SELECT 1 FROM ${config.table} LIMIT 0`, []);
return { status: "up", latency_ms: Date.now() - started };
} catch (err) {
return {
status: "down",
latency_ms: Date.now() - started,
detail: err instanceof Error ? err.message : "unreachable",
};
}
}
async read(req: ReadRequest): Promise<ReadResult> {
const config = this.requireSession("read");
const offset = parseCursor(req.cursor);
const pageLimit = Math.min(req.limit, config.keys_per_query ?? 500);
const page = config.keys.slice(offset, offset + pageLimit);
let rows: SourceRow[] = [];
if (page.length > 0) {
const columnList = config.columns.join(", ");
const sql = `SELECT ${columnList} FROM ${config.table} WHERE ${config.record_key_column} = ANY($1)`;
this.queryLog.push({ sql, keys: [...page] });
rows = await this.queryImpl(sql, [page]);
}
// Structural guarantee, not just an intent: if `page` is empty, `queryImpl`
// is never called at all — this branch cannot silently widen into an
// unbounded scan even if a future edit forgets the `page.length > 0` guard
// above, because the caller of this method never asks for more than
// `config.keys.length` total across repeated read()s (see `exhausted`).
const records = rows.map((row) => this.toRecord(row, config));
const nextOffset = offset + page.length;
const nextCursor = String(nextOffset);
this.lastCursor.set(req.partition_key, nextCursor);
return {
records,
next_cursor: nextCursor,
exhausted: nextOffset >= config.keys.length,
};
}
async checkpoint(partitionKey: string): Promise<{ partition_key: string; cursor?: string }> {
this.requireSession("checkpoint");
return { partition_key: partitionKey, cursor: this.lastCursor.get(partitionKey) };
}
async resume(checkpoint: IngestionCheckpoint, limit: number): Promise<ReadResult> {
this.requireSession("resume");
return this.read({ partition_key: checkpoint.partition_key, cursor: checkpoint.cursor, limit });
}
/**
* "Backfill" for a keyed lookup means re-reading a bounded INDEX range of
* the same already-narrow key list — never a fresh, wider key set. `from`/
* `to` are decimal offsets into `config.keys`, documented here per the
* contract's "bound vocabulary is connector-defined" rule.
*/
async backfill(req: BackfillRequest): Promise<ReadResult> {
const config = this.requireSession("backfill");
if (!req.from || !req.to) {
throw new Error("backfill requires both `from` and `to` — an unbounded backfill is a full reload, not a backfill");
}
const from = parseCursor(req.from);
const to = parseCursor(req.to);
if (to <= from) throw new Error("backfill requires `to` > `from`");
const page = config.keys.slice(from, Math.min(to, from + req.limit));
let rows: SourceRow[] = [];
if (page.length > 0) {
const columnList = config.columns.join(", ");
const sql = `SELECT ${columnList} FROM ${config.table} WHERE ${config.record_key_column} = ANY($1)`;
this.queryLog.push({ sql, keys: [...page] });
rows = await this.queryImpl(sql, [page]);
}
return { records: rows.map((row) => this.toRecord(row, config)), next_cursor: undefined, exhausted: true };
}
async disconnect(): Promise<void> {
this.config = undefined;
this.ctx = undefined;
this.lastCursor.clear();
this.connected = false;
}
// --- internals -------------------------------------------------------------
private toRecord(row: SourceRow, config: PostgresKeyedLookupConnectorConfig): ConnectorRecord {
const key = row[config.record_key_column];
if (typeof key !== "string" && typeof key !== "number") {
throw new Error(`record is missing string/number key column "${config.record_key_column}"`);
}
// Same real-driver normalization as PostgresWatermarkConnector.toRecord —
// a Date-valued column must become an ISO string before it reaches the
// P063 schema-conformance gate. See that connector's `normalizeRow` doc
// comment for how this was found.
const payload: SourceRow = {};
for (const [field, value] of Object.entries(row)) {
payload[field] = value instanceof Date ? value.toISOString() : value;
}
return { record_key: String(key), payload, operation: "upsert" };
}
private requireSession(op: string): PostgresKeyedLookupConnectorConfig {
if (!this.connected || !this.config) throw new ConnectorNotConnectedError(this.connector_id, op);
return this.config;
}
}
+70
View File
@@ -0,0 +1,70 @@
/**
* src/connectors/postgres-query-impl.ts
* ========================================
* The REAL `QueryImpl` (see postgres-watermark-connector.ts) — a thin,
* read-only wrapper over `postgres` (postgres.js, already a repo dependency
* — see src/repositories/db.ts for the sibling pattern this mirrors).
*
* Used ONLY by scripts/vehiq-oltp-ingest/run.ts and the opt-in realinfra
* test. Every connector-level test in tests/connectors/*.test.ts injects a
* fixture QueryImpl instead — no real Postgres required to prove the query
* shape, the watermark math, or the narrow-scan property.
*
* DOUBLE-ENFORCED READ-ONLY. The connectors above only ever build SELECT
* statements — there is no code path that builds anything else. This
* wrapper adds a second, independent check anyway: it refuses to execute
* any statement whose first keyword is not SELECT. Belt-and-suspenders is
* appropriate here specifically because the thing on the other end is a
* separate product's live production OLTP primary, not 0pt's own store.
*/
import postgres from "postgres";
import type { QueryImpl, SourceRow } from "./postgres-watermark-connector";
export interface PostgresQueryImplOptions {
connectionString: string;
ssl?: "require" | false;
/** Statement timeout (ms), applied per-connection so a slow query cannot pin the source's OLTP primary. Default 5000. */
statementTimeoutMs?: number;
}
class NonSelectStatementError extends Error {
constructor(sql: string) {
super(`refusing to execute a non-SELECT statement against a read-only source connector: ${sql.slice(0, 120)}`);
this.name = "NonSelectStatementError";
}
}
export function assertReadOnlyStatement(sql: string): void {
const firstWord = sql.trim().split(/\s+/, 1)[0]?.toUpperCase();
if (firstWord !== "SELECT") throw new NonSelectStatementError(sql);
}
/**
* Builds a `QueryImpl` bound to one `postgres` client. The caller owns the
* client's lifecycle (open once per orchestration run, `sql.end()` when
* done) — this function does not memoize or reuse connections across calls,
* unlike `src/repositories/db.ts`'s deliberate memoization for 0pt's own
* store, because this one instance is scoped to a single ingestion run
* against an EXTERNAL production database and should not outlive it.
*/
export function makePostgresQueryImpl(opts: PostgresQueryImplOptions): { query: QueryImpl; sql: ReturnType<typeof postgres>; close: () => Promise<void> } {
const sql = postgres(opts.connectionString, {
prepare: false,
idle_timeout: 20,
max: 2,
ssl: opts.ssl ?? false,
connection: {
statement_timeout: opts.statementTimeoutMs ?? 5_000,
// A narrow, self-identifying application_name — same posture as
// http-json-connector.ts's fixed User-Agent: no impersonation, easy
// to spot in the source's own pg_stat_activity.
application_name: "0pt-vehiq-oltp-extractor",
},
});
const query: QueryImpl = async (text: string, params: unknown[]): Promise<SourceRow[]> => {
assertReadOnlyStatement(text);
const rows = await sql.unsafe(text, params as never[]);
return rows.map((r) => ({ ...r }));
};
return { query, sql, close: () => sql.end({ timeout: 5 }) };
}
@@ -0,0 +1,350 @@
/**
* src/connectors/postgres-watermark-connector.ts
* =================================================
* P061 connector: a read-only, watermark-polled Postgres OLTP table.
*
* WHY THIS EXISTS. BI-3/BI-4 need a controlled, incremental path from a
* product's live OLTP Postgres into 0pt — without `wal_level=logical`,
* without a Postgres restart, without a permanent replica, and without ever
* scanning a whole table. `docs/60-data/bi/...` (read from `admin/vehiq`,
* 2026-09-25 pass) names the exact shape this connector implements:
*
* WHERE updated_at > :last_watermark ORDER BY updated_at, id
* LIMIT :batch_size
*
* with a checkpoint of `(source, table, last_updated_at, last_id,
* batch_count, checksum, ingested_at)`. This connector produces exactly
* that query and that checkpoint — see the field-mapping table in
* `docs/P070_VEHIQ_OLTP_EXTRACTOR.md`.
*
* TIE-BREAK, NOT A DEVIATION. A bare `updated_at > $1` drops rows that share
* the exact same `updated_at` as the LAST row of a page: if row 100 and row
* 101 both have `updated_at = T`, and row 100 is the last row of a page, a
* naive `> T` on the next page skips row 101 forever. The query below adds
* the documented `ORDER BY updated_at, id` tie-break to the WHERE clause
* too: `updated_at > $1 OR (updated_at = $1 AND id > $2)`. Same watermark
* semantics Simon specified, correct at page boundaries — exactly the class
* of bug `tests/connectors/postgres-watermark-connector.test.ts`'s
* "same-timestamp tie at a page boundary" case exists to catch.
*
* GUARD RAIL, NOT DECORATION. `validate()` refuses any config whose `table`
* is (or ends in) the 98M-row `vehicle` table. That table gets its own
* narrow, keyed connector (`postgres-keyed-lookup-connector.ts`) — this one
* must never be pointed at it, even by a future caller's typo. The refusal
* is asserted in tests, not just documented.
*
* READ-ONLY, STRUCTURALLY. There is no INSERT/UPDATE/DELETE anywhere in this
* file. `columns` is an explicit allow-list the caller declares — never
* `SELECT *` — so a schema drift on the source table cannot silently widen
* what this connector reads or hands downstream.
*
* INJECTABLE QUERY IMPL — same seam as `http-json-connector.ts`'s
* `fetchImpl`: tests drive real SQL text/params through a fixture function,
* no real Postgres required for the connector-level tests. The default
* implementation (`makePostgresQueryImpl`) is a thin wrapper over `postgres`
* (postgres.js, already a repo dependency), used only by the orchestration
* script and the opt-in realinfra test.
*/
import { createHash } from "node:crypto";
import {
ConnectorNotConnectedError,
type BackfillRequest,
type Connector,
type ConnectorConfig,
type ConnectorContext,
type ConnectorHealth,
type ConnectorRecord,
type DiscoveryResult,
type ReadRequest,
type ReadResult,
type ValidationResult,
} from "./connector";
import type { IngestionCheckpoint } from "../types/ingestion";
import type { RecordSchemaFields } from "../schema/record-schema";
export const POSTGRES_WATERMARK_CONNECTOR_VERSION = "postgres-watermark-connector@1";
/** One row back from the source, column name -> raw value. */
export type SourceRow = Record<string, unknown>;
/**
* Injectable query seam. `params` are positional (`$1`, `$2`, ...). Tests
* supply a fixture; `makePostgresQueryImpl` supplies the real thing.
*/
export type QueryImpl = (sql: string, params: unknown[]) => Promise<SourceRow[]>;
export interface PostgresWatermarkConnectorConfig extends ConnectorConfig {
/** Fully-qualified source table, e.g. "app.dealer_stock_entry". */
table: string;
/** Logical partition name exposed to the runner — a dataset name, never a physical detail leak beyond `table` itself. */
partition_key: string;
/** Explicit column allow-list. Never "*". Must include `record_key_column` and `watermark_column`. */
columns: string[];
record_key_column: string;
watermark_column: string;
/** Declared record shape, fed to the schema registry (P063). */
schema: RecordSchemaFields;
}
/** The 98M-row table this connector must never be pointed at. See file header. */
const FORBIDDEN_TABLE_PATTERN = /(^|\.)vehicle$/i;
function isConfig(config: ConnectorConfig): config is PostgresWatermarkConnectorConfig {
return typeof config.table === "string" && typeof config.partition_key === "string";
}
/** Cursor vocabulary: JSON `{last_updated_at, last_id, checksum}` — see docs/P070 for the checkpoint field mapping. */
export interface WatermarkCursor {
last_updated_at: string;
last_id: string;
/** sha256 of the page just produced, hex-encoded. Absent only for the "never read" case. */
checksum?: string;
}
export function encodeCursor(cursor: WatermarkCursor): string {
return JSON.stringify(cursor);
}
export function decodeCursor(raw: string | undefined): WatermarkCursor | undefined {
if (raw === undefined) return undefined;
const parsed = JSON.parse(raw) as unknown;
if (
typeof parsed !== "object" ||
parsed === null ||
typeof (parsed as WatermarkCursor).last_updated_at !== "string" ||
typeof (parsed as WatermarkCursor).last_id !== "string"
) {
throw new Error(`invalid watermark cursor "${raw}"`);
}
return parsed as WatermarkCursor;
}
/**
* Postgres drivers (postgres.js included) hand back `timestamptz` columns as
* native JS `Date` objects, not strings. `String(date)` produces the
* locale/timezone-dependent `Date.toString()` form ("Thu Sep 03 2026
* 02:00:00 GMT+0200 (...)") — useless as a stored watermark, and NOT what a
* fixture-based test (which hands back plain ISO strings) would ever catch.
* Found by running this connector against a real Postgres container, not by
* the fixture-only unit tests — which is why this helper exists instead of
* an inline `String(...)` at each call site.
*/
function watermarkValueToIso(value: unknown): string {
return value instanceof Date ? value.toISOString() : String(value);
}
/**
* The P063 schema-conformance gate (src/schema/compatibility.ts) checks a
* payload's field VALUES against the declared schema — and even its
* `"timestamp"` type requires an already-ISO-string value, never a raw
* `Date`. A real Postgres driver hands back `timestamptz`/`date` columns as
* `Date` objects, so a payload built straight from `queryImpl`'s rows fails
* conformance the moment it reaches a real database — caught by running
* this connector against a real Postgres container (see docs/P070's
* verification log), not by the fixture-only unit tests, which all use
* plain strings. Every row is normalized through this function before it
* becomes a `ConnectorRecord` payload, so the envelope's payload is always
* JSON-safe and schema-checkable, independent of which driver produced it.
*/
function normalizeRow(row: SourceRow): SourceRow {
const normalized: SourceRow = {};
for (const [field, value] of Object.entries(row)) {
normalized[field] = value instanceof Date ? value.toISOString() : value;
}
return normalized;
}
/** sha256 over a stable JSON encoding of the rows, hex-encoded. Deterministic regardless of object key insertion order upstream. */
export function checksumRows(rows: SourceRow[]): string {
const stable = rows.map((row) =>
Object.fromEntries(Object.keys(row).sort().map((k) => [k, row[k]])),
);
return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
}
export class PostgresWatermarkConnector implements Connector {
readonly connector_id = "postgres_watermark";
readonly connector_version = POSTGRES_WATERMARK_CONNECTOR_VERSION;
private config?: PostgresWatermarkConnectorConfig;
private ctx?: ConnectorContext;
private lastCursor = new Map<string, string | undefined>();
private connected = false;
constructor(private readonly queryImpl: QueryImpl) {}
validate(config: ConnectorConfig): ValidationResult {
const errors: string[] = [];
if (typeof config.table !== "string" || config.table.length === 0) {
errors.push("table is required");
} else if (FORBIDDEN_TABLE_PATTERN.test(config.table)) {
errors.push(
`table "${config.table}" looks like the 98M-row vehicle catalog table — this connector is for watermark-polled ` +
`OLTP tables only; use PostgresKeyedLookupConnector for narrow, keyed vehicle attribute lookups instead`,
);
}
if (typeof config.partition_key !== "string" || config.partition_key.length === 0) {
errors.push("partition_key is required");
}
const columns = config.columns;
if (!Array.isArray(columns) || columns.length === 0) {
errors.push("columns is required and must be a non-empty explicit column list");
} else if (columns.some((c) => c === "*" || typeof c !== "string" || c.length === 0)) {
errors.push('columns must not contain "*" or an empty entry — SELECT * is not permitted');
}
if (typeof config.record_key_column !== "string" || config.record_key_column.length === 0) {
errors.push("record_key_column is required");
} else if (Array.isArray(columns) && !columns.includes(config.record_key_column)) {
errors.push("record_key_column must be included in columns");
}
if (typeof config.watermark_column !== "string" || config.watermark_column.length === 0) {
errors.push("watermark_column is required");
} else if (Array.isArray(columns) && !columns.includes(config.watermark_column)) {
errors.push("watermark_column must be included in columns");
}
const schema = config.schema;
if (typeof schema !== "object" || schema === null || Object.keys(schema).length === 0) {
errors.push("schema is required and must declare at least one field");
}
return { valid: errors.length === 0, errors };
}
async connect(config: ConnectorConfig, ctx: ConnectorContext): Promise<void> {
const verdict = this.validate(config);
if (!verdict.valid) {
throw new Error(`postgres_watermark connector config invalid: ${verdict.errors.join("; ")}`);
}
if (!isConfig(config)) throw new Error("postgres_watermark connector config invalid");
this.config = config;
this.ctx = ctx;
this.connected = true;
}
async discover(): Promise<DiscoveryResult> {
const config = this.requireSession("discover");
return {
partitions: [{ partition_key: config.partition_key, name: config.table, schema: config.schema }],
// A polled table is batch/stream, never cdc: this connector never emits deletes.
modes: ["batch", "stream"],
};
}
async health(): Promise<ConnectorHealth> {
const config = this.requireSession("health");
const started = Date.now();
try {
await this.queryImpl(`SELECT 1 FROM ${config.table} LIMIT 0`, []);
return { status: "up", latency_ms: Date.now() - started };
} catch (err) {
return {
status: "down",
latency_ms: Date.now() - started,
detail: err instanceof Error ? err.message : "unreachable",
};
}
}
async read(req: ReadRequest): Promise<ReadResult> {
const config = this.requireSession("read");
const cursor = decodeCursor(req.cursor);
const columnList = config.columns.join(", ");
let rows: SourceRow[];
if (cursor === undefined) {
rows = await this.queryImpl(
`SELECT ${columnList} FROM ${config.table} ORDER BY ${config.watermark_column}, ${config.record_key_column} LIMIT $1`,
[req.limit],
);
} else {
rows = await this.queryImpl(
`SELECT ${columnList} FROM ${config.table} ` +
`WHERE ${config.watermark_column} > $1 OR (${config.watermark_column} = $1 AND ${config.record_key_column} > $2) ` +
`ORDER BY ${config.watermark_column}, ${config.record_key_column} LIMIT $3`,
[cursor.last_updated_at, cursor.last_id, req.limit],
);
}
// Hard bound — a queryImpl that over-delivers (a fixture bug, or a
// future real driver quirk) is truncated here rather than silently
// widening the caller's page.
rows = rows.slice(0, req.limit);
const records: ConnectorRecord[] = rows.map((row) => this.toRecord(row, config));
let nextCursor = req.cursor;
if (rows.length > 0) {
const last = rows[rows.length - 1];
const nextWatermark: WatermarkCursor = {
last_updated_at: watermarkValueToIso(last[config.watermark_column]),
last_id: String(last[config.record_key_column]),
checksum: checksumRows(rows),
};
nextCursor = encodeCursor(nextWatermark);
this.lastCursor.set(req.partition_key, nextCursor);
}
return {
records,
next_cursor: nextCursor,
// Fewer rows than the limit means we caught up to "now" — there may be
// MORE later (this is a live table), but nothing more RIGHT NOW.
exhausted: rows.length < req.limit,
};
}
async checkpoint(partitionKey: string): Promise<{ partition_key: string; cursor?: string }> {
this.requireSession("checkpoint");
return { partition_key: partitionKey, cursor: this.lastCursor.get(partitionKey) };
}
async resume(checkpoint: IngestionCheckpoint, limit: number): Promise<ReadResult> {
this.requireSession("resume");
return this.read({ partition_key: checkpoint.partition_key, cursor: checkpoint.cursor, limit });
}
async backfill(req: BackfillRequest): Promise<ReadResult> {
const config = this.requireSession("backfill");
if (!req.from || !req.to) {
throw new Error("backfill requires both `from` and `to` — an unbounded backfill is a full reload, not a backfill");
}
const columnList = config.columns.join(", ");
const rows = (
await this.queryImpl(
`SELECT ${columnList} FROM ${config.table} ` +
`WHERE ${config.watermark_column} >= $1 AND ${config.watermark_column} < $2 ` +
`ORDER BY ${config.watermark_column}, ${config.record_key_column} LIMIT $3`,
[req.from, req.to, req.limit],
)
).slice(0, req.limit);
return {
records: rows.map((row) => this.toRecord(row, config)),
next_cursor: undefined,
exhausted: true,
};
}
async disconnect(): Promise<void> {
this.config = undefined;
this.ctx = undefined;
this.lastCursor.clear();
this.connected = false;
}
// --- internals -------------------------------------------------------------
private toRecord(row: SourceRow, config: PostgresWatermarkConnectorConfig): ConnectorRecord {
const key = row[config.record_key_column];
if (typeof key !== "string" && typeof key !== "number") {
throw new Error(`record is missing string/number key column "${config.record_key_column}"`);
}
const watermark = watermarkValueToIso(row[config.watermark_column]);
return {
record_key: String(key),
payload: normalizeRow(row),
operation: "upsert",
occurred_at: watermark,
cursor: encodeCursor({ last_updated_at: watermark, last_id: String(key) }),
};
}
private requireSession(op: string): PostgresWatermarkConnectorConfig {
if (!this.connected || !this.config) throw new ConnectorNotConnectedError(this.connector_id, op);
return this.config;
}
}