iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / mind-worker / src / config-record.tsmain at 949894f

// config-record.ts — THE MIND'S CONFIG ON ITS OWN LOG. When an isolate of the mind Worker starts,
// it compares its config with the one this Worker last recorded, whose hash is in KV. If they
// differ, it appends `mind/configured` on `/` and keeps the new hash. So the log says what the
// mind was deployed with, each time that changed: its repos and entry, and the kernel's commit.
// A deploy that changes nothing appends nothing.
import { sha256Hex } from "core-itx";
import { mindWorkerConfigOf } from "./config.ts";
import type { Env } from "./env.ts";
import { appendAsPlatform } from "./platform-append.ts";

const LAST_RECORDED = "mind/configured:last-recorded-hash";

let recorded: Promise<void> | undefined;

/** Resolves when this isolate has compared its config with the last one recorded, and recorded
 *  it where they differed. One comparison for the isolate; one that failed is made again at the
 *  next call. Never rejects. */
export function configRecorded(env: Env): Promise<void> {
  recorded ||= record(env).catch((error) => {
    recorded = undefined;
    console.info({
      event: "mind.config-not-recorded",
      namespace: "mind",
      message: "the mind Worker's config was not compared with the one last recorded on the mind's log",
      error: error instanceof Error ? error.message : String(error),
    });
  });
  return recorded;
}

async function record(env: Env): Promise<void> {
  // through JSON, so each secret of the config is the string "REDACTED" (iterate/app-config)
  const config: Record<string, unknown> = JSON.parse(JSON.stringify(mindWorkerConfigOf(env)));
  const hash = await sha256Hex(JSON.stringify(config));
  if ((await env.MIND_KV.get(LAST_RECORDED)) === hash) return;
  // The key names the config and the Worker's version: two isolates of one deploy land one
  // event, and a config that comes back to an earlier value is a new event, since its deploy is
  // a new version.
  await appendAsPlatform("/", [
    {
      type: "events.iterate.com/mind/configured",
      idempotencyKey: `mind/configured:${hash}:${env.CF_VERSION_METADATA.id}`,
      payload: config,
    },
  ]);
  await env.MIND_KV.put(LAST_RECORDED, hash);
}