The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/*
* The whole stack, assembled once.
*
* Every module above this file describes one thing and knows nothing about the
* others; this is the only place that knows the order they go in and what each
* one is handed. That order is not a style choice — it is the dependency graph,
* and writing it down once is what keeps eleven modules from each having an
* opinion about it:
*
* images ──→ api, proxy, collector, registry proxy (addresses for one commit)
* network ──→ cluster ──→ hosts
* ├──→ database ─┐
* ├──→ cache ────┼──→ api
* └──→ clickhouse ┴──→ collector ──→ api, proxy, registry proxy, runners
* storage ────────────────────────────────→ api
* mail ───────────────────────────────────→ api
* api ──→ proxy, registry proxy, runners ──→ alarms
*
* The providers arrive as one bundle rather than being imported here, so this
* file names no cloud. That is what makes it testable without one: a bundle of
* recording fakes drives the same wiring the real bundle does.
*/
import type { Api, ApiCapability, ApiDependencies, ApiProvider } from './api.ts'
import { API_PORT, publicHostsFor } from './api.ts'
import type { AlarmProvider, AlarmSubjects } from './alarms.ts'
import type { Cache, CacheProvider } from './cache.ts'
import { CACHE_PASSWORD_VARIABLE, cacheEnvironment } from './cache.ts'
import type { ClickHouse, ClickHouseMode, ClickHouseProvider } from './clickhouse.ts'
import { CLICKHOUSE_PASSWORD_VARIABLE, clickHouseEnvironment } from './clickhouse.ts'
import { SECRET_FETCH_INSTANCE_ID } from './runner-enrollment.ts'
import { DEFAULT_CLICKHOUSE_RETENTION_HOURS } from './clickhouse-retention.ts'
import type { Cluster, ClusterProvider, WorkloadHost } from './cluster.ts'
import type { Collector, CollectorProvider } from './collector.ts'
import { COLLECTOR_API_KEY_STORE_KEY, COLLECTOR_API_KEY_VARIABLE } from './collector.ts'
import type { Database, DatabaseProvider } from './database.ts'
import { DATABASE_PASSWORD_VARIABLE, databaseEnvironment } from './database.ts'
import type { Edge, EdgeProvider } from './edge.ts'
import type { UserDomain } from './hosts.ts'
import type { Images, ImagesRequest } from './image.ts'
import type { Mail, MailProvider } from './mail.ts'
import { mailEnvironment } from './mail.ts'
import type { Network, NetworkProvider } from './network.ts'
import type { RegistryProxy, RegistryProxyProvider } from './registry-proxy.ts'
import {
registryCredentialEnvironment,
type RegistryCredentialStore,
type RegistryCredentialStoreProvider,
} from './registry-credentials.ts'
import {
REGISTRY_PROXY_CONTROL_PLANE_VARIABLE,
REGISTRY_PROXY_HOST_VARIABLE,
REGISTRY_PROXY_PORT,
REGISTRY_PROXY_PORT_VARIABLE,
REGISTRY_PROXY_UPSTREAM_HOSTS,
REGISTRY_PROXY_UPSTREAM_HOSTS_VARIABLE,
registryProxyHostOf,
} from './registry-proxy.ts'
import { runnerApiUrl } from './runner-boot.ts'
import type { DeploySecretFetch, RunnerAssignment, RunnerProvider, RunnerSlot, Runners } from './runners.ts'
import { API_RUNNER_TOKEN_VARIABLE } from './runners.ts'
import type { Storage, StorageProvider } from './storage.ts'
import type { DeployConfig } from '../src/config.ts'
/**
* The containerised workloads the cluster places. The runner is a machine and
* is placed directly; the registry proxy is placed by its own provider.
*/
const CONTAINER_ROLES = ['api', 'proxy', 'otel-collector'] as const
/**
* The image each workload pulls, keyed by the artifact name
* `mbuild.config.json` declares. A missing component is a build that did not
* publish rather than an address this file could invent.
*/
const imageFor = (
images: Images,
component: 'api' | 'proxy' | 'otel-collector' | 'registry-proxy' | 'secret-server',
): $util.Input<string> => {
const address = images[component]
if (!address) throw new Error(`mbuild published no ${component} image for this commit`)
return address
}
/** What one deploy decides, as opposed to what `mdeploy.config.json` declares. */
export type StackInputs = {
/** `CLICKHOUSE_RETENTION_HOURS` from the stage, or null when it set none. */
clickHouseRetentionHours: number | null
stage: string
/** The commit being deployed. Every container runs the same one. */
tag: string
/** The stage's own domain. The control plane answers at `api.<domain>`. */
domain: string
/** The zone `*.<proxyDomain>` is written into. Every box is a name under it. */
proxyDomain: string
/** What the proxy speaks to a box. */
proxyProtocol: string
/**
* The origin the control plane hands a client composing a box URL.
*
* Carried into the API's environment rather than derived there: the API takes
* it with `getOrThrow`, so a container without it answers `/api/config` with
* a 500 — and the proxy reads that route before it forwards a byte.
*/
proxyTemplateUrl: string
/** Whether private workloads get outbound internet. */
internetEgress: boolean
/** The verified sender domain, or null for a stage that sends no mail. */
senderDomain: string | null
/** `STACK_USER_DOMAIN` and its zone: users' named apps are `<name>.<domain>`, or null for none. */
userDomain: UserDomain | null
/** What each runner installs, resolved before any host exists. */
runnerBinary: import('./runners.ts').RunnerBinary
/** The hosts to create, and the names the control plane registers them under. */
runnerFleet: readonly RunnerSlot[]
filestoreProjects: readonly string[]
/** Each workload's own environment and addresses, split by the store's groups. */
apiEnvironment: Record<string, $util.Input<string>>
apiSecrets: Record<string, $util.Input<string>>
proxyEnvironment: Record<string, $util.Input<string>>
proxySecrets: Record<string, $util.Input<string>>
collectorEnvironment: Record<string, $util.Input<string>>
collectorSecrets: Record<string, $util.Input<string>>
runnerEnvironment: Record<string, $util.Input<string>>
runnerSecrets: Record<string, $util.Input<string>>
}
/**
* The providers, already parameterised with whatever their cloud needs. Each
* entry is a function from the modules it depends on to the provider itself,
* which is why the bundle can be built before any resource exists.
*/
export type StackProviders = {
secretServer?: (input: { network: Network; database: Database; image: $util.Input<string> }) => {
writeUrl: $util.Output<string>
deployFetch: DeploySecretFetch
}
images: (request: ImagesRequest) => Images
network: NetworkProvider
storage: StorageProvider
cluster: (input: { network: Network }) => ClusterProvider
database: (input: { network: Network }) => DatabaseProvider
cache: (input: { network: Network }) => CacheProvider
clickhouse: (input: { network: Network }) => ClickHouseProvider
mail: MailProvider
collector: (input: {
host: WorkloadHost
network: Network
clickhouse: ClickHouse
dependsOn: any[]
}) => CollectorProvider
/**
* Handed the network as well as its dependencies, because the API is private
* either way and the two clouds say so differently. AWS puts it behind a
* security group the network already arranged; Cloud Run refuses everyone
* except a named invoker, and that name comes from the network too.
*/
api: (input: { dependencies: ApiDependencies; network: Network }) => ApiProvider
edge: (input: { host: WorkloadHost; network: Network; dependsOn: any[] }) => EdgeProvider
/**
* Whether this cloud's edge writes the user domain's wildcard record and
* certificate. Asked before the API is placed, because the API must not hand
* out `demo.<userDomain>` URLs on a cloud whose edge serves none of them.
*/
servesUserDomain: () => boolean
/**
* Whether this cloud's runners keep box state on a data disk the control
* plane can grow online. Asked before the API is placed, because the API is
* granted the resize capability only where a disk exists to grow — a grant
* bounded to resources the cloud does not create would be a permission that
* silently matched nothing.
*/
resizeRunnerDisks: () => boolean
/**
* No host, like the runner: on the cloud that deploys it this is a managed
* service rather than a cluster task, so it takes its placement from the
* network directly. The other cloud answers with the inactive handle.
*/
registryProxy: (input: {
network: Network
dependsOn: any[]
registryCredentials: RegistryCredentialStore
}) => RegistryProxyProvider
/** Where registry passwords live: on the proxy's cloud, and inactive on the other. */
registryCredentials: RegistryCredentialStoreProvider
/**
* One host's registration token, minted so it survives the next deploy.
*
* A provider member rather than a `new random.RandomPassword` here, because
* nothing else in this file constructs a resource — that property is what
* lets a bundle of fakes drive the same wiring. Both engines carry the same
* `random` provider, so neither implementation names a cloud.
*/
mintRunnerToken: (name: string) => $util.Input<string>
/**
* No host: a runner is a machine rather than a task, so it takes a placement
* from the network directly. See `cluster.ts`.
*/
runners: (input: {
network: Network
/** What registers the hosts the API does not seed. See `runner-registration.ts`. */
adminApiKey: $util.Input<string>
/** The region those rows go in — the same one the API seeded its own into. */
regionId: string
dependsOn: any[]
}) => RunnerProvider
alarms: (input: { subjects: AlarmSubjects }) => AlarmProvider
}
/**
* A name one workload reads is carried by one channel and no other.
*
* Every channel becomes an environment variable in the same container, so a
* name in two of them is two entries for one variable — and the clouds do not
* agree about that: an ECS task takes the last one written, a Cloud Run
* revision will not accept the pair at all. Refused here, where every channel
* is known.
*
* `injected` is why this takes four arguments rather than comparing the two
* maps. The database password, the cache password and the ClickHouse password
* are handed to their containers by reference under names that never appear in
* `environment`, so comparing only those two would let a store address for one
* through — to be dropped on one cloud and rejected on the other, which is the
* divergence this exists to prevent.
*/
const assertOneChannelPerName = ({
workload,
environment,
secrets,
injected,
}: {
/** The container this is about, as the refusal should name it. */
workload: string
environment: Record<string, $util.Input<string>>
secrets: Record<string, $util.Input<string>>
/** Names the stack hands the workload by reference itself. */
injected: readonly string[]
}): void => {
const carried = new Set([...Object.keys(environment), ...injected])
const both = Object.keys(secrets).filter((name) => carried.has(name))
if (both.length > 0) {
throw new Error(
`${both.join(', ')} would reach the ${workload} twice — the stack carries that name itself, ` +
'and the store names it as an address; a name is carried by one channel or the other',
)
}
}
/**
* Retention is resolved here, where the mode is known. Only a self-hosted
* ClickHouse applies it; a value set for a managed or disabled one would be
* silently dropped, so it is refused instead.
*/
const clickHouseRetentionFor = (mode: ClickHouseMode, configured: number | null): number => {
if (configured !== null && mode !== 'self-hosted') {
throw new Error(`CLICKHOUSE_RETENTION_HOURS cannot be set when deploy.clickhouse.mode is ${mode}`)
}
return configured ?? DEFAULT_CLICKHOUSE_RETENTION_HOURS
}
/** What the deploy reports, and what a post-deploy check reads. */
export type StackOutputs = {
apiUrl: $util.Output<string>
proxyUrl: $util.Output<string>
databaseId: $util.Output<string>
cacheId: $util.Output<string>
storageName: $util.Output<string>
collectorUrl: $util.Output<string>
clickHouseId: $util.Output<string> | null
/** Null on a cloud that does not deploy one, as `clickHouseId` is for a disabled store. */
registryProxyUrl: $util.Output<string> | null
runnerIds: $util.Output<string>[]
}
export const deployStack = ({
providers,
config,
inputs,
}: {
providers: StackProviders
config: DeployConfig
inputs: StackInputs
}): StackOutputs => {
const images = providers.images({ tag: inputs.tag })
const network = providers.network({ internetEgress: inputs.internetEgress })
const storage: Storage = providers.storage(config.storage)
const cluster: Cluster = providers.cluster({ network })({ roles: CONTAINER_ROLES })
const database: Database = providers.database({ network })(config.database)
const secrets = providers.secretServer?.({ network, database, image: imageFor(images, 'secret-server') })
const cache: Cache = providers.cache({ network })(config.cache)
const clickhouse: ClickHouse = providers.clickhouse({ network })({
...config.clickhouse,
retentionHours: clickHouseRetentionFor(config.clickhouse.mode, inputs.clickHouseRetentionHours),
})
const registryCredentials: RegistryCredentialStore = providers.registryCredentials()
/*
* The network's own rules, which reach every workload through the cluster.
* Outbound HTTPS is how any task pulls an image or reaches the OIDC issuer,
* and the proxy↔API pair is how a box lookup succeeds; a task placed before
* they exist starts, fails, and is replaced in a loop. Nothing else consumes
* `cluster.ready`, so every workload waits on it here.
*/
const placed = cluster.ready
// Ahead of the API because it produces that service's SMTP settings, and
// because verification blocks on DNS rather than on anything this stack
// builds — so a first deploy of a new sender domain waits here rather than at
// the first invitation.
const mail: Mail = providers.mail({ senderDomain: inputs.senderDomain })
// Before the API, so every workload emits to the same collector — including
// the API's own traces, which is why it is not the other way round.
/*
* The key the collector authenticates to the API with, under the name the
* collector reads. `collector.ts` owns both names and says why there are two.
*
* Renamed on whichever channel carries it, rather than on the one that
* usually does. The store may mark this key in `env.selectGroup.secret`, and
* then it arrives as an address in `collectorSecrets` instead of as a value —
* a first-class shape this stack supports and `stack.test.ts` exercises. A
* rename that only read the value channel would ship a collector with no
* `BOXLITE_API_KEY` on exactly that path: silent, because the collector's own
* config has a default which authenticates as nobody.
*
* Two entries, one secret, on both clouds: an ECS `secrets` list and a Cloud
* Run revision each take more than one name pointing at one place.
*/
const collectorKeyValue = inputs.collectorEnvironment[COLLECTOR_API_KEY_STORE_KEY]
const collectorKeyAddress = inputs.collectorSecrets[COLLECTOR_API_KEY_STORE_KEY]
if (!collectorKeyValue && !collectorKeyAddress) {
// Required in its group, so reaching here means the declaration changed
// rather than a stage forgetting something. Refused: the alternative is a
// collector that starts, looks healthy, and is answered 401 forever.
throw new Error(
`${COLLECTOR_API_KEY_STORE_KEY} reached neither the collector's values nor its secrets, so the ` +
`collector cannot be given ${COLLECTOR_API_KEY_VARIABLE} and would authenticate to the API as nobody`,
)
}
const collectorEnvironment = {
...inputs.collectorEnvironment,
...clickHouseEnvironment(clickhouse, 'writer'),
...(collectorKeyValue ? { [COLLECTOR_API_KEY_VARIABLE]: collectorKeyValue } : {}),
}
const collectorSecrets = {
...inputs.collectorSecrets,
...(collectorKeyAddress ? { [COLLECTOR_API_KEY_VARIABLE]: collectorKeyAddress } : {}),
}
assertOneChannelPerName({
workload: 'collector',
environment: collectorEnvironment,
secrets: collectorSecrets,
injected: [CLICKHOUSE_PASSWORD_VARIABLE],
})
const collector: Collector = providers.collector({
host: cluster.hostFor('otel-collector'),
network,
clickhouse,
dependsOn: [...placed, ...(clickhouse.active ? clickhouse.ready : [])],
})({
image: imageFor(images, 'otel-collector'),
// One list for all three pipelines. A collector told to write to a
// ClickHouse that does not exist retries every batch forever, so a disabled
// stage runs the BoxLite exporter alone.
exporters: clickhouse.active ? '[boxlite_exporter,clickhouse]' : '[boxlite_exporter]',
environment: collectorEnvironment,
secrets: collectorSecrets,
})
// The stack's own names last: a stale copy of a database host in the store
// must not shadow the database this deploy just built.
/*
* The fleet's tokens, minted before the API because the API spends one.
*
* Pairing is token-based: the API seeds the first runner's row from
* `DEFAULT_RUNNER_API_KEY`, and that host presents the same value as
* `BOXLITE_RUNNER_TOKEN`. So the two have to come from one place, and it has
* to be a place that runs before the API — which is here, not in a provider.
*
* One resource name per control-plane name rather than per index, so growing
* the fleet mints a new token instead of renumbering the existing ones and
* invalidating every row already registered.
*/
const fleet: RunnerAssignment[] = inputs.runnerFleet.map((slot) => ({
slot,
token: providers.mintRunnerToken(`RunnerToken-${slot.controlPlaneRunnerName}`),
}))
const defaultRunnerToken = fleet[0]?.token
if (defaultRunnerToken === undefined) {
throw new Error('the fleet is empty; a stage runs at least one runner, which the API seeds its row from')
}
/*
* The registry proxy, before the API because the API is handed its host: a
* private image is given to a runner as a ref under that host, and only the
* resolver writes one. The proxy asks the API about every caller — a
* runner's key is an opaque column, not a signed token — but it reaches the
* API by `api.<domain>`, which the stage's domain fixes before either
* exists, so nothing of the API's is needed to build it. Until the API
* answers, a caller is told to retry, as during any restart of it.
*
* The proxy reads organization logins from the credential store and uses
* its configured host list for anonymous pulls.
*
* Telemetry on, for the reason the edge proxy's note further down gives: the
* binary declares both switches without a default, and one left unset ships
* nothing while looking healthy.
*/
const { [REGISTRY_PROXY_UPSTREAM_HOSTS_VARIABLE]: anonymousUpstreamHosts, ...baseApiEnvironment } =
inputs.apiEnvironment
const registryProxy: RegistryProxy = providers.registryProxy({
network,
dependsOn: placed,
registryCredentials,
})({
image: imageFor(images, 'registry-proxy'),
environment: {
OTEL_LOGGING_ENABLED: 'true',
OTEL_TRACING_ENABLED: 'true',
OTEL_EXPORTER_OTLP_ENDPOINT: collector.otlpUrl,
ENVIRONMENT: inputs.stage,
[REGISTRY_PROXY_PORT_VARIABLE]: String(REGISTRY_PROXY_PORT),
[REGISTRY_PROXY_CONTROL_PLANE_VARIABLE]: runnerApiUrl(`https://${publicHostsFor({ domain: inputs.domain }).api}`),
[REGISTRY_PROXY_UPSTREAM_HOSTS_VARIABLE]: anonymousUpstreamHosts || REGISTRY_PROXY_UPSTREAM_HOSTS.join(','),
...registryCredentialEnvironment(registryCredentials),
},
})
/** What the API writes into private refs, and what a runner presents its key to. */
const registryProxyHost = registryProxy.active ? registryProxy.url.apply(registryProxyHostOf) : null
// One answer for the API, the proxy and the edge, so a domain's URL is
// minted, resolved and served under the same wildcard — or not offered at all.
// Refused rather than dropped on a cloud that cannot serve it: a stage that
// sets the domain expects its users' apps to answer there.
if (inputs.userDomain && !providers.servesUserDomain()) {
throw new Error(
`STACK_USER_DOMAIN is ${inputs.userDomain.domain}, and this cloud's edge serves no user domain; unset it`,
)
}
const platformDomain = inputs.userDomain?.domain ?? null
const apiEnvironment = {
...baseApiEnvironment,
...(secrets && { SECRET_SERVER_URL: secrets.writeUrl }),
// The first host's token, which is the one row the API seeds itself. Every
// later host is registered explicitly — see `runner-registration.ts`.
[API_RUNNER_TOKEN_VARIABLE]: defaultRunnerToken,
...databaseEnvironment(database),
...cacheEnvironment(cache),
...mailEnvironment(mail),
...clickHouseEnvironment(clickhouse, 'reader'),
...registryCredentialEnvironment(registryCredentials),
...(registryProxyHost
? {
[REGISTRY_PROXY_HOST_VARIABLE]: registryProxyHost,
}
: {}),
/*
* `DB_TLS_ENABLED` is not here. It used to be, as a constant `'true'`
* written after `databaseEnvironment` and therefore winning over it — which
* is fine while every database presents a certificate the image trusts, and
* wrong the moment one does not. A Cloud Run workload reaches Cloud SQL
* through the platform's proxy, over a socket, and telling the client to
* negotiate TLS across it gets `The server does not support SSL
* connections`. The database module derives it from `applicationTls`, which
* is the one place that knows.
*/
OTEL_EXPORTER_OTLP_ENDPOINT: collector.otlpUrl,
BOX_OTEL_ENDPOINT_URL: collector.otlpUrl,
PROXY_DOMAIN: inputs.proxyDomain,
PROXY_PROTOCOL: inputs.proxyProtocol,
PROXY_TEMPLATE_URL: inputs.proxyTemplateUrl,
// New domain requests need the wildcard served by the edge below.
// Without this suffix, claims are refused; bindings of already owned
// full hostnames still use the stored ownership record.
...(platformDomain ? { PROXY_APP_DOMAIN: platformDomain } : {}),
S3_DEFAULT_BUCKET: storage.name,
// Storage may precede runner rollout. Admission requires a separate opt-in.
CHECKPOINTS_ENABLED: inputs.apiEnvironment.CHECKPOINTS_ENABLED ?? 'false',
MEMORY_CHECKPOINTS_ENABLED: inputs.apiEnvironment.MEMORY_CHECKPOINTS_ENABLED ?? 'false',
// Supply the archive prefix wherever storage provides the dedicated bucket.
...(storage.checkpoints.active ? { CHECKPOINT_ARCHIVE_PREFIX: storage.checkpoints.archivePrefix } : {}),
CLOUD_APP_SOURCE_BUCKET: storage.name,
CLOUD_APP_SOURCE_BACKEND: storage.binding.cloud === 'gcp' ? 'gcs' : 's3',
CLOUD_APP_SOURCE_PREFIX: 'cloud-apps',
}
assertOneChannelPerName({
workload: 'API',
environment: apiEnvironment,
secrets: inputs.apiSecrets,
/*
* The three the stack mints and hands over by reference.
*
* The SMTP credential is deliberately not among them, and the asymmetry is
* worth stating: an SES SMTP credential is an IAM user's access key, which
* the deploy role cannot create — so it is seeded out of band and reaches
* the API through the store's own `api` group like any other secret. What
* the mail module contributes is the host and the From address, which is
* why `mailEnvironment` carries those and nothing else.
*/
injected: [DATABASE_PASSWORD_VARIABLE, CACHE_PASSWORD_VARIABLE, CLICKHOUSE_PASSWORD_VARIABLE],
})
const api: Api = providers.api({
network,
dependencies: {
host: cluster.hostFor('api'),
placement: network.placementFor('api'),
database,
cache,
storage,
clickhouse,
waitFor: [...placed, ...database.ready, ...cache.ready, ...collector.ready, ...(mail.sending ? mail.ready : [])],
},
})({
...config.api,
image: imageFor(images, 'api'),
port: API_PORT,
domain: inputs.domain,
environment: apiEnvironment,
secrets: inputs.apiSecrets,
capabilities: capabilitiesFor({
storage,
clickhouse,
registryCredentials,
resizeRunnerDisks: providers.resizeRunnerDisks(),
filestoreProjects: inputs.filestoreProjects,
}),
})
const proxyEnvironment = {
/*
* Telemetry on unless the stage says otherwise.
*
* The two switches the proxy actually reads — `cmd/proxy/config/config.go`
* declares neither with a default, so a Go bool left unset is false and the
* exporter is never built. The incumbent stack said `envOr(…, 'true')` and
* the runner's boot script still writes both; the port dropped them here,
* which is a proxy that looks healthy and ships nothing.
*
* Before the store's own copy, so a stage that wants its proxy quiet seeds
* `false` in `env.selectGroup.proxy` rather than editing this.
*/
OTEL_LOGGING_ENABLED: 'true',
OTEL_TRACING_ENABLED: 'true',
...inputs.proxyEnvironment,
OTEL_EXPORTER_OTLP_ENDPOINT: collector.otlpUrl,
...(platformDomain ? { PROXY_APP_DOMAIN: platformDomain } : {}),
}
assertOneChannelPerName({
workload: 'proxy',
environment: proxyEnvironment,
secrets: inputs.proxySecrets,
injected: [],
})
const edge: Edge = providers.edge({
host: cluster.hostFor('proxy'),
network,
// The proxy is a front door, so it comes up after what it proxies to: it
// must not accept a box connection before the API can say which runner
// holds that box.
dependsOn: [...placed, ...api.ready],
})({
image: imageFor(images, 'proxy'),
domain: inputs.proxyDomain,
userDomain: inputs.userDomain,
protocol: inputs.proxyProtocol,
apiUrl: api.address,
environment: proxyEnvironment,
secrets: inputs.proxySecrets,
})
const runnerEnvironment: Record<string, $util.Input<string>> = {
...inputs.runnerEnvironment,
OTEL_EXPORTER_OTLP_ENDPOINT: collector.otlpUrl,
}
// OS Config publishes the fetch URL and enrolled host identity together.
if (secrets) {
delete runnerEnvironment.SECRET_SERVER_URL
delete runnerEnvironment[SECRET_FETCH_INSTANCE_ID]
}
assertOneChannelPerName({
workload: 'runner',
environment: runnerEnvironment,
secrets: inputs.runnerSecrets,
injected: secrets ? ['SECRET_SERVER_URL', SECRET_FETCH_INSTANCE_ID] : [],
})
/*
* What registers the hosts the API will not seed.
*
* The API seeds one row, from its own `DEFAULT_RUNNER_*`; a fleet of more
* than one needs the rest registered through the admin API, which needs that
* key. Demanded here rather than where the command is built, because this is
* the layer that knows how many hosts there are — a single-host stage needs
* none of this and must not be failed for it.
*/
const adminApiKey = inputs.apiEnvironment.ADMIN_API_KEY
if (inputs.runnerFleet.length > 1 && adminApiKey === undefined) {
throw new Error(
`this stage runs ${inputs.runnerFleet.length} runners, and the API seeds only the first — ` +
'registering the rest needs ADMIN_API_KEY, which reached the API as an address rather than a value',
)
}
const runners: Runners = providers.runners({
network,
adminApiKey: adminApiKey ?? '',
// The same region the API seeded its own row into, or that seed and these
// registrations would land in two different regions.
regionId: (inputs.apiEnvironment.DEFAULT_REGION_ID as string) ?? 'us',
// A host registers itself with the control plane at first boot, so the
// control plane has to be answering before one exists.
dependsOn: [...api.ready],
})({
...config.runners,
nestedVirtualization: true,
fleet,
deploySecretFetch: secrets?.deployFetch,
binary: inputs.runnerBinary,
apiUrl: api.address,
otlpUrl: collector.otlpUrl,
registryProxyHost,
checkpointBucket: storage.checkpoints.active ? storage.checkpoints.bucket : null,
environment: runnerEnvironment,
secrets: inputs.runnerSecrets,
})
// Alarms watch what is already serving, so nothing waits on them: one that
// cannot be created must not roll back a service that is answering.
providers.alarms({ subjects: { api, edge, runners } })(config.alarms)
return {
apiUrl: api.url,
proxyUrl: edge.url,
databaseId: database.id,
cacheId: cache.id,
storageName: storage.name,
collectorUrl: collector.otlpUrl,
clickHouseId: clickhouse.active ? clickhouse.id : null,
registryProxyUrl: registryProxy.active ? registryProxy.url : null,
runnerIds: runners.ids,
}
}
/**
* What the API may do.
*
* List its own bucket, which is the boot probe; create, tag and delete the
* volume buckets it owns, which is bounded by the storage module's prefix; vend
* a scoped credential for one of them; read telemetry back, which exists only
* where a stage keeps any; write registry passwords it cannot read back, which
* exists only where the registry proxy does; and delete checkpoint archives,
* which exists only where the storage module keeps a checkpoint bucket. Nothing
* here names an ARN or a role — the provider bundle expands each sentence into
* its cloud's own grants.
*
* A provider names each grant by its place in this list, so a new capability
* goes last: inserted earlier, it would move the grants after it to new
* resources, and replacing a non-authoritative IAM member deletes the binding
* its replacement holds.
*/
export const capabilitiesFor = ({
storage,
clickhouse,
registryCredentials,
resizeRunnerDisks,
filestoreProjects,
}: {
storage: Storage
clickhouse: ClickHouse
registryCredentials: RegistryCredentialStore
/** Whether this cloud's runners carry a data disk, asked of the provider bundle. */
resizeRunnerDisks: boolean
filestoreProjects: readonly string[]
}): ApiCapability[] => [
{ kind: 'list-own-bucket', storage },
{ kind: 'manage-volume-buckets', storage },
{ kind: 'vend-volume-credentials', storage },
...(clickhouse.active ? ([{ kind: 'read-telemetry', clickhouse }] as ApiCapability[]) : []),
...(registryCredentials.active
? ([{ kind: 'write-registry-credentials', store: registryCredentials }] as ApiCapability[])
: []),
...(storage.checkpoints.active
? ([{ kind: 'manage-checkpoint-archives', checkpoints: storage.checkpoints }] as ApiCapability[])
: []),
...(resizeRunnerDisks ? ([{ kind: 'resize-runner-disks' }] as ApiCapability[]) : []),
{ kind: 'manage-app-source', storage },
...(filestoreProjects.length
? ([{ kind: 'read-filestore-instances', projects: filestoreProjects }] as ApiCapability[])
: []),
]