Files
0pt/src/connectors/http-json-connector.ts
T
Claude Opus 5 b5ab885a67
CI (SIAX Cloud) / security (push) Successful in 27s
Security Scan (SIAX Cloud) / security (push) Successful in 30s
CI (SIAX Cloud) / quality (push) Successful in 39s
CI (SIAX Cloud) / security (pull_request) Successful in 43s
CI (SIAX Cloud) / integration (push) Successful in 51s
CI (SIAX Cloud) / quality (pull_request) Successful in 54s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m15s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 13s
feat(analytics): BI-P129 — ConnectorProvider, and four gates on where data lands
BI-P129 names four provider kinds (native, dlt, Meltano/Singer, Airbyte-if-
licensed). This commit ships the seam and the `native` provider; dlt and
Singer follow on this branch.

What is deliberately NOT here: a second ingestion stack. 0pt already has the
P061 connector contract, the P062 runner with durable checkpoints and
crash/resume tests, the schema registry, the quality gate and the idempotency
ledger. A provider's job is to hand back a P061 `Connector`; the highway is
the one that exists.

What is new is the question the P061 stack has no opinion about: an ingestion
run has to LAND somewhere, and where it lands is an analytics contract
question. Four fail-closed gates, each attacked with the guard (must refuse)
AND without it (must succeed — otherwise the guard is decoration):

  1. tier — source data lands in RAW, or NORMALIZED with a declared
     normalization. Never directly in CURATED/SERVING. BI-P003's "no business
     dashboard reads arbitrary raw ingestion tables" is defeated in one line
     by relabelling the landing table SERVING; the tier is therefore checked
     at WRITE, not only at read.
  2. contract coverage — every field discovery actually reported must be
     declared in the BI-P004 contract. An undeclared column is an
     unclassified column. The counterfactual test lands `personnummer` into a
     RAW table whose contract says pii_classification "none", and the runner
     reports success: that is the harm, shown rather than asserted.
  3. physical home — RAW/NORMALIZED land as Parquet/Iceberg in ST0RE
     (st0re#45 shapes), never straight into ClickHouse.
  4. provider readiness — a provider whose own providerReadiness() says
     verified:false cannot run in a production runtime without a recorded,
     named exception. This is the structural form of the honesty rule 0pt#35
     set with MetricFlow.

Airbyte is a declared kind with NO implementation: its server is ELv2, which
restricts offering the software as a managed service, and that is exactly
what 0pt does. Registering or planning one is refused at the registry, in one
place, so a future licence review has a single constant to change.

BI-P129 DoD — "two real source types ingest into canonical analytics tiers" —
is proven with the two real, heterogeneous P061 connectors: a JSONL file on
actual disk (cursor = line offset, real CDC deletes) and an HTTP JSON API
driven through a real fetch/Response cycle (cursor = opaque server token).
Both run through the real runner into the declared RAW tier, paged, with
9 rows landed each and distinct envelope ids.

Verification: 24 tests. Mutation-checked — neutering gates 1 and 2 fails 5 of
them, so they are load-bearing rather than incidental.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 06:22:07 +02:00

275 lines
11 KiB
TypeScript

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