// OBSERVE — the kernel's fold for the second difference between simulated and real: how the tree // is kept current (docs/concepts/the-model.md). // // A pack's refresh and ingest code hand the kernel RESOURCES, never rows. The kernel diffs each // against the upstream view and appends to the ROOT's log (the parent log — the vendor's history as // observed) only what changed: one entry per changed subject, carrying the changed fields; an // unchanged resource appends nothing; a listing the adapter declares complete tombstones what it // no longer holds. A refresh runs inside a scope that collects the adapter's observations and folds // them as one batch; an ingest observes directly, one resource at a time. import { withHistoryLock } from './ancestry.ts'; import { AsyncLocalStorage } from 'node:async_hooks'; import { appendParentEntry, readParentTreeMap, type Entry, type Tree } from './log.ts'; import { hashFieldValue, type SubjectFields } from './hash.ts'; import { worldNow } from './world-clock.ts'; import { worldPaths } from './storage.ts'; /** `adopts`: the local id of a subject a deploy settled with no vendor id, which this observation is (refresh's * adoption, architecture "Refresh"): the observation lands as that subject's alias, and the local one stands. */ export type ObservedResource = { type: string; id: string; fields: SubjectFields; deleted?: boolean; adopts?: string }; export type ObserveReport = { observed: number; appended: number; unchanged: number; removed: number }; export type Observation = { service: string; root?: string } & ( | { resource: ObservedResource } | { resources: ObservedResource[]; complete?: Completed[] } ); // ONE sink per process, whichever copy of the kernel a pack resolved: a pack installed beside a // world carries its own `@volter/world-core`, and its observations must reach the scope the runtime // opened. A module-level instance would be one per copy; a process-global symbol is one per process. const SINK = Symbol.for('volter.observe.sink'); // created on first use, never at import: a browser bundle carrying the kernel carries this module // through the pack's shared helpers, and a browser has no AsyncLocalStorage — constructing one at load // would kill the whole client ("not a constructor") for a scope the browser never opens const sink = (): AsyncLocalStorage => ((globalThis as Record)[SINK] ??= new AsyncLocalStorage()) as AsyncLocalStorage; /** Run `fn` with every `observeResource` inside it COLLECTED instead of folded; the caller folds the * batch (`observeResources`) once `fn` returns. The kernel's refresh does this around an adapter. */ export async function collectObservations(fn: () => Promise): Promise<{ value: T; observations: Observation[] }> { const observations: Observation[] = []; const value = await sink().run(observations, fn); return { value, observations }; } /** A type a batch listed in full: all of it, or (a type under a parent) the subjects whose `field` names one of the * parents listed `within`. */ export type Completed = string | { type: string; field: string; within: string[] } | { type: string; ids: string[] }; /** Fold a collected batch: one `observeResources` per service, `complete` applied to each. */ export function foldObservations(observations: Observation[], opts: { root?: string; at?: string; complete?: Completed[]; batch?: string } = {}): ObserveReport { const total: ObserveReport = { observed: 0, appended: 0, unchanged: 0, removed: 0 }; const groups = new Map }>(); for (const o of observations) { const root = opts.root ?? o.root; const key = JSON.stringify([o.service, root]); let group = groups.get(key); if (!group) { group = { service: o.service, root, resources: [], complete: new Set(opts.complete) }; groups.set(key, group); } if ('resource' in o) group.resources.push(o.resource); else for (const resource of o.resources) group.resources.push(resource); if ('resources' in o) for (const type of o.complete ?? []) group.complete.add(type); } for (const { service, root, resources, complete } of groups.values()) { const r = foldResources(service, resources, { ...opts, root, complete: [...complete] }); total.observed += r.observed; total.appended += r.appended; total.unchanged += r.unchanged; total.removed += r.removed; } return total; } /** One observed resource: collected when a refresh scope is open, else folded onto the root's log now. */ export function observeResource(service: string, resource: ObservedResource, opts: { root?: string; at?: string } = {}): ObserveReport { const collecting = typeof AsyncLocalStorage === 'function' ? sink().getStore() : undefined; if (collecting) { collecting.push({ service, resource, ...(opts.root !== undefined ? { root: opts.root } : {}) }); return { observed: 1, appended: 0, unchanged: 0, removed: 0 }; } return observeResources(service, [resource], opts); } function stable(value: unknown): string { if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined'; if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`; const o = value as Record; return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${stable(o[k])}`).join(',')}}`; } /** The fold: diff each resource against upstream state, append what changed to the root's log. `complete` * names the types this batch listed in full (or in full under the parents it names) — a subject of such a type the * batch does not hold is tombstoned. Entry ids are content-addressed, so the same observation folds once. */ export function observeResources(service: string, resources: ObservedResource[], opts: { root?: string; at?: string; complete?: Completed[]; batch?: string } = {}): ObserveReport { const collecting = typeof AsyncLocalStorage === 'function' ? sink().getStore() : undefined; if (collecting) { collecting.push({ service, resources, ...(opts.root !== undefined ? { root: opts.root } : {}), ...(opts.complete ? { complete: opts.complete } : {}) }); return { observed: resources.length, appended: 0, unchanged: 0, removed: 0 }; } return foldResources(service, resources, opts); } function foldResources(service: string, resources: ObservedResource[], opts: { root?: string; at?: string; complete?: Completed[]; batch?: string }): ObserveReport { return withHistoryLock(worldPaths(service, opts.root).dir, () => { const at = opts.at ?? worldNow(); // one look is one batch: every entry it appends carries the same id, and no position may split it const batch = opts.batch ?? `obs:${service}:${at}`; const tree: Tree = readParentTreeMap(service, opts.root); const report: ObserveReport = { observed: resources.length, appended: 0, unchanged: 0, removed: 0 }; const seen = new Set(); const append = (subject: { type: string; id: string }, fields: SubjectFields, aliasOf?: string): boolean => { const entry: Entry = { id: `observed:${service}:${subject.type}:${subject.id}:${hashFieldValue({ subject, fields, at, ...(aliasOf ? { aliasOf } : {}) })}`, service, op: 'set', operation: 'observed', subject, occurredAt: at, actor: { kind: 'system', id: 'vendor' }, fields, batch, ...(aliasOf ? { aliasOf } : {}), }; const { appended } = appendParentEntry(entry, opts.root); const key = `${subject.type}:${subject.id}`; const existing = tree.get(key) ?? { type: subject.type, id: subject.id, updatedAt: at, fields: {} }; const merged: SubjectFields = { ...existing.fields, ...fields }; if (existing.fields.deleted === true && fields.deleted !== true) delete merged.deleted; tree.set(key, { ...existing, updatedAt: at, fields: merged }); return appended; }; for (const r of resources) { const key = `${r.type}:${r.id}`; seen.add(key); // an adoption: the vendor's subject is the local one a deploy made with no id, aliased to it if (r.adopts !== undefined && !tree.has(key)) { seen.add(`${r.type}:${r.adopts}`); if (append({ type: r.type, id: r.id }, r.fields, r.adopts)) report.appended += 1; else report.unchanged += 1; continue; } const existing = tree.get(key); if (r.deleted) { if (existing && existing.fields.deleted !== true) { if (append({ type: r.type, id: r.id }, { deleted: true })) report.removed += 1; } else report.unchanged += 1; continue; } const changed: SubjectFields = {}; for (const [k, v] of Object.entries(r.fields)) if (v !== undefined && (existing === undefined || stable(existing.fields[k]) !== stable(v))) changed[k] = v; if (Object.keys(changed).length === 0 && existing !== undefined && existing.fields.deleted !== true) { report.unchanged += 1; continue; } if (existing?.fields.deleted === true && Object.keys(changed).length === 0) Object.assign(changed, r.fields); // resurrected as it stands if (append({ type: r.type, id: r.id }, changed)) report.appended += 1; else report.unchanged += 1; } for (const c of opts.complete ?? []) { const type = typeof c === 'string' ? c : c.type; const within = typeof c === 'string' || !('within' in c) ? undefined : new Set(c.within); // subjects read one by one (a refresh of the known): only those read are whole, an unseen one is gone const ids = typeof c !== 'string' && 'ids' in c ? new Set(c.ids) : undefined; for (const s of tree.values()) { if (s.type !== type || seen.has(`${s.type}:${s.id}`) || s.fields.deleted === true) continue; if (within && typeof c !== 'string' && 'field' in c && !within.has(String(s.fields[c.field]))) continue; if (ids && !ids.has(s.id)) continue; if (append({ type: s.type, id: s.id }, { deleted: true })) report.removed += 1; } } return report; }, { operation: 'observation batch' }); }