@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
217 lines (202 loc) • 8.2 kB
JavaScript
/**
* 05-kubernetes — everything a Kubernetes collector says to the ingest API, in order.
*
* SCENARIO: a cluster's most important objects (a Namespace, a Deployment and
* the Service in front of it) reach the catalog, then change. Each numbered
* step is one SDK call, and the comment names the request it makes:
*
* The organization, once (an administrator, not every collector; re-running changes nothing):
* 1. the `kubernetes` source type GET /source_types?slug=kubernetes
* 2. its mappings, shipped by nullplatform GET /source_types/{id}/mappings
* 3. bind them, for every cluster GET /source_types/{id}/destinations,
* POST /source_types/{id}/destinations (what is missing)
* The collector, on every start:
* 4. its source (upserted) GET /sources?slug=… (POST /sources, PATCH /sources/{id})
* 5. what its source applies GET /sources/{id}/destinations
* The backfill (and every resync):
* 6. a run of the complete listing POST /sources/{id}/runs, POST /sources/{id}/inputs,
* PATCH /runs/{id}, GET /runs/{id}
* The steady state:
* 7. each change as an event POST /sources/{id}/inputs
* 8. what became of the events GET /inputs/{id}
* 9. what the source owns now GET /sources/{id}/entities
*
* The manifests are what the Kubernetes API returns (managedFields left out),
* plus `_refs`: what an object names by name (its namespace, the pods a
* service selects), resolved to uids by the collector, which the mappings read.
*
* Run it against the public API with your nullplatform API key:
*
* NULLPLATFORM_API_KEY=… node examples/05-kubernetes.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 });
}
// ── the cluster's objects, as the Kubernetes API answers them ─────────────────
const NAMESPACE_UID = '6f1c2a54-0d1e-4b55-9e3a-2b7f8c1d4e01';
const namespace = {
apiVersion: 'v1',
kind: 'Namespace',
metadata: {
name: 'shop',
uid: NAMESPACE_UID,
creationTimestamp: '2026-10-01T12:00:00Z',
labels: { 'kubernetes.io/metadata.name': 'shop', team: 'commerce' },
},
spec: { finalizers: ['kubernetes'] },
status: { phase: 'Active' },
};
const deployment = {
apiVersion: 'apps/v1',
kind: 'Deployment',
metadata: {
name: 'checkout',
namespace: 'shop',
uid: '0b5e6a2f-3c7d-4e8f-9a1b-2c3d4e5f6a02',
generation: 3,
creationTimestamp: '2026-10-01T12:05:00Z',
labels: { app: 'checkout', team: 'commerce' },
annotations: { 'deployment.kubernetes.io/revision': '3' },
},
spec: {
replicas: 3,
selector: { matchLabels: { app: 'checkout' } },
strategy: { type: 'RollingUpdate' },
template: {
metadata: { labels: { app: 'checkout' } },
spec: {
serviceAccountName: 'checkout',
containers: [
{
name: 'checkout',
image: 'registry.example.com/shop/checkout:1.4.0',
ports: [{ containerPort: 8080, protocol: 'TCP' }],
},
],
},
},
},
status: {
observedGeneration: 3,
replicas: 3,
readyReplicas: 3,
availableReplicas: 3,
updatedReplicas: 3,
conditions: [{ type: 'Available', status: 'True' }],
},
_refs: { namespace: NAMESPACE_UID },
};
const service = {
apiVersion: 'v1',
kind: 'Service',
metadata: {
name: 'checkout',
namespace: 'shop',
uid: '9c8d7e6f-5a4b-4c3d-8e2f-1a0b9c8d7e03',
creationTimestamp: '2026-10-01T12:05:10Z',
labels: { app: 'checkout' },
},
spec: {
type: 'ClusterIP',
clusterIP: '10.43.12.7',
selector: { app: 'checkout' },
sessionAffinity: 'None',
ports: [{ name: 'http', port: 80, targetPort: 8080, protocol: 'TCP' }],
},
status: { loadBalancer: {} },
// The pods its selector selects, resolved by the collector (none listed here).
_refs: { namespace: NAMESPACE_UID, pods: [] },
};
const SOURCE = 'prod-eu';
/** What this example sends: each record type and the catalog endpoint (a specification) it goes to. */
const KINDS = ['namespace', 'deployment', 'service'];
/** Steps 1–3: the organization binds the type's mappings once, for every cluster. */
async function bindOnce(ingest) {
const type = await ingest.sourceTypes.find('kubernetes'); // 1
const mappings = (await ingest.mappings.listForSourceType(type.id, { limit: 100 })).results; // 2
// 3: an upsert: what is bound already is left as it is, the rest is created in one batch.
const bound = await ingest.destinations.upsertForSourceType(
type.id,
KINDS.map((kind) => ({
mappingId: mappings.find((mapping) => mapping.recordType === kind).id,
target: 'catalog', // a record type goes to the catalog's specification of its kind
endpoint: `k8s-${kind}`,
})),
);
console.log(
`1-3 the kubernetes type binds ${bound.map((destination) => destination.recordType).join(', ')}`,
);
}
async function main() {
const ingest = connect();
await bindOnce(ingest);
// 4: the collector's source, by slug: created, or brought to these settings (nothing sent when equal).
const [source] = await ingest.sources.upsert([
{
slug: SOURCE,
name: 'Production cluster (eu)',
type: 'kubernetes',
attributes: { env: 'prod', region: 'eu-west-1' }, // read by mappings as $source.attributes
},
]);
console.log(`4 source ${source.slug}: ${source.id}`);
// 5: what its source applies: the record types worth sending.
const applied = (await ingest.destinations.listForSource(source.id, { limit: 100 })).results;
const types = KINDS.filter((kind) =>
applied.some((destination) => destination.recordType === kind),
);
console.log(`5 applied: ${types.join(', ')}`);
// 6: the backfill: one run of the complete listing, one observation time for all of it.
const run = await ingest.runs.open(source.id, { types, onConflict: OnConflict.ABORT });
const listedAt = new Date().toISOString();
[namespace, deployment, service].forEach((object) =>
run.add({ type: object.kind.toLowerCase(), observedAt: listedAt, payload: object }),
);
let done;
try {
done = await run.finalize();
} catch (error) {
await run.abort(); // a run that cannot finish deletes nothing
throw error;
}
console.log(`6 run ${done.status}:`, done.counters);
if (done.status !== RunStatus.COMPLETED) {
throw new Error(`the backfill did not complete: ${done.status}`);
}
// 7: the steady state: the deployment scales out, the service is removed.
const events = ingest.events.batcher(source.id);
const changedAt = new Date().toISOString();
const scaled = {
...deployment,
metadata: { ...deployment.metadata, generation: 4 },
spec: { ...deployment.spec, replicas: 5 },
status: { ...deployment.status, observedGeneration: 4, replicas: 5, readyReplicas: 5 },
};
const ids = [
events.upsert('deployment', scaled, { observedAt: changedAt }),
events.delete('service', service, { observedAt: changedAt }),
];
await events.close();
// 8: what became of each event.
const settled = await ingest.inputs.wait(ids);
settled.forEach((input) => console.log(`8 ${input.type} ${input.op}: ${input.status}`));
// 9: what the source owns now: the namespace and the scaled deployment.
const owned = (await ingest.entities.list(source.id)).results.filter(
(entity) => !entity.deletedAt,
);
console.log(
`9 owned: ${owned.map((entity) => `${entity.endpoint}/${entity.externalId}`).join(', ')}`,
);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});