Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

16.7 KB
Raw Blame
/*
 * What one deploy reads out of the environment, in one place.
 *
 * mdeploy puts the stage's configuration into the environment before the stack
 * runs, and the stack turns some of it into each workload's own environment.
 * That turning is policy, not plumbing: which keys are required, which pair
 * with each other, which get composed into a single value the service's schema
 * accepts.
 *
 * Both engines call this — `sst.config.ts` on the AWS path and
 * `pulumi/program.ts` on the GCP one — and that is the whole point. Two copies
 * that drifted would deploy a control plane behaving differently on one cloud,
 * which is the kind of difference found months later, with a matching digest
 * and nothing reporting it. `test/stack-env.test.ts` asserts that only one copy
 * exists. The API's own environment is one layer further down, in
 * `src/api-environment.ts`, for the same reason.
 *
 * It takes an environment rather than reading `process.env`, because the Pulumi
 * program runs inside the driver's own process: reading the ambient environment
 * there would read whatever that shell happened to hold.
 */

import { renderRunnerEnvironment } from '../stack/runner-environment.ts'
import { apiEnvironmentFrom } from './api-environment.ts'
import { clickHouseRetentionHours } from '../stack/clickhouse-retention.ts'
import {
  OTEL_GROUP,
  PROXY_GROUP,
  RUNNER_GROUP,
  serviceSecretsFrom,
  splitServiceChannels,
  type GroupDeclaration,
} from './env.ts'
import type { RunnerSlot } from '../stack/runners.ts'
import type { UserDomain } from '../stack/hosts.ts'
import { runnerNameFor } from '../stack/runners.ts'
import type { Cloud } from 'mstage/config'
import { IMAGE_TAG } from 'mbuild/address'

export class StackEnvError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'StackEnvError'
  }
}

/** Configuration that must be supplied, with the reason it matters. */
const required = (environment: NodeJS.ProcessEnv, key: string, why: string): string => {
  const value = environment[key]?.trim()
  if (!value) throw new StackEnvError(`${key} is required — ${why}`)
  return value
}

const optional = (environment: NodeJS.ProcessEnv, key: string): string | null => environment[key]?.trim() || null

/**
 * The last two labels, which is the registrable domain under every suffix this
 * platform registers in (`.ai`, `.page`, `.site`, ...). A two-label public
 * suffix such as `co.uk` would compare stricter than browsers do; no stage uses
 * one, and refusing is the safe direction.
 */
const registrableDomainOf = (domain: string): string => domain.split('.').slice(-2).join('.')

/**
 * `STACK_USER_DOMAIN`: users' named apps are served at `<name>.<domain>`, or
 * nowhere when it is unset — there is no fallback under the stage's own domain.
 *
 * A separate registrable domain is the point. Under `STACK_DOMAIN` a user's page
 * is same-site with the dashboard, can set cookies the dashboard receives, and a
 * blocklist that flags one user's app takes the platform's domain with it. So a
 * value under the same registrable domain as `STACK_DOMAIN` or an overridden
 * `DASHBOARD_DOMAIN` is refused rather
 * than served — a sibling like `apps.boxlite.ai` beside `dev.boxlite.ai` too.
 * It is a different domain, so its records go into its own Cloudflare zone.
 */
export const userDomainFrom = (environment: NodeJS.ProcessEnv): UserDomain | null => {
  const domain = optional(environment, 'STACK_USER_DOMAIN')?.toLowerCase()
  if (!domain) return null
  for (const key of ['STACK_DOMAIN', 'DASHBOARD_DOMAIN']) {
    const platformDomain = optional(environment, key)?.toLowerCase()
    if (platformDomain && registrableDomainOf(domain) === registrableDomainOf(platformDomain)) {
      throw new StackEnvError(
        `STACK_USER_DOMAIN ${domain} shares ${registrableDomainOf(domain)} with ${key} ${platformDomain}; ` +
          "users' apps need a registrable domain of their own",
      )
    }
  }
  return {
    domain,
    dnsZoneId: required(
      environment,
      'CLOUDFLARE_USER_ZONE_ID',
      `the records for *.${domain} go into the zone that holds it`,
    ),
  }
}

/** At most this many hosts in one fleet, which is `runner/model/inventory.ts`'s own bound. */
const MAX_RUNNERS = 100

/** What the control plane accepts as a runner's registered name. */
const RUNNER_NAME = /^[a-zA-Z0-9_.-]{2,255}$/

/**
 * The fleet, as slots rather than as a count.
 *
 * The first host keeps the resource name `Runner` and the operator's chosen
 * control-plane name; every later one is numbered. Both facts are load-bearing
 * and neither is cosmetic: the resource name is what a targeted deploy selects
 * on and what an existing stage's state already calls its first host, so
 * renaming it would replace a machine rather than update one.
 */
export const runnerFleetFrom = ({
  environment,
  app,
  stage,
}: {
  environment: NodeJS.ProcessEnv
  app: string
  stage: string
}): RunnerSlot[] => {
  const raw = optional(environment, 'RUNNERS') ?? '1'
  if (!/^[1-9][0-9]*$/.test(raw) || Number(raw) > MAX_RUNNERS) {
    throw new StackEnvError(`RUNNERS must be a whole number from 1 to ${MAX_RUNNERS}; got ${JSON.stringify(raw)}`)
  }
  const defaultName = optional(environment, 'DEFAULT_RUNNER_NAME') ?? 'default'
  if (!RUNNER_NAME.test(defaultName)) {
    throw new StackEnvError(
      'DEFAULT_RUNNER_NAME must be 2-255 characters of letters, digits, underscores, periods and hyphens',
    )
  }
  return Array.from({ length: Number(raw) }, (_, offset) => {
    const index = offset + 1
    return index === 1
      ? { resourceName: 'Runner', nameTag: runnerNameFor({ app, stage, index }), controlPlaneRunnerName: defaultName }
      : {
          resourceName: `Runner-runner-${index}`,
          nameTag: runnerNameFor({ app, stage, index }),
          controlPlaneRunnerName: `runner-${index}`,
        }
  })
}

/**
 * A ClickHouse someone else operates, or nothing.
 *
 * All three or none. An endpoint with no credentials is a database this stage
 * cannot authenticate to, and credentials with no endpoint are a secret for
 * nothing — so a stage that supplied two of the three is a mistake worth naming
 * here rather than a `mode: managed` deploy that fails halfway.
 */
const managedClickHouseFrom = (
  environment: NodeJS.ProcessEnv,
): { url: string; writerSecretArn: string; readerSecretArn: string } | null => {
  const parts = {
    url: optional(environment, 'CLICKHOUSE_URL'),
    writerSecretArn: optional(environment, 'CLICKHOUSE_WRITER_PASSWORD_SECRET_ARN'),
    readerSecretArn: optional(environment, 'CLICKHOUSE_READER_PASSWORD_SECRET_ARN'),
  }
  const present = Object.entries(parts).filter(([, value]) => value !== null)
  if (present.length === 0) return null
  if (present.length !== 3) {
    throw new StackEnvError(
      'CLICKHOUSE_URL, CLICKHOUSE_WRITER_PASSWORD_SECRET_ARN and CLICKHOUSE_READER_PASSWORD_SECRET_ARN ' +
        `must be set together; this stage set only ${present.map(([key]) => key).join(', ')}`,
    )
  }
  return parts as { url: string; writerSecretArn: string; readerSecretArn: string }
}

/**
 * The identity let read this stage's ClickHouse reader password.
 *
 * A grant rather than a copy: the consumer reads the secret this stack owns, so
 * a rotation reaches it with nothing to synchronise and no second value to go
 * stale. One account, because the publication has one consumer — a second one
 * is a second grant, not a longer string.
 *
 * Optional: a stage that publishes nothing has nobody to name, and a stage on
 * AWS reaches its ClickHouse a different way entirely.
 */
const clickStackConsumerFrom = (environment: NodeJS.ProcessEnv): string | null => {
  const account = optional(environment, 'CLICKSTACK_CONSUMER_ACCOUNT')
  if (account === null) return null
  // Checked here rather than at the IAM call: a malformed member comes back
  // from Google as a policy error naming neither this key nor this stage.
  if (!/^[^@\s]+@[^@\s]+\.iam\.gserviceaccount\.com$/.test(account)) {
    throw new StackEnvError(`CLICKSTACK_CONSUMER_ACCOUNT must be a service account email, and is ${account}`)
  }
  return account
}

/** Everything one deploy decides, as opposed to what `mdeploy.config.json` declares. */
export type StackEnvironment = {
  /** The commit being deployed. Every container runs the same one. */
  tag: string
  /** The stage's own domain. `api.<domain>` is where the control plane answers. */
  domain: string
  /**
   * Where the dashboard is served, or null for the stage domain itself.
   *
   * The raw setting rather than the resolved host: `stack/api.ts`'s
   * `publicHostsFor` is the one place that turns the pair into two names, and
   * this carries it there rather than answering the question a second time.
   */
  dashboardDomain: string | null
  proxyDomain: string
  proxyProtocol: string
  /**
   * The origin the control plane hands a client composing a box URL.
   *
   * The API reads it as `proxy.templateUrl` and `ConfigurationDto` takes it
   * with `getOrThrow`, so a container without it answers `/api/config` with a
   * 500 — and the box proxy reads that route before it forwards a byte, so it
   * never finishes starting. Defaulted from the protocol and the zone, which is
   * the rule `deployment/environment.ts` already applies on the incumbent path.
   */
  proxyTemplateUrl: string
  /** The verified sender domain, or null for a stage that sends no mail. */
  senderDomain: string | null
  /** Where users' named apps are served, or null for a stage that offers none. See `userDomainFrom`. */
  userDomain: UserDomain | null
  runnerFleet: RunnerSlot[]
  /** A ClickHouse someone else operates, for a stage that runs none of its own. */
  managedClickHouse: { url: string; writerSecretArn: string; readerSecretArn: string } | null
  /** Hours the stage asked for, or null for none; the stack resolves the default once it knows the mode. */
  clickHouseRetentionHours: number | null
  /** Provision a dedicated account with a stage-owned credential. */
  otelOpenapiEnabled: boolean
  /**
   * The consumer of this stage's ClickStack publication, by service account, or
   * null for a stage that publishes to nobody.
   */
  clickStackConsumer: string | null
  /**
   * The DNS zone every public record is written into.
   *
   * Required on both clouds even though only one of them reads it here: SST's
   * Cloudflare adapter discovers the zone from the domain, and the Pulumi path
   * has no adapter to discover anything — so a GCP stage names it. Read for
   * both so a stage that moves clouds does not discover a missing key on the
   * far side of the move.
   */
  dnsZoneId: string
  /**
   * The SMTP relay a GCP stage sends through, or null.
   *
   * Google has no sending service, so a GCP stage that names a sender domain
   * has to name a relay as well. Null on AWS, where SES is the answer.
   */
  mailRelayHost: string | null
  apiEnvironment: Record<string, string>
  filestoreProjects: string[]
  /** Addresses rather than values, for the keys `env.selectGroup.secret` marks. */
  apiSecrets: Record<string, string>
  proxyEnvironment: Record<string, string>
  proxySecrets: Record<string, string>
  collectorEnvironment: Record<string, string>
  collectorSecrets: Record<string, string>
  runnerEnvironment: Record<string, string>
  runnerSecrets: Record<string, string>
}

/**
 * Each workload's two channels: values, and addresses.
 *
 * Split rather than merged because the two travel differently — a value reaches
 * the container as plain environment, an address as an ECS `secrets` entry or a
 * Cloud Run `secretKeyRef` — and which cloud renders it is why `home` is here.
 */
const channels = ({
  environment,
  declaration,
  region,
  stage,
  home,
}: {
  environment: NodeJS.ProcessEnv
  declaration: GroupDeclaration
  region: string
  stage: string
  home: Cloud
}) => {
  const api = apiEnvironmentFrom({ environment, declaration, region, stage, home })
  // Invocation metadata bypasses stored stage groups, like the image tag.
  const generationKey = environment.CI_SCHEDULER_GENERATION === undefined ? 'GITHUB_RUN_ID' : 'CI_SCHEDULER_GENERATION'
  const generation = environment[generationKey]
  if (generation !== undefined) {
    if (!/^[1-9][0-9]*$/.test(generation) || !Number.isSafeInteger(Number(generation)))
      throw new StackEnvError(`${generationKey} must be a canonical positive safe integer`)
    api.environment.CI_SCHEDULER_GENERATION = generation
  }
  const split = (group: string) =>
    splitServiceChannels({
      delivered: serviceSecretsFrom({ group, declaration, environment }),
      declaration,
      home,
    })
  const proxy = split(PROXY_GROUP)
  const collector = split(OTEL_GROUP)
  const runner = split(RUNNER_GROUP)
  renderRunnerEnvironment(runner.values.BOXLITE_RUNNER_ENV, [
    ...Object.keys(runner.values),
    ...Object.keys(runner.addresses),
    ...Object.keys(runner.addresses).map((name) => `${name}_ARN`),
  ])
  return {
    apiEnvironment: api.environment,
    filestoreProjects: api.filestoreProjects,
    apiSecrets: api.secrets,
    proxyEnvironment: proxy.values,
    proxySecrets: proxy.addresses,
    collectorEnvironment: collector.values,
    collectorSecrets: collector.addresses,
    runnerEnvironment: runner.values,
    runnerSecrets: runner.addresses,
  }
}

/**
 * One deploy's inputs, read and checked before anything is built.
 *
 * What is checked here is the shape of what arrived: every required key is
 * present, the tag is one full commit sha, and the fleet is a number this
 * repository will create. The failure then names the key rather than the
 * resource that choked on it.
 *
 * The runner binary is deliberately not among them. It is not configuration a
 * stage supplies — it is the checkout's own version, which
 * `stack/runner-binary.ts` resolves where the resources are built.
 */
export const readStackEnvironment = ({
  environment,
  declaration,
  app,
  stage,
  region,
  home,
}: {
  environment: NodeJS.ProcessEnv
  /** Where `env.selectGroup` is declared: which keys are each service's own. */
  declaration: GroupDeclaration
  /** The app segment every resource name carries. See `runnerNamePrefix`. */
  app: string
  stage: string
  region: string
  /** Which cloud's secret store an address in `env.selectGroup.secret` names. */
  home: Cloud
}): StackEnvironment => {
  const tag = required(environment, 'BOXLITE_IMAGE_TAG', 'a deploy names the exact commit it ships')
  // mbuild's constant, not a copy of it. The copy that used to live here was
  // the same rule written twice, and the two would have disagreed the moment
  // mbuild learned to tag a release build.
  if (!IMAGE_TAG.test(tag)) {
    throw new StackEnvError('BOXLITE_IMAGE_TAG must be one full lowercase commit SHA, optionally prefixed "v<X.Y.Z>-"')
  }
  const proxyDomain = required(environment, 'PROXY_DOMAIN', 'every box is a name under this zone')
  // A default rather than a requirement: the proxy speaks to a box inside the
  // network, and `http` there is the shape every stage has used. What must
  // never be defaulted is the zone above, which is public.
  const proxyProtocol = optional(environment, 'PROXY_PROTOCOL') ?? 'http'
  const openapi = optional(environment, 'OTEL_OPENAPI_ENABLED')
  if (openapi !== null && !['true', 'false'].includes(openapi)) {
    throw new StackEnvError('OTEL_OPENAPI_ENABLED must be true or false')
  }
  return {
    tag,
    domain: required(environment, 'STACK_DOMAIN', "the stage's own domain; the control plane answers at api.<domain>"),
    // Absent is the common stage, which serves its dashboard at the domain
    // above. Named only by a stage that publishes it somewhere else — prod,
    // whose apex belongs to the marketing site.
    dashboardDomain: optional(environment, 'DASHBOARD_DOMAIN'),
    proxyDomain,
    proxyProtocol,
    // Composed from the two above when the store says nothing, which is the
    // same rule the incumbent path applies. See the field's own note.
    proxyTemplateUrl: optional(environment, 'PROXY_TEMPLATE_URL') ?? `${proxyProtocol}://${proxyDomain}`,
    // Absent is a stage that sends no mail, which is a supported state — see
    // `stack/mail.ts`. An empty string is the same answer, spelled by a store
    // that holds the key with nothing in it.
    senderDomain: optional(environment, 'MAIL_DOMAIN'),
    userDomain: userDomainFrom(environment),
    runnerFleet: runnerFleetFrom({ environment, app, stage }),
    managedClickHouse: managedClickHouseFrom(environment),
    clickHouseRetentionHours:
      optional(environment, 'CLICKHOUSE_RETENTION_HOURS') === null ? null : clickHouseRetentionHours(environment),
    otelOpenapiEnabled: openapi === 'true',
    clickStackConsumer: clickStackConsumerFrom(environment),
    dnsZoneId: required(environment, 'CLOUDFLARE_ZONE_ID', 'every public record this stage writes goes into it'),
    mailRelayHost: optional(environment, 'MAIL_RELAY_HOST'),
    ...channels({ environment, declaration, region, stage, home }),
  }
}