The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import { Readable } from 'node:stream'
import { buffer } from 'node:stream/consumers'
import { createCloudAppStore } from '../../../test/cloud-app-store'
import { sha256hex } from './auth'
import type { BoxInfo, CreateBoxRequest } from './boxlite'
import type { Ctx, Deps } from './ctx'
import { Store, type Deployment, type MigrationFile } from './db'
import type { AppliedRow } from './appdb'
import { buildCtx, createServer } from './server'
import { createApp } from './services/apps'
import type { SupervisorStatus } from './supervisor'
const withPostgres = process.env.DB_HOST ? describe : describe.skip
const web = ['[runtime]', 'image="node"', '[[service]]', 'name="web"', 'command="node server.js"', 'port=3000'].join(
'\n',
)
const database = '\n[database]\nmigrations="migrations/"'
const volume = '\n[[volume]]\nname="uploads"\nmount="/data"'
withPostgres('hosted App deployment worker', () => {
let db: Awaited<ReturnType<typeof createCloudAppStore>>
let store: Store
beforeAll(async () => {
db = await createCloudAppStore()
store = new Store(db.source, db.organizationId, undefined, db.schema)
})
afterAll(async () => {
await db?.close()
})
async function environment(name: string) {
const blobs = new Map<string, Buffer>()
const boxes = new Map<string, BoxInfo>()
const mounts = new Map<string, string>()
const applied: AppliedRow[] = []
const services = [{ name: 'web', state: 'running', health: 'healthy', port: 3000 }]
let token: string
const supervisorRequest = (path: string, payload?: unknown) =>
server.request('/sv/v1/' + path, {
method: payload === undefined ? 'GET' : 'POST',
headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' },
body: payload === undefined ? undefined : JSON.stringify(payload),
})
const report = async (status: SupervisorStatus) => {
const response = await supervisorRequest('status', status)
if (!response.ok) throw new Error(await response.text())
}
const live = async (_url: string, _secret: string, release: number) =>
report({ deployment: release, phase: 'live', services })
const supervisor = {
health: jest.fn(async (_url: string) => ({ ok: true, deployment: null, version: 2, services })),
deploy: jest.fn(async (_url: string, _secret: string, release: number) => {
await supervisorRequest('logs', [{ deployment: release, source: 'build', line: 'compiled server.js' }])
await report({ deployment: release, phase: 'built' })
}),
activate: jest.fn(live),
rollback: jest.fn(live),
}
const boxlite = {
createBox: jest.fn(async (request: CreateBoxRequest) => {
const box = { id: request.name, name: request.name, status: 'running' }
boxes.set(box.id, box)
token = request.env.BOXLITE_BOX_TOKEN
return box
}),
getBox: async (id: string) => boxes.get(id) ?? null,
tunnel: async (id: string) => 'https://' + id + '.example.test',
deleteBox: jest.fn(async (id: string) => {
boxes.delete(id)
}),
startBox: jest.fn(async (id: string) => {
boxes.get(id)!.status = 'running'
}),
stopBox: jest.fn(async (id: string) => {
boxes.get(id)!.status = 'stopped'
}),
}
const volumes = {
list: async () => [...mounts].map(([name, id]) => ({ name, id })),
create: jest.fn(async (_app, _env, name: string) => {
const id = 'volume-' + mounts.size
mounts.set(name, id)
return { name, id }
}),
remove: jest.fn(),
}
const neon = {
createProject: jest.fn(async () => ({
projectId: 'project',
mainBranchId: 'main-branch',
connectionUri: 'postgresql://[email protected]/db',
})),
restoreBranch: jest.fn(async () => undefined),
createBranch: jest.fn(async (_project: string, name: string, _parent: string, _init: string) => ({
branchId: 'br-' + name,
})),
connectionUri: jest.fn(
async (_project: string, branch: string) => 'postgresql://owner@' + branch + '.example.test/db',
),
}
const appdb = {
ensureReader: jest.fn(async () => undefined),
listApplied: async () => applied,
query: jest.fn(async () => ({ rows: [] })),
copyMigrationLedger: jest.fn(async (_from: string, _to: string) => 1),
applyMigration: jest.fn(async (_url: string, m: MigrationFile, deployment: number) => {
applied.push({ file: m.file, sha256: m.sha256, deployment, applied_at: new Date().toISOString() })
}),
}
const ctx: Ctx = buildCtx(
{
publicUrl: 'https://api.example.test',
supervisorUrl: 'https://guest-api.example.test',
managementUrl: 'https://api.example.test',
sessionSecret: 'test',
identityPrivateKey: '',
runtimeImages: { node: 'runtime:test' },
diskSizeGb: 10,
autoStopSeconds: 900,
artifactUrl: 'https://artifact.example.test',
domainsEnabled: false,
agentMdPath: '',
svBinDir: '',
},
{
store,
boxlite,
supervisor,
neon,
appdb,
volumes,
boxes: { list: async (_app, env) => [...boxes.keys()].filter((id) => !env || env.active_box_id === id) },
domains: { releaseEnvironment: async () => undefined },
blobs: {
has: async (_app: string, sha: string) => blobs.has(sha),
put: async (_app: string, sha: string, stream: Readable) => {
const contents = await buffer(stream)
blobs.set(sha, contents)
return { bytes: contents.length, deduped: false }
},
read: (_app: string, sha: string) => Readable.from([blobs.get(sha)!]),
},
origins: { envUrl: () => 'https://' + name + '.apps.example.test' },
} as unknown as Deps,
{ pollMs: 2, buildMs: 1000, activateMs: 1000, supervisorReadyMs: 1000 },
)
const app = await createApp(ctx, name)
const env = (await store.envByName(app.id, 'main'))!
const server = createServer(ctx)
const principal = {
organizationId: db.organizationId,
userId: 'owner',
actor: 'user:owner',
permissions: ['write:apps', 'read:apps'],
}
const request = (path: string, payload?: unknown, method = 'POST') =>
server.request(
'/v1/apps/' + name + path,
{
method,
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
},
{ platformPrincipal: principal },
)
async function upload(files: Record<string, string>) {
const manifest = Object.entries(files).map(([path, body]) => ({
path,
size: Buffer.byteLength(body),
mode: 0o644,
sha256: sha256hex(body),
}))
const started = await request('/uploads', { manifest })
expect(started.status).toBe(200)
const { upload_id, missing } = await started.json()
for (const file of manifest.filter((f) => missing.includes(f.sha256))) {
const put = await server.request(
'/v1/apps/' + name + '/uploads/' + upload_id + '/files/' + file.sha256,
{
method: 'PUT',
body: files[file.path],
},
{ platformPrincipal: principal },
)
expect(put.status).toBe(200)
}
const completed = await request('/uploads/' + upload_id + '/complete', {})
expect(completed.status).toBe(200)
return (await completed.json()).snapshot_id as string
}
const enqueue = async (input: object) => {
const result = await request('/envs/main/deployments', input)
if (result.status !== 202) throw new Error(await result.text())
return (await result.json()).number as number
}
const run = async (input: object): Promise<Deployment> => {
const number = await enqueue(input)
await ctx.orchestrator.runQueued(env.id)
return (await store.deployment(env.id, number))!
}
const manifest = '[app]\nname="' + name + '"\n' + web
return {
ctx,
app,
env,
manifest,
report,
request,
supervisorRequest,
upload,
enqueue,
run,
boxlite,
supervisor,
neon,
volumes,
appdb,
}
}
test('deploys source, applies a migration to that release and rolls configuration and database back together', async () => {
const h = await environment('release-history')
const manifest = h.manifest + database + volume
const sql = 'CREATE TABLE messages (id integer);'
const snapshot = await h.upload({
'boxlite.toml': manifest,
'server.js': 'console.log(1)',
'migrations/0001_messages.sql': sql,
})
const first = await h.run({ kind: 'deploy', snapshot_id: snapshot, manifest })
expect(first).toMatchObject({
status: 'live',
release: 1,
spec_version: 1,
snapshot_id: snapshot,
error: null,
built: true,
})
expect(first.steps.map((s) => [s.name, s.status])).toEqual(
['check', 'upload', 'database', 'box', 'build', 'migrate', 'start', 'live'].map((name) => [name, 'done']),
)
expect(h.boxlite.createBox.mock.calls[0][0]).toMatchObject({
image: 'runtime:test',
volumes: [{ managed_volume: 'volume-0', guest_path: '/data' }],
})
expect(h.appdb.applyMigration).toHaveBeenCalledWith(
expect.stringContaining('sslmode=verify-full'),
{ file: '0001_messages.sql', sha256: sha256hex(sql), sql },
1,
)
expect(await (await h.supervisorRequest('spec')).json()).toMatchObject({
deployment: 1,
env: { BOXLITE_APP: h.app.name, DATABASE_URL: expect.stringContaining('main.example.test') },
snapshot: { id: snapshot },
})
expect(await store.events(h.env.id, 1)).toEqual(
expect.arrayContaining([
expect.objectContaining({
event: 'log',
data: expect.objectContaining({ source: 'build', line: 'compiled server.js' }),
}),
expect.objectContaining({ event: 'done', data: expect.objectContaining({ status: 'live' }) }),
]),
)
const nextSql = 'ALTER TABLE messages ADD COLUMN title text;'
const migration = { file: '0002_title.sql', sql: nextSql, sha256: sha256hex(nextSql) }
const second = await h.run({
kind: 'apply',
manifest: manifest + '\n[variables]\nCOLOR="blue"',
base_version: 1,
migrations: [{ file: '0001_messages.sql', sha256: sha256hex(sql), sql }, migration],
})
expect(second).toMatchObject({
status: 'live',
spec_version: 2,
release: 1,
snapshot_id: snapshot,
restore_point: expect.any(String),
})
expect(h.appdb.applyMigration).toHaveBeenCalledTimes(2)
expect(h.supervisor.deploy).toHaveBeenCalledTimes(1)
expect(await store.deployment(h.env.id, 1)).toMatchObject({ status: 'superseded' })
expect((await (await h.supervisorRequest('spec')).json()).env.COLOR).toBe('blue')
const rollback = await h.run({ kind: 'rollback', to: 1, with_database: true })
expect(rollback).toMatchObject({ status: 'live', release: 1, snapshot_id: snapshot, spec_version: 3 })
expect(await store.deployment(h.env.id, 2)).toMatchObject({ status: 'rolled_back' })
expect(await store.spec(h.env.id, 3)).toMatchObject({
base_version: 2,
deployment: 3,
variables: {},
database: { applied: [{ file: '0001_messages.sql', deployment: 1 }] },
})
expect(h.neon.restoreBranch).toHaveBeenCalledWith(
'project',
'main-branch',
second.restore_point,
'main-before-rollback-3',
)
expect(h.supervisor.rollback.mock.calls.map((call) => call[2])).toEqual([1, 1])
})
test('failed builds preserve the live release and a replaced Box invalidates earlier rollback targets', async () => {
const h = await environment('release-failure')
const snapshot = await h.upload({ 'server.js': 'console.log("ok")' })
const deploy = { kind: 'deploy', snapshot_id: snapshot, manifest: h.manifest }
const first = await h.run(deploy)
expect(first.status).toBe('live')
h.supervisor.deploy.mockImplementationOnce(async (_url, _secret, n) => {
await h.report({
deployment: n,
phase: 'failed',
step: 'build',
error: 'build exited 1',
log_tail: ['syntax error'],
})
})
const broken = await h.run({ ...deploy, base_version: 1 })
expect(broken).toMatchObject({
status: 'failed',
built: false,
error: { step: 'build', message: 'build exited 1', log_tail: ['syntax error'] },
})
expect(await store.envById(h.env.id)).toMatchObject({ requested_deployment: 1, live_deployment: 1 })
expect(h.supervisor.activate).toHaveBeenCalledTimes(1)
expect(await h.ctx.orchestrator.rollbackProblem(h.env, broken.number)).toContain('never went live')
const fixed = await h.run({ ...deploy, manifest: h.manifest + volume, base_version: 1 })
expect(fixed).toMatchObject({ status: 'live', release: 3 })
expect(h.boxlite.deleteBox).toHaveBeenCalledWith(first.box_id)
const current = (await store.envById(h.env.id))!
expect(await h.ctx.orchestrator.rollbackProblem(current, first.number)).toContain(
'Box that has since been replaced',
)
expect(await h.ctx.orchestrator.rollbackProblem(current, fixed.number)).toBeNull()
})
test('cancels queued and building jobs, rejects cancellation during activation, and recovers a lost worker', async () => {
const h = await environment('release-cancel')
const snapshot = await h.upload({ 'server.js': 'console.log(1)' })
const input = { kind: 'deploy', manifest: h.manifest, snapshot_id: snapshot }
await expect(h.ctx.orchestrator.cancel(h.env.id, 42)).rejects.toMatchObject({ code: 'not_found' })
const queued = await h.enqueue(input)
expect((await h.ctx.orchestrator.cancel(h.env.id, queued)).status).toBe('cancelled')
await expect(h.ctx.orchestrator.cancel(h.env.id, queued)).rejects.toThrow('already finished')
h.supervisor.deploy.mockImplementationOnce(async (_url, _secret, n) => {
await h.ctx.orchestrator.cancel(h.env.id, n)
await h.report({ deployment: n, phase: 'built' })
})
expect(await h.run(input)).toMatchObject({ status: 'cancelled', error: null })
expect(h.supervisor.activate).not.toHaveBeenCalled()
h.supervisor.activate.mockImplementationOnce(async (_url, _secret, n) => {
await expect(h.ctx.orchestrator.cancel(h.env.id, n)).rejects.toThrow('already switching traffic')
await h.report({ deployment: n, phase: 'live' })
})
const current = await h.run(input)
expect(current.status).toBe('live')
const interrupted = await h.enqueue({ ...input, base_version: current.spec_version })
const lease = new AbortController()
h.supervisor.deploy.mockImplementationOnce(async () => {
lease.abort(new Error('lease lost'))
})
await expect(h.ctx.orchestrator.runQueued(h.env.id, lease.signal)).rejects.toThrow('lease lost')
expect((await store.deployment(h.env.id, interrupted))?.status).toBe('building')
await h.ctx.orchestrator.recover(h.env.id)
expect(await store.deployment(h.env.id, interrupted)).toMatchObject({
status: 'failed',
error: { step: 'worker' },
steps: expect.arrayContaining([{ name: 'build', status: 'failed', detail: expect.any(String) }]),
})
expect(await store.envById(h.env.id)).toMatchObject({
live_deployment: current.number,
requested_deployment: current.number,
})
})
test('reports build instructions, migration order, and scheduled services from the queued snapshot', async () => {
const h = await environment('scheduled-worker')
const manifest = [
h.manifest.replace('image="node"', 'image="node"\nbuild=["npm install", "npm run build"]'),
'[[service]]',
'name="worker"',
'command="node worker.js"',
'[[schedule]]',
'name="daily"',
'cron="0 1 * * *"',
'target="web:/jobs/daily"',
'[[schedule]]',
'name="hourly"',
'cron="0 * * * *"',
'target="web:/jobs/hourly"',
database,
].join('\n')
const snapshot = await h.upload({
'package.json': '{"scripts":{"build":"node build.js"}}',
'public/asset.txt': 'x'.repeat(1024 * 1024),
'migrations/0002_flags.sql': 'ALTER TABLE jobs ADD COLUMN done boolean;',
'migrations/0001_jobs.sql': 'CREATE TABLE jobs (id int);',
})
h.supervisor.activate.mockImplementationOnce(async (_url, _secret, release) =>
h.report({
phase: 'live',
deployment: release,
services: [
{ name: 'web', state: 'running', port: 3000, health: 'none' },
{ name: 'worker', state: 'running' },
],
}),
)
const n = await h.enqueue({ kind: 'deploy', manifest, snapshot_id: snapshot })
await h.ctx.orchestrator.runQueued()
const release = await store.deployment(h.env.id, n)
expect(release?.status).toBe('live')
expect(release?.steps).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: 'upload', detail: expect.stringContaining('4 files, 1.0 MB') }),
expect.objectContaining({ name: 'build', detail: 'npm install && npm run build' }),
expect.objectContaining({ name: 'start', detail: 'web :3000 running · worker running · 2 schedules' }),
]),
)
expect(h.appdb.applyMigration.mock.calls.map(([, m]) => m.file)).toEqual(['0001_jobs.sql', '0002_flags.sql'])
const log = await store.logs(h.env.id, { deployment: n, limit: 100 })
expect(log.some((l) => l.line.includes('package.json has no lockfile'))).toBe(true)
const before = await store.events(h.env.id, n)
await h.supervisorRequest('logs', [{ deployment: n, source: 'web', line: 'runtime after activation' }])
await h.ctx.orchestrator.run(h.env.id, n)
expect(await store.events(h.env.id, n)).toEqual(before)
expect(h.supervisor.deploy).toHaveBeenCalledTimes(1)
})
test('configuration-only setup runs auth schema preparation and branches with the requested data policy', async () => {
const h = await environment('branch-policy')
const manifest = h.manifest + database + '\n[auth]\nproviders=["github"]\nprotect=["/private/*"]'
await store.run(
'INSERT INTO app_oauth_clients (app_id, provider, client_id, client_secret, updated_at) VALUES (?,?,?,?,?)',
h.app.id,
'github',
'client',
'test-client-secret',
new Date().toISOString(),
)
h.appdb.ensureReader.mockRejectedValueOnce(new Error('reader not ready'))
const empty = await h.run({ kind: 'apply', manifest })
expect(empty).toMatchObject({
status: 'live',
release: null,
steps: [
{ name: 'database', status: 'done' },
{ name: 'migrate', detail: 'no migration files' },
{ name: 'live' },
],
})
expect(h.appdb.query).toHaveBeenCalledWith(
expect.any(String),
expect.arrayContaining([expect.stringContaining('boxlite.current_user_id()')]),
{ write: true },
)
expect(h.boxlite.createBox).not.toHaveBeenCalled()
expect(await h.ctx.orchestrator.rollbackProblem(h.env, 1)).toContain('has no release')
expect((await h.request('/envs', { name: 'qa' })).status).toBe(201)
expect((await h.request('/envs', { name: 'demo', from: 'qa', with_data: true })).status).toBe(201)
expect(h.neon.createBranch.mock.calls).toEqual([
['project', 'qa', 'main-branch', 'schema-only'],
['project', 'demo', 'br-qa', 'parent-data'],
])
expect(h.appdb.copyMigrationLedger.mock.calls).toEqual([
[expect.stringContaining('main.example.test'), expect.stringContaining('br-qa.example.test')],
])
expect(h.neon.createProject).toHaveBeenCalledTimes(1)
expect((await store.envByName(h.app.id, 'demo'))?.db_url).toContain('br-demo.example.test')
expect((await store.logs(h.env.id, { limit: 100 })).map((l) => l.line)).toContainEqual(
expect.stringContaining('reader not ready'),
)
})
test('provisions a deferred child database from the main branch after its named parent was removed', async () => {
const h = await environment('deferred-parent')
expect((await h.request('/envs', { name: 'staging' })).status).toBe(201)
expect((await h.request('/envs', { name: 'child', from: 'staging' })).status).toBe(201)
expect(h.neon.createProject).not.toHaveBeenCalled()
expect((await h.request('/envs/staging', undefined, 'DELETE')).status).toBe(200)
const child = (await store.envByName(h.app.id, 'child'))!
const prepared = await h.ctx.resources.ensureDatabase(h.app.id, child.id)
expect(prepared).toMatchObject({ branchId: 'br-child', host: 'br-child.example.test' })
expect(h.neon.createBranch).toHaveBeenCalledWith('project', 'child', 'main-branch', 'schema-only')
expect(h.appdb.copyMigrationLedger).not.toHaveBeenCalled()
expect(await h.ctx.resources.appUrl(h.app.name, 'staging')).toBe(h.ctx.config.publicUrl)
expect(await h.ctx.resources.appUrl('absent', 'main')).toBe(h.ctx.config.publicUrl)
})
test('rejects malformed migration files before building and guards already applied SQL in the uploaded snapshot', async () => {
const h = await environment('migration-guard')
const manifest = h.manifest + database
const malformed = await h.upload({ 'migrations/first.sql': 'SELECT 1;' })
const invalid = await h.run({ kind: 'deploy', manifest, snapshot_id: malformed })
expect(invalid).toMatchObject({
status: 'failed',
error: { step: 'check', errors: [expect.objectContaining({ file: 'migrations/first.sql' })] },
})
expect(h.boxlite.createBox).not.toHaveBeenCalled()
const source = { 'migrations/0001_init.sql': 'CREATE TABLE entries (id int);' }
const snapshot = await h.upload(source)
expect(await h.run({ kind: 'deploy', manifest, snapshot_id: snapshot })).toMatchObject({
status: 'live',
release: 2,
})
const again = await h.run({ kind: 'deploy', manifest, snapshot_id: snapshot, base_version: 1 })
expect(again.steps).toContainEqual(expect.objectContaining({ name: 'migrate', detail: 'schema up to date' }))
const edited = await h.upload({ 'migrations/0001_init.sql': 'CREATE TABLE entries (id bigint);' })
const rejected = await h.run({ kind: 'deploy', manifest, snapshot_id: edited, base_version: again.spec_version })
expect(rejected).toMatchObject({
status: 'failed',
built: true,
error: { step: 'migrate', message: expect.stringContaining('applied migration(s) changed') },
})
expect(h.appdb.applyMigration).toHaveBeenCalledTimes(1)
expect((await store.envById(h.env.id))?.live_deployment).toBe(again.number)
})
test('replaces an unbootable fresh Box once and preserves a live Box on supervisor failure', async () => {
const h = await environment('boot-recovery')
const manifest = h.manifest + volume
const snapshot = await h.upload({ 'server.js': 'console.log(1)' })
h.ctx.timing.supervisorReadyMs = 60
const health = h.supervisor.health.getMockImplementation()!
h.supervisor.health.mockImplementation(async (url: string) => {
if (!url.includes('-1-r.')) throw new Error('supervisor unreachable')
return health(url)
})
const live = await h.run({ kind: 'deploy', manifest, snapshot_id: snapshot })
expect(live).toMatchObject({ status: 'live', box_id: expect.stringMatching(/-1-r$/) })
expect(h.boxlite.createBox).toHaveBeenCalledTimes(2)
expect(h.volumes.create).toHaveBeenCalledTimes(1)
expect(h.boxlite.deleteBox.mock.calls).toEqual([['app-boot-recovery-main']])
const persisted = (await store.envById(h.env.id))!
await h.ctx.resources.sleep(persisted.active_box_id!)
await h.ctx.resources.ensureRunning(h.env.id, () => undefined)
expect(h.boxlite.startBox).toHaveBeenCalledWith(persisted.active_box_id)
expect(h.ctx.resources.recentlyWoken(persisted.active_box_id!)).toBe(true)
h.supervisor.health.mockRejectedValue(new Error('supervisor unreachable'))
const failed = await h.run({ kind: 'deploy', manifest, snapshot_id: snapshot, base_version: 1 })
expect(failed).toMatchObject({
status: 'failed',
error: { step: 'box', message: expect.stringContaining('supervisor unreachable') },
})
expect(h.boxlite.deleteBox).toHaveBeenCalledTimes(1)
await h.ctx.resources.deleteVolumes(h.app, persisted)
expect(h.volumes.remove).toHaveBeenCalledWith(h.app, persisted, 'volume-0')
})
test('retains the running release outside the three newest builds and reads its effective spec after failed activations', async () => {
const h = await environment('release-retention')
await store.run(
'INSERT INTO app_secrets (app_id,name,value,updated_at) VALUES (?,?,?,?)',
h.app.id,
'service-key',
'configured-value',
new Date().toISOString(),
)
const manifest = h.manifest + '\n[secrets]\nSERVICE_KEY="app/service-key"'
const snapshot = await h.upload({ 'server.js': 'console.log(1)' })
const input = { kind: 'deploy', manifest, snapshot_id: snapshot }
expect(await h.run(input)).toMatchObject({ status: 'live', release: 1 })
expect(await h.run({ ...input, base_version: 1 })).toMatchObject({ status: 'live', release: 2 })
expect(await h.run({ kind: 'rollback', to: 1, with_database: true })).toMatchObject({ status: 'live', release: 1 })
expect(h.neon.restoreBranch).not.toHaveBeenCalled()
h.supervisor.activate.mockImplementation(async (_url, _secret, n) => {
await h.report({ deployment: n, phase: 'failed', error: 'health probe failed' })
})
for (let i = 0; i < 3; i++) {
expect(await h.run({ ...input, base_version: 3 })).toMatchObject({
status: 'failed',
built: true,
error: { step: 'start' },
})
}
const live = (await store.envById(h.env.id))!
expect(await h.ctx.orchestrator.rollbackProblem(live, 1)).toBeNull()
expect(await h.ctx.orchestrator.rollbackProblem(live, 2)).toContain('pruned')
expect(await h.ctx.orchestrator.rollbackProblem(live, 12)).toContain('no deployment')
const spec = await h.ctx.resources.currentSpec(live)
expect(spec?.version).toBe(3)
expect(await h.ctx.resources.runtimeEnv(h.app, live, spec)).toMatchObject({ SERVICE_KEY: 'configured-value' })
await store.run('DELETE FROM app_secrets WHERE app_id = ? AND name = ?', h.app.id, 'service-key')
expect(await h.ctx.resources.runtimeEnv(h.app, live, spec)).not.toHaveProperty('SERVICE_KEY')
expect(await h.ctx.resources.effectiveAccess({ ...live, access_override: 'org' })).toBe('org')
})
test('reuses a sleeping Box for unchanged code and replaces a missing Box when applying a deferred resize', async () => {
const h = await environment('runtime-resize')
const snapshot = await h.upload({ 'server.js': 'console.log(1)' })
const input = { kind: 'deploy', manifest: h.manifest, snapshot_id: snapshot }
const first = await h.run(input)
await h.ctx.resources.sleep(first.box_id!)
const resumed = await h.run({ ...input, base_version: 1 })
expect(resumed.box_id).toBe(first.box_id)
expect(h.boxlite.startBox).toHaveBeenCalledWith(first.box_id)
const resized = h.manifest.replace('image="node"', 'image="node"\nsize="medium"')
const applied = await h.run({ kind: 'apply', manifest: resized, base_version: 2 })
expect(applied).toMatchObject({ status: 'live', release: resumed.release, box_id: resumed.box_id })
expect(h.boxlite.createBox).toHaveBeenCalledTimes(1)
expect((await store.logs(h.env.id, { deployment: applied.number, limit: 30 })).map((l) => l.line)).toContain(
'runtime image/size changes take effect on the next deploy',
)
await h.boxlite.deleteBox(resumed.box_id!)
const replaced = await h.run({ ...input, manifest: resized, base_version: 3 })
expect(replaced).toMatchObject({ status: 'live', box_id: 'app-runtime-resize-main-4' })
expect(h.boxlite.createBox.mock.calls[1][0].memory_mib).toBeGreaterThan(
h.boxlite.createBox.mock.calls[0][0].memory_mib,
)
expect(h.boxlite.deleteBox).toHaveBeenCalledTimes(1)
})
})