UNPKG

@nullplatform/ingest

Version:

Client SDK for the nullplatform ingest API: push snapshots and delta events from a collector into the catalog and other targets, follow runs, replay and drift checks

162 lines (151 loc) • 6.46 kB
/** * 04-failures-and-guards — what goes wrong, and how a collector reacts. * * SCENARIO: the defensive edges of a snapshot collector. * 1. A dry-run finalize: see what a snapshot WOULD delete before letting it. * 2. A refused batch: a typo'd record type makes the API reject the batch. * The run stops (every later add/finalize throws the same error), so it * can never be finalized into deleting what the lost batch carried. Abort * it and take a new snapshot. * 3. API errors: `IngestError` carries `status`, `code` and `body`; * `retryable` says the failure is transient (5xx, 429, unreachable). The * SDK already retried it, unless the call is a POST a resend could * repeat (opening a run is sent once). 401/403/400/404/409 are * deterministic. * 4. A bad input id: every input id must be a UUIDv7; the SDK refuses any * other before sending (omit the id and it generates one). * 5. Soft delete: deleting a source keeps its history; creating it again * revives it. * * Run it like 01-snapshot.cjs: NULLPLATFORM_API_KEY=… node examples/04-failures-and-guards.cjs */ const { Engine, IngestClient, IngestError, IngestErrorCode, OnConflict, uuidv7, } = require('@nullplatform/ingest'); // ── client: the SDK reads no environment; this example reads the API key and ─ // passes it in. Everything else is the SDK's default: the public API. function connect() { const apiKey = process.env.NULLPLATFORM_API_KEY ?? process.env.NP_API_KEY; if (!apiKey) { console.error('Set NULLPLATFORM_API_KEY (or NP_API_KEY) to run this example.'); process.exit(1); } return new IngestClient({ apiKey }); } const SOURCE = 'dns-zones'; async function seed(ingest) { // 'dns' is the organization's own source type (kubernetes, say, is nullplatform's). // Every setup call is an upsert: re-run, it sends nothing. await ingest.sourceTypes.upsert([{ slug: 'dns', name: 'DNS provider' }]); const [source] = await ingest.sources.upsert([ { slug: SOURCE, name: 'DNS zones', type: 'dns', runs: { maxDeleteRatio: 0.5 } }, ]); const [mapping] = await ingest.mappings.upsertForSource(source.id, [ { recordType: 'zone', engine: Engine.JSONATA, expression: '{ "id": name, "data": $ }' }, ]); await ingest.destinations.upsertForSource(source.id, [ { mappingId: mapping.id, target: 'catalog', endpoint: 'dns-zone' }, ]); const run = await ingest.runs.open(source.id, { onConflict: OnConflict.ABORT }); ['example.com', 'example.net', 'example.org'].forEach((name) => { run.add({ type: 'zone', payload: { name, records: 12 } }); }); await run.finalize(); return source; } /** 1. Report a snapshot, but only delete when the dry run looks sane. */ async function cautiousSnapshot(ingest, source, zones) { const run = await ingest.runs.open(source.id, { onConflict: OnConflict.ABORT }); zones.forEach((name) => run.add({ type: 'zone', payload: { name, records: 12 } })); const preview = await run.finalize({ dryRun: true }); // the run stays open const { seen, stale, guardReason } = preview.reconciliation; console.log(`dry run: ${seen} seen, ${stale} would be deleted`, guardReason || ''); if (preview.reconciliation.guardTripped) { // The guard would refuse anyway; close the run without deleting anything. return run.abort(); } return run.finalize(); } /** 2. A batch the API refuses stops the run; abort it. */ async function snapshotWithATypo(ingest, source) { const run = await ingest.runs.open(source.id, { onConflict: OnConflict.ABORT }); run.add({ type: 'zone', payload: { name: 'example.com', records: 12 } }); run.add({ type: 'zoen', payload: { name: 'example.net', records: 12 } }); // no such mapping try { await run.finalize(); throw new Error('expected the refused batch to stop the run'); } catch (error) { if (!(error instanceof IngestError) || error.code !== IngestErrorCode.VALIDATION) { throw error; } console.log('refused batch:', error.status, error.code, error.message); const aborted = await run.abort(); console.log('run', aborted.status, '— nothing was deleted'); } } /** 3. Telling API errors apart. */ async function describeFailure(ingest) { try { // Ids are the API's UUIDs: this one names no source. await ingest.runs.open(uuidv7()); } catch (error) { if (!(error instanceof IngestError)) { throw error; } switch (error.code) { case IngestErrorCode.NOT_FOUND: console.log('no such source — register it first:', error.message); break; case IngestErrorCode.AUTHORIZATION: console.log('the API key lacks permission; retrying will not help'); break; default: console.log(error.retryable ? 'transient, try later:' : 'refused:', error.message); } } } /** 4. Input ids are UUIDv7s: yours are checked, missing ones are generated. */ async function ids(ingest, source) { const events = ingest.events.batcher(source.id); const mine = uuidv7(); console.log( 'kept id:', events.upsert('zone', { name: 'example.dev', records: 3 }, { id: mine }) === mine, ); try { events.upsert('zone', { name: 'example.app' }, { id: 'a4b1c2d3-0000-4000-8000-000000000000' }); } catch (error) { console.log('refused id:', error.message); } await events.close(); } /** 5. Soft delete and revival: the slug comes back with the same id. */ async function deleteAndRevive(ingest, source) { const deleted = await ingest.sources.delete(source.id); console.log('deleted at:', deleted.deletedAt); const [revived] = await ingest.sources.upsert([{ slug: SOURCE, name: 'DNS zones', type: 'dns' }]); console.log('revived:', revived.deletedAt === null, 'same id:', revived.id === source.id); if (revived.id !== source.id) { throw new Error('expected the revived source to keep its id'); } } async function main() { const ingest = connect(); const source = await seed(ingest); // Two of three zones gone at once: 2/3 ≥ 0.5, so the guard would refuse. await cautiousSnapshot(ingest, source, ['example.com']); await cautiousSnapshot(ingest, source, ['example.com', 'example.net', 'example.org']); await snapshotWithATypo(ingest, source); await describeFailure(ingest); await ids(ingest, source); await deleteAndRevive(ingest, source); } main().catch((error) => { console.error(error); process.exit(1); });