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

178 lines (167 loc) • 6.32 kB
/** * 01-snapshot — report the full state of a system as one snapshot run. * * SCENARIO: a cluster inventory job. Each pass lists the deployments of a * cluster and reports them as ONE run: open it, `add()` every deployment as it * is enumerated, `finalize()`. On finalize the API soft-deletes the catalog * entities this source reported before but not this time — unless a guard * trips (an empty run, or too large a share of deletions). * * The cluster API is stubbed: two passes, the second one missing a deployment * that was removed in between, so the second finalize deletes exactly that one. * * Run it against the public API with your nullplatform API key: * * NULLPLATFORM_API_KEY=… node examples/01-snapshot.cjs */ const { IngestClient, OnConflict, RunStatus } = 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 }); } /** A Deployment as the Kubernetes API answers it (trimmed): the shipped mapping reads this shape. */ function deployment({ namespace, name, uid, replicas, image }) { return { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { namespace, name, uid }, spec: { replicas, selector: { matchLabels: { app: name } }, template: { spec: { containers: [{ name, image }] } }, }, }; } // ── stubbed cluster API: what the collector already talks to ─────────────────── const cluster = { passes: [ [ deployment({ namespace: 'shop', name: 'checkout', uid: '0b5e6a2f-3c7d-4e8f-9a1b-2c3d4e5f6a01', replicas: 3, image: 'registry.example.com/checkout:1.4.0', }), deployment({ namespace: 'shop', name: 'payments', uid: '0b5e6a2f-3c7d-4e8f-9a1b-2c3d4e5f6a02', replicas: 2, image: 'registry.example.com/payments:2.0.1', }), deployment({ namespace: 'shop', name: 'catalog', uid: '0b5e6a2f-3c7d-4e8f-9a1b-2c3d4e5f6a03', replicas: 2, image: 'registry.example.com/catalog:0.9.3', }), ], [ // `payments` was removed from the cluster; `checkout` was scaled up. deployment({ namespace: 'shop', name: 'checkout', uid: '0b5e6a2f-3c7d-4e8f-9a1b-2c3d4e5f6a01', replicas: 5, image: 'registry.example.com/checkout:1.4.0', }), deployment({ namespace: 'shop', name: 'catalog', uid: '0b5e6a2f-3c7d-4e8f-9a1b-2c3d4e5f6a03', replicas: 2, image: 'registry.example.com/catalog:0.9.3', }), ], ], async listDeployments(pass) { return this.passes[pass]; }, }; const SOURCE = 'cluster-prod-eu'; /** * The organization's setup, done once (by its administrators, not by every * collector): `kubernetes` is nullplatform's global source type, so its * collectors define no mappings. The organization binds the type's mapping of * deployments, the one nullplatform ships, to a destination once, for every * source of the type. It keys each entity by the object's uid, so two clusters * never claim one. */ async function bindOnce(ingest) { const type = await ingest.sourceTypes.find('kubernetes'); const [mapping] = (await ingest.mappings.listForSourceType(type.id, { recordType: 'deployment' })) .results; // An upsert: run it again and nothing changes. await ingest.destinations.upsertForSourceType(type.id, [ { mappingId: mapping.id, target: 'catalog', endpoint: 'k8s-deployment' }, ]); } /** * The collector declares its source, found by its slug (the API gave it its * id, which later calls take), and nothing else: what its records become is * the organization's destinations of its type. */ async function register(ingest) { const [source] = await ingest.sources.upsert([ { slug: SOURCE, name: 'Production cluster (eu)', type: 'kubernetes', // Refuse a finalize that would delete half or more of what this source owns. runs: { maxDeleteRatio: 0.5 }, }, ]); return source; } /** One inventory pass: the whole current state, as one run. */ async function reportSnapshot(ingest, source, pass) { // A run left open by a crashed pass is aborted, and a fresh one opened. const run = await ingest.runs.open(source.id, { types: ['deployment'], onConflict: OnConflict.ABORT, }); // One observation time for the whole listing: the state "as of" the list call. const listedAt = new Date().toISOString(); const deployments = await cluster.listDeployments(pass); deployments.forEach((object) => { // Batched by count and bytes behind the scenes; every record gets a UUIDv7 id. run.add({ type: 'deployment', observedAt: listedAt, payload: object }); }); try { // Flush, finalize, and wait until the API has applied and reconciled the run. return await run.finalize(); } catch (error) { // A run that cannot be finalized must not linger: close it without deleting. await run.abort(); throw error; } } async function main() { const ingest = connect(); await bindOnce(ingest); const source = await register(ingest); const first = await reportSnapshot(ingest, source, 0); console.log('pass 1:', first.status, first.counters, first.reconciliation); const second = await reportSnapshot(ingest, source, 1); // status: RunStatus.COMPLETED (or RunStatus.GUARD_TRIPPED when a guard refused to delete). // reconciliation: { seen, stale, deleted, guardTripped, guardReason, dryRun } console.log('pass 2:', second.status, second.counters, second.reconciliation); if (second.status !== RunStatus.COMPLETED) { throw new Error(`a guard refused to delete: ${second.reconciliation.guardReason}`); } if (second.reconciliation.deleted !== 1) { throw new Error('expected the removed deployment to be deleted'); } } main().catch((error) => { console.error(error); process.exit(1); });