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 (147 loc) • 6.49 kB
/** * 03-follow-up — operate a source: inspect, page through, fix a mapping, replay. * * SCENARIO: an operator script run after a sync. It reads what the source sent * and what became of it (the input log, page by page), previews and changes a * mapping, replays the stored inputs through the new mapping, then checks the * entities the source owns and whether anyone edited them behind its back. * Before that, it looks at where a mapping can write: the targets the platform * configured, and the types of one. * * Every list answers `{ paging: { limit, offset }, results }` and takes * `{ limit, offset }`. There is no total: keep reading while a page comes back * full. `allPages` below is that loop. * * Run it like 01-snapshot.cjs: NULLPLATFORM_API_KEY=… node examples/03-follow-up.cjs */ const { DriftPolicy, Engine, IngestClient, InputStatus, OnConflict, } = 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 }); } /** Read every page of a list: `readPage({ limit, offset })` returns a Page. */ async function allPages(readPage, limit = 100, offset = 0) { const page = await readPage({ limit, offset }); if (page.results.length < limit) { return page.results; } return page.results.concat(await allPages(readPage, limit, offset + limit)); } const SOURCE = 'billing-accounts'; /** Seed: a source with a few accounts, so there is something to look at. */ async function seed(ingest) { // 'billing' 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: 'billing', name: 'Billing system' }]); const [source] = await ingest.sources.upsert([ { slug: SOURCE, name: 'Billing accounts', type: 'billing' }, ]); const [mapping] = await ingest.mappings.upsertForSource(source.id, [ { recordType: 'account', engine: Engine.JSONATA, expression: '{ "id": id, "data": { "plan": plan } }', }, ]); await ingest.destinations.upsertForSource(source.id, [ { mappingId: mapping.id, target: 'catalog', endpoint: 'billing-account' }, ]); const run = await ingest.runs.open(source.id, { onConflict: OnConflict.ABORT }); ['acct-001', 'acct-002', 'acct-003', 'acct-004', 'acct-005'].forEach((id, index) => { run.add({ type: 'account', payload: { id, plan: index % 2 ? 'team' : 'enterprise' } }); }); await run.finalize(); return source; } async function main() { const ingest = connect(); // Where a mapping can write: the configured targets (named by slug), and a target's endpoints. const targets = await ingest.targets.list(); console.log( 'targets:', targets.results.map((target) => `${target.slug} (${target.name})`), ); const catalog = await ingest.targets.find('catalog'); const { results: accountEndpoints } = await ingest.endpoints.listForTarget(catalog.id, { slug: 'billing-account', }); console.log('billing-account is endpoint', accountEndpoints[0] && accountEndpoints[0].id); const source = await seed(ingest); // The input log, two at a time: what was sent, and what became of each input. const log = await allPages((page) => ingest.inputs.list(source.id, page), 2); console.log( 'inputs:', log.map((input) => `${input.type}:${input.status}`), ); const rejected = await ingest.inputs.list(source.id, { status: InputStatus.REJECTED }); console.log('rejected on the first page:', rejected.results.length); // Try a mapping change on a sample before storing it (a mapping is found by // its record type, changed by its id): a preview stores nothing. const mapping = await ingest.mappings.findForSource(source.id, 'account'); const change = { expression: '{ "id": id, "data": { "plan": plan, "tier": plan = "enterprise" ? 1 : 2 } }', }; const preview = await ingest.mappingPreviews.create({ mappingId: mapping.id, definition: { engine: mapping.engine, ...change }, sample: { payload: { id: 'acct-001', plan: 'enterprise' } }, }); console.log('preview:', preview.entities, preview.errors); // Store it, see the history, and replay the stored inputs through it. await ingest.mappings.update(mapping.id, change); const history = await ingest.mappings.revisions(mapping.id, { limit: 10 }); console.log( 'revisions:', history.results.map((revision) => revision.revision), ); // The API queues the replay in the background; it says how far it got. const started = await ingest.replays.create(source.id, { types: ['account'] }); const replay = await ingest.replays.wait(started.id, { intervalMs: 200, timeoutMs: 60_000 }); await ingest.inputs.waitIdle(source.id, { intervalMs: 200, timeoutMs: 60_000 }); // The replay's inputs carry its id, so what it did can be followed. const replayed = await ingest.inputs.list(source.id, { replayId: replay.id, limit: 100 }); console.log( 'replayed:', replay.progress.queued, replayed.results.map((input) => input.result?.outcome), ); // The source at a glance: backlog, last run, and the day's outcomes. const stats = await ingest.sources.stats(source.id); console.log('stats:', stats.pending, stats.settled.byOutcome); // What the source owns now, and whether the catalog still matches it. const owned = await allPages((page) => ingest.entities.list(source.id, { deleted: false, ...page }), ); console.log( 'owned entities:', owned.map((entity) => `${entity.target}/${entity.endpointId}/${entity.externalId}`), ); const check = await ingest.driftChecks.createAndWait(source.id, DriftPolicy.REPORT, { intervalMs: 200, }); console.log('drift:', check.status, check.counters); const drifted = await ingest.entities.list(source.id, { drifted: true, limit: 50 }); console.log('drifted entities:', drifted.results.length); const sources = await ingest.sources.list({ limit: 20 }); console.log( 'sources:', sources.results.map((each) => each.slug), sources.paging, ); } main().catch((error) => { console.error(error); process.exit(1); });