- Source Registry (§10): rights/license/purpose metadata, provenance,
freshness SLA, health checks, describe/query; purpose gate FAILS CLOSED
(no rights record => deny); cross-tenant probes => NOT_FOUND.
- Search (§10/§42): OpenSearch REST adapter (no SDK) + SearchService with
MANDATORY tenant + purpose/rights filtering, versioned index definitions,
bulk, generation-per-rebuild (opt-{name}--g{n}) with atomic alias cutover,
rollback, failed-rebuild generation discard. OpenSearch never canonical.
- Quality (§10): versioned rule registry (GE-JSON interchange), local
engine for the GE core subset (never silently passes unsupported types),
runs/results/issues/score/trend, whole-run delegation to the GE backend
via N0D (0pt.quality.ge_run) - never fabricated results.
- Dataset (§10/§5/§53): immutable numbered versions holding canonical
st0re:artifact refs only, idempotent createVersion, export registers the
ST0RE artifact + AUD0 evidence + OpenLineage.
- Metadata (§10): OpenMetadata PUT /api/v1/tables projection adapter +
projectAll rebuild path; projection never canonical.
- Analytics (§10): ClickHouse HTTP adapter, closed metric-query DSL with
FORCED tenant predicate + readonly/max_execution_time/max_result_rows,
TTL retention. Zero connection to b0ts/quarantined pipelines.
- Features (§10): versioned feature-view registry, real Feast
get-online-features adapter, materialize/get-historical as N0D delegation.
- ER (§10): generic candidate API with deterministic blocking + transparent
scoring + per-field explanations, product hard-rule hook (force both
directions), review-band handoff, Splink batch via N0D contract.
93 new unit/contract tests; suite 248 passed / 1 skipped.
Co-Authored-By: Claude Fable 5 <[email protected]>
199 lines
7.5 KiB
TypeScript
199 lines
7.5 KiB
TypeScript
/**
|
|
* src/search/opensearch-adapter.ts
|
|
* =================================
|
|
* 0pt's OpenSearch adapter (Master-DoD §10 Search). Raw REST via fetch — no
|
|
* OpenSearch SDK dependency (same "small surface, explicit wire" posture as
|
|
* the platform clients; the REST calls used here are stable public API:
|
|
* PUT index, POST _bulk, POST _search, POST _aliases, DELETE index).
|
|
*
|
|
* This adapter is DUMB on purpose: it knows OpenSearch, not 0pt's rules.
|
|
* Tenant scoping, purpose/rights filtering, generation naming and rebuild
|
|
* orchestration live in SearchService — the adapter never decides what is
|
|
* safe to return.
|
|
*
|
|
* OpenSearch is NEVER canonical truth (§42): nothing here is the system of
|
|
* record; everything can be deleted and rebuilt via SearchService.rebuild.
|
|
*/
|
|
import { SiaxError, siaxErrorCodeForUpstreamStatus } from "../platform/errors";
|
|
|
|
export interface OpenSearchAdapterOptions {
|
|
baseUrl: string;
|
|
/** Basic auth as "user:pass" — local/dev clusters often run security-disabled. */
|
|
basicAuth?: string;
|
|
timeoutMs?: number;
|
|
}
|
|
|
|
export interface OpenSearchSearchBody {
|
|
query: unknown;
|
|
from?: number;
|
|
size?: number;
|
|
sort?: unknown[];
|
|
track_total_hits?: boolean;
|
|
}
|
|
|
|
export interface OpenSearchAdapter {
|
|
createIndex(physicalIndex: string, mappings: Record<string, unknown>): Promise<void>;
|
|
deleteIndex(physicalIndex: string): Promise<void>;
|
|
indexExists(physicalIndex: string): Promise<boolean>;
|
|
bulkIndex(physicalIndex: string, docs: { id: string; body: Record<string, unknown> }[]): Promise<{
|
|
errors: { doc_id: string; error: string }[];
|
|
}>;
|
|
search(target: string, body: OpenSearchSearchBody): Promise<{
|
|
total: number;
|
|
hits: { _id: string; _score: number | null; _index: string; _source: Record<string, unknown> }[];
|
|
}>;
|
|
/** Atomic alias cutover: remove alias from all current indices, add to `physicalIndex`. */
|
|
switchAlias(alias: string, physicalIndex: string): Promise<void>;
|
|
/** Physical indices an alias points at (empty when alias unknown). */
|
|
aliasTargets(alias: string): Promise<string[]>;
|
|
/** List physical indices matching a pattern. */
|
|
listIndices(pattern: string): Promise<string[]>;
|
|
refresh(physicalIndex: string): Promise<void>;
|
|
health(): Promise<{ status: string }>;
|
|
}
|
|
|
|
export class HttpOpenSearchAdapter implements OpenSearchAdapter {
|
|
private readonly baseUrl: string;
|
|
private readonly authHeader?: string;
|
|
private readonly timeoutMs: number;
|
|
|
|
constructor(opts: OpenSearchAdapterOptions) {
|
|
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
|
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString("base64")}` : undefined;
|
|
this.timeoutMs = opts.timeoutMs ?? 30_000;
|
|
}
|
|
|
|
private async request(
|
|
method: string,
|
|
path: string,
|
|
body?: unknown,
|
|
opts?: { ndjson?: string; acceptStatuses?: number[] }
|
|
): Promise<{ status: number; json: unknown }> {
|
|
const headers: Record<string, string> = {
|
|
"Content-Type": opts?.ndjson !== undefined ? "application/x-ndjson" : "application/json",
|
|
};
|
|
if (this.authHeader) headers["Authorization"] = this.authHeader;
|
|
let res: Response;
|
|
try {
|
|
res = await fetch(`${this.baseUrl}${path}`, {
|
|
method,
|
|
headers,
|
|
body: opts?.ndjson !== undefined ? opts.ndjson : body === undefined ? undefined : JSON.stringify(body),
|
|
signal: AbortSignal.timeout(this.timeoutMs),
|
|
});
|
|
} catch (cause) {
|
|
throw new SiaxError("DEPENDENCY_UNAVAILABLE", "opensearch", `${method} ${path} unreachable`, { cause });
|
|
}
|
|
const json = (await res.json().catch(() => undefined)) as unknown;
|
|
if (!res.ok && !(opts?.acceptStatuses ?? []).includes(res.status)) {
|
|
const reason =
|
|
(json as { error?: { type?: string; reason?: string } } | undefined)?.error?.type ?? `http_${res.status}`;
|
|
throw new SiaxError(
|
|
siaxErrorCodeForUpstreamStatus(res.status),
|
|
"opensearch",
|
|
`${method} ${path} → HTTP ${res.status} (${reason})`
|
|
);
|
|
}
|
|
return { status: res.status, json };
|
|
}
|
|
|
|
async createIndex(physicalIndex: string, mappings: Record<string, unknown>): Promise<void> {
|
|
await this.request("PUT", `/${encodeURIComponent(physicalIndex)}`, {
|
|
settings: { number_of_shards: 1, number_of_replicas: 0 },
|
|
mappings,
|
|
});
|
|
}
|
|
|
|
async deleteIndex(physicalIndex: string): Promise<void> {
|
|
await this.request("DELETE", `/${encodeURIComponent(physicalIndex)}`, undefined, { acceptStatuses: [404] });
|
|
}
|
|
|
|
async indexExists(physicalIndex: string): Promise<boolean> {
|
|
const res = await this.request("HEAD", `/${encodeURIComponent(physicalIndex)}`, undefined, {
|
|
acceptStatuses: [404],
|
|
});
|
|
return res.status === 200;
|
|
}
|
|
|
|
async bulkIndex(
|
|
physicalIndex: string,
|
|
docs: { id: string; body: Record<string, unknown> }[]
|
|
): Promise<{ errors: { doc_id: string; error: string }[] }> {
|
|
if (docs.length === 0) return { errors: [] };
|
|
const lines: string[] = [];
|
|
for (const doc of docs) {
|
|
lines.push(JSON.stringify({ index: { _index: physicalIndex, _id: doc.id } }));
|
|
lines.push(JSON.stringify(doc.body));
|
|
}
|
|
const res = await this.request("POST", "/_bulk", undefined, { ndjson: lines.join("\n") + "\n" });
|
|
const body = res.json as {
|
|
errors?: boolean;
|
|
items?: { index?: { _id?: string; error?: { type?: string; reason?: string } } }[];
|
|
};
|
|
const errors: { doc_id: string; error: string }[] = [];
|
|
if (body.errors && body.items) {
|
|
for (const item of body.items) {
|
|
if (item.index?.error) {
|
|
errors.push({ doc_id: item.index._id ?? "?", error: item.index.error.type ?? "bulk_error" });
|
|
}
|
|
}
|
|
}
|
|
return { errors };
|
|
}
|
|
|
|
async search(
|
|
target: string,
|
|
body: OpenSearchSearchBody
|
|
): Promise<{
|
|
total: number;
|
|
hits: { _id: string; _score: number | null; _index: string; _source: Record<string, unknown> }[];
|
|
}> {
|
|
const res = await this.request("POST", `/${encodeURIComponent(target)}/_search`, {
|
|
track_total_hits: true,
|
|
...body,
|
|
});
|
|
const json = res.json as {
|
|
hits?: {
|
|
total?: { value?: number };
|
|
hits?: { _id: string; _score: number | null; _index: string; _source: Record<string, unknown> }[];
|
|
};
|
|
};
|
|
return { total: json.hits?.total?.value ?? 0, hits: json.hits?.hits ?? [] };
|
|
}
|
|
|
|
async switchAlias(alias: string, physicalIndex: string): Promise<void> {
|
|
const current = await this.aliasTargets(alias);
|
|
const actions: unknown[] = current.map((idx) => ({ remove: { index: idx, alias } }));
|
|
actions.push({ add: { index: physicalIndex, alias } });
|
|
await this.request("POST", "/_aliases", { actions });
|
|
}
|
|
|
|
async aliasTargets(alias: string): Promise<string[]> {
|
|
const res = await this.request("GET", `/_alias/${encodeURIComponent(alias)}`, undefined, {
|
|
acceptStatuses: [404],
|
|
});
|
|
if (res.status === 404) return [];
|
|
return Object.keys((res.json as Record<string, unknown>) ?? {});
|
|
}
|
|
|
|
async listIndices(pattern: string): Promise<string[]> {
|
|
const res = await this.request(
|
|
"GET",
|
|
`/_cat/indices/${encodeURIComponent(pattern)}?format=json&h=index`,
|
|
undefined,
|
|
{ acceptStatuses: [404] }
|
|
);
|
|
if (res.status === 404) return [];
|
|
return ((res.json as { index: string }[]) ?? []).map((r) => r.index);
|
|
}
|
|
|
|
async refresh(physicalIndex: string): Promise<void> {
|
|
await this.request("POST", `/${encodeURIComponent(physicalIndex)}/_refresh`);
|
|
}
|
|
|
|
async health(): Promise<{ status: string }> {
|
|
const res = await this.request("GET", "/_cluster/health");
|
|
return { status: (res.json as { status?: string })?.status ?? "unknown" };
|
|
}
|
|
}
|