/** * 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): Promise; deleteIndex(physicalIndex: string): Promise; indexExists(physicalIndex: string): Promise; bulkIndex(physicalIndex: string, docs: { id: string; body: Record }[]): 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 }[]; }>; /** Atomic alias cutover: remove alias from all current indices, add to `physicalIndex`. */ switchAlias(alias: string, physicalIndex: string): Promise; /** Physical indices an alias points at (empty when alias unknown). */ aliasTargets(alias: string): Promise; /** List physical indices matching a pattern. */ listIndices(pattern: string): Promise; refresh(physicalIndex: string): Promise; 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 = { "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): Promise { await this.request("PUT", `/${encodeURIComponent(physicalIndex)}`, { settings: { number_of_shards: 1, number_of_replicas: 0 }, mappings, }); } async deleteIndex(physicalIndex: string): Promise { await this.request("DELETE", `/${encodeURIComponent(physicalIndex)}`, undefined, { acceptStatuses: [404] }); } async indexExists(physicalIndex: string): Promise { const res = await this.request("HEAD", `/${encodeURIComponent(physicalIndex)}`, undefined, { acceptStatuses: [404], }); return res.status === 200; } async bulkIndex( physicalIndex: string, docs: { id: string; body: Record }[] ): 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 }[]; }> { 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 }[]; }; }; return { total: json.hits?.total?.value ?? 0, hits: json.hits?.hits ?? [] }; } async switchAlias(alias: string, physicalIndex: string): Promise { 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 { const res = await this.request("GET", `/_alias/${encodeURIComponent(alias)}`, undefined, { acceptStatuses: [404], }); if (res.status === 404) return []; return Object.keys((res.json as Record) ?? {}); } async listIndices(pattern: string): Promise { 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 { 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" }; } }