@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
165 lines (145 loc) • 8.35 kB
Markdown
---
name: nullplatform-ingest
description: Writes and reviews code that uses @nullplatform/ingest, the client SDK of the nullplatform ingest API, to feed nullplatform (the catalog, core entities) from a system of record. Use when building or changing a collector, sync job, inventory script or webhook handler that calls IngestClient, sources.upsert, runs.open, events.batcher, mappings, destinations or source types, or when the user mentions catalog ingestion, snapshots, backfills, resyncs or delta events.
license: MIT
metadata:
package: '@nullplatform/ingest'
---
# Using @nullplatform/ingest
The SDK talks to the nullplatform ingest API. A collector names its **source**
(one system: a cluster, an org), backfills it with a **run** (the complete
state, reconciled: what it no longer reports is deleted), then sends every
change as an **event**. Mappings in the API turn its records into entities;
destinations say which target and endpoint they are written to.
**Before writing code, read the full reference:**
`node_modules/@nullplatform/ingest/llms.txt` (every export and signature, and
the removed calls you must not generate). This file is the short version.
## Rules that prevent the common mistakes
1. **camelCase fields, enum vocabularies.** Write and read camelCase
(`recordType`, `observedAt`, `sourceId`, `runs.maxDeleteRatio`): the SDK
renames them to the API's snake_case. What you own (`payload`,
`attributes`, mapped `data`) is sent as it is. Use the exported enums, never
their strings: `Engine.JSONATA`, `OnConflict.ABORT`, `RunStatus.COMPLETED`.
Never write `kind`.
2. **Ids are the API's, slugs are yours.** Name a source by `slug`; keep the
`Source` that `sources.upsert` returns and pass `source.id` everywhere.
3. **Input ids are UUIDv7.** Omit `id` (the SDK generates one) or pass
`uuidv7()`. Never a UUIDv4, a hash or a business key.
4. **A run is ONE complete listing** of its types: open, `add` everything,
`finalize`. What you did not add is deleted (behind guards). Never use a run
for a partial update: send events.
5. **Events never delete by omission.** Only `events.delete(...)` deletes.
6. **`observedAt` is when the state was observed**, one value per listing,
never the send time.
7. **On any failure in a run, `await run.abort()`** (it deletes nothing) and
rethrow. A failed batch is sticky: never catch and keep adding.
8. **Lists answer `Page<Item>`** (`{ paging, results }`), never an array, never a
total: walk pages while `results.length === limit`.
9. **The SDK reads no environment variables.** Read `process.env` yourself and
pass the values to `new IngestClient({...})`. One client per process.
10. **A collector of a global source type defines no mappings.** For
`kubernetes`, nullplatform ships the mappings and the organization binds
them to destinations once. Only a collector of the organization's own type
upserts mappings for its source (`mappings.upsertForSource`, then
`destinations.upsertForSource`).
11. **A mapping or destination belongs to a source type or to one source**:
create and list it under its owner (`createForSourceType` / `createForSource`,
`listForSourceType` / `listForSource`); read, change and delete it by its id. A
source's destination list is what it applies (`{ effective: false }`: its
own only).
12. **Setup code runs on every start, through the upserts**, one contract for
all: `sources.upsert`, `sourceTypes.upsert`, `mappings.upsertForSourceType` /
`upsertForSource`, `destinations.upsertForSourceType` / `upsertForSource`. Each
takes an ARRAY of specs in the create format, finds each by its natural
key (slug; a destination by `mappingId` + its target and endpoint, by slug or by id), creates
what is missing, patches only what differs, never deletes, and answers the
resources in the specs' order, each with what it did (`upserted`:
`UpsertOutcome.CREATED`, `UPDATED` or `UNCHANGED`). Never `list` then
`create` by hand. A
collector sends only what it owns: what it sends is set on every start.
13. **Every call reaches the public API; the key's grants decide.** A
collector's key (`organization:machine:ingest`, at its source's NRN) runs a
collector; an organization's setup (source types, a type's destinations)
needs `organization:ingest_admin` at the organization's root. A 403 is a
missing grant, never a wrong URL.
14. **A slug names one mapping of a type** across nullplatform's and the
organization's. To customize nullplatform's, upsert your own under another
slug and bind it; `upsertForSourceType` on nullplatform's slug with a different
definition is a 403.
## Shape of a collector
```js
const { IngestClient, OnConflict, RunStatus } = require('@nullplatform/ingest');
// The public API is the default: an API key is all there is to configure.
const ingest = new IngestClient({
apiKey: process.env.NULLPLATFORM_API_KEY ?? process.env.NP_API_KEY,
});
const [source] = await ingest.sources.upsert([
{ slug: 'prod-eu', name: 'Production EU', type: 'kubernetes' },
]);
// Backfill or resync: the complete state.
const run = await ingest.runs.open(source.id, {
types: ['deployment'],
onConflict: OnConflict.ABORT,
});
const observedAt = new Date().toISOString();
try {
(await listDeployments()).forEach((item) =>
run.add({ type: 'deployment', observedAt, payload: item }),
);
const done = await run.finalize();
if (done.status === RunStatus.GUARD_TRIPPED) {
console.warn('a guard refused to delete', done.reconciliation.guardReason);
}
} catch (error) {
await run.abort();
throw error;
}
// Steady state: each change as an event.
const events = ingest.events.batcher(source.id);
events.upsert('deployment', changed, { observedAt: change.time });
events.delete('deployment', removed, { observedAt: change.time });
await events.close(); // on shutdown
```
Or let the SDK drive the runs: describe the collector and hand it to
`runCollector` (a long-running worker) or `runSnapshot` (one snapshot). They
upsert the source and the collector's own mappings before every snapshot,
send only the types the source applies, abort the run on any failure so
nothing is deleted, and restart the watch with a backoff. `runCollector`'s
first snapshot is due by the source's last run, so a restart does not
backfill again before `intervalSeconds` since it. Prefer them to a
hand-rolled loop.
```js
const { ClientIngest, IngestClient, runCollector } = require('@nullplatform/ingest');
await runCollector(
{
source: { type: 'kubernetes', name: 'Production EU' },
recordTypes: ['deployment'],
async *snapshot() {
yield* (await listDeployments()).map((payload) => ({ type: 'deployment', payload }));
},
},
new ClientIngest(new IngestClient({ apiKey: process.env.NP_API_KEY })),
{ source: { slug: 'prod-eu' }, log: console, signal, intervalSeconds: 3600 },
);
```
## Errors
Catch `IngestError` and branch on `error.code` (`IngestErrorCode`), never on
the message. The SDK retries 5xx and network errors for GET, PATCH and DELETE
and for the POSTs a resend cannot repeat (`inputs.create`, the run handles and
event batchers that send through it, `mappingPreviews.create`,
`replays.create` with an `idempotencyKey`); any other POST is sent once, and
the upserts read again and continue when a create answers 409. A failed token
exchange is retried like a request and surfaces as an `IngestError`. It
refreshes the token once on a 401 (never for a `token`: that 401 surfaces)
and waits out a 429. Any other 4xx is a bug in the call (a 400 names the
field); `IngestErrorCode.TARGET_REJECTED` (502) is a target refusing what the
API asked it on the call's behalf.
Every `get` answers `null` when there is none (`sources.get`, `runs.get`,
`inputs.get`, `entities.get`, `endpoints.get`…); the wait helpers throw an
`IngestError` 404 for a resource that does not exist.
## When reviewing code that uses the SDK
Check the rules above first: a run fed a partial listing, a caught batch error
that keeps adding, `observedAt` set at send time, snake_case fields, strings
where an enum belongs, non-UUIDv7 input ids, environment reads expected from
the SDK, a `baseURL` set to the public API (it is the default), and a
Kubernetes collector defining its own mappings.