Relaunch macOS orca serve safely after updates (#9634)

This commit is contained in:
OrcaWin
2026-07-21 17:44:40 -07:00
committed by GitHub
parent b25c298a2b
commit 1fef1e1ddd
16 changed files with 1621 additions and 64 deletions
+244 -1
View File
@@ -1,7 +1,17 @@
import { EventEmitter } from 'node:events'
import { resolve } from 'node:path'
import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { encodePairingOffer, PAIRING_OFFER_VERSION } from '../../shared/pairing'
import {
getServeUpdateHandoffPath,
parseServeUpdateHandoffState
} from '../../shared/serve-update-handoff'
import {
readServeUpdateHandoff,
SERVE_REPLACEMENT_READY_TIMEOUT_MS
} from './serve-update-supervisor'
const { spawnMock } = vi.hoisted(() => ({
spawnMock: vi.fn()
@@ -17,6 +27,7 @@ class FakeChildProcess extends EventEmitter {
stdout = new EventEmitter()
kill = vi.fn()
unref = vi.fn()
pid = 4101
}
const RECIPE_JSON = JSON.stringify({
@@ -71,6 +82,8 @@ function startRecipeJsonServer() {
}
describe('serveOrcaApp', () => {
const temporaryDirectories: string[] = []
beforeEach(() => {
spawnMock.mockReset()
process.env.ORCA_APP_EXECUTABLE = '/Applications/Orca.app/Contents/MacOS/Orca'
@@ -80,8 +93,238 @@ describe('serveOrcaApp', () => {
vi.restoreAllMocks()
delete process.env.ORCA_APP_EXECUTABLE
delete process.env.ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT
delete process.env.ORCA_USER_DATA_PATH
return Promise.all(
temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true }))
)
})
it.runIf(process.platform === 'darwin')(
'keeps the serve supervisor alive until the installed target version can take ownership',
async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-serve-update-'))
temporaryDirectories.push(root)
const appPath = join(root, 'Orca.app')
const executable = join(appPath, 'Contents', 'MacOS', 'Orca')
const infoPlistPath = join(appPath, 'Contents', 'Info.plist')
const userDataPath = join(root, 'user-data')
await mkdir(join(appPath, 'Contents', 'MacOS'), { recursive: true })
await mkdir(userDataPath, { recursive: true })
await writeFile(
infoPlistPath,
'<plist><dict><key>CFBundleShortVersionString</key><string>1.0.51</string></dict></plist>'
)
process.env.ORCA_APP_EXECUTABLE = executable
process.env.ORCA_USER_DATA_PATH = userDataPath
const oldOwner = new FakeChildProcess()
const replacementOwner = new FakeChildProcess()
replacementOwner.pid = 4102
spawnMock.mockReturnValueOnce(oldOwner).mockReturnValueOnce(replacementOwner)
let supervisorExited = false
const supervisor = serveOrcaApp({ json: true }).then((code) => {
supervisorExited = true
return code
})
const childEnv = spawnMock.mock.calls[0]?.[2]?.env as NodeJS.ProcessEnv | undefined
const handoffPath = childEnv?.ORCA_SERVE_UPDATE_HANDOFF_PATH
expect(handoffPath).toBeTruthy()
await writeFile(
handoffPath!,
JSON.stringify({
schemaVersion: 1,
phase: 'install-requested',
fromVersion: '1.0.51',
targetVersion: '1.0.61',
servingPid: oldOwner.pid
})
)
oldOwner.emit('exit', 0, null)
await Promise.resolve()
expect(supervisorExited).toBe(false)
expect(spawnMock).toHaveBeenCalledTimes(1)
const updateAppPath = join(root, 'Update.app')
await mkdir(join(updateAppPath, 'Contents'), { recursive: true })
await writeFile(
join(updateAppPath, 'Contents', 'Info.plist'),
'<plist><dict><key>CFBundleShortVersionString</key><string>1.0.61</string></dict></plist>'
)
await rename(appPath, join(root, 'Previous.app'))
await rename(updateAppPath, appPath)
await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(2))
replacementOwner.emit('message', {
type: 'orca:serve-ready',
version: '1.0.61',
runtimeId: 'runtime-new'
})
expect(supervisorExited).toBe(false)
await vi.waitFor(async () => expect(await readServeUpdateHandoff(handoffPath!)).toBeNull())
replacementOwner.emit('exit', 0, null)
await expect(supervisor).resolves.toBe(0)
}
)
it.runIf(process.platform === 'darwin')(
'records a replacement version mismatch without starting a retry loop',
async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-serve-update-mismatch-'))
temporaryDirectories.push(root)
const appPath = join(root, 'Orca.app')
const executable = join(appPath, 'Contents', 'MacOS', 'Orca')
const userDataPath = join(root, 'user-data')
await mkdir(join(appPath, 'Contents', 'MacOS'), { recursive: true })
await mkdir(userDataPath, { recursive: true })
await writeFile(
join(appPath, 'Contents', 'Info.plist'),
'<plist><dict><key>CFBundleShortVersionString</key><string>1.0.61</string></dict></plist>'
)
const handoffPath = getServeUpdateHandoffPath(userDataPath)
await writeFile(
handoffPath,
JSON.stringify({
schemaVersion: 1,
phase: 'install-requested',
fromVersion: '1.0.51',
targetVersion: '1.0.61',
servingPid: 4101
})
)
process.env.ORCA_APP_EXECUTABLE = executable
process.env.ORCA_USER_DATA_PATH = userDataPath
const replacementOwner = new FakeChildProcess()
replacementOwner.pid = 4102
spawnMock.mockReturnValue(replacementOwner)
vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
const supervisor = serveOrcaApp({ json: true })
await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce())
replacementOwner.emit('message', {
type: 'orca:serve-ready',
version: '1.0.51',
runtimeId: 'runtime-old'
})
await vi.waitFor(() => expect(replacementOwner.kill).toHaveBeenCalledWith('SIGTERM'))
replacementOwner.emit('exit', 0, null)
await expect(supervisor).resolves.toBe(1)
expect(spawnMock).toHaveBeenCalledOnce()
expect(parseServeUpdateHandoffState(JSON.parse(await readFile(handoffPath, 'utf8')))).toEqual(
expect.objectContaining({
phase: 'failed',
targetVersion: '1.0.61',
reason: expect.stringContaining('reported version 1.0.51')
})
)
}
)
it.runIf(process.platform === 'darwin')(
'records replacement spawn failure before rejecting without a retry loop',
async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-serve-update-spawn-failure-'))
temporaryDirectories.push(root)
const appPath = join(root, 'Orca.app')
const executable = join(appPath, 'Contents', 'MacOS', 'Orca')
const userDataPath = join(root, 'user-data')
await mkdir(join(appPath, 'Contents', 'MacOS'), { recursive: true })
await mkdir(userDataPath, { recursive: true })
await writeFile(
join(appPath, 'Contents', 'Info.plist'),
'<plist><dict><key>CFBundleShortVersionString</key><string>1.0.61</string></dict></plist>'
)
const handoffPath = getServeUpdateHandoffPath(userDataPath)
await writeFile(
handoffPath,
JSON.stringify({
schemaVersion: 1,
phase: 'install-requested',
fromVersion: '1.0.51',
targetVersion: '1.0.61',
servingPid: 4101
})
)
process.env.ORCA_APP_EXECUTABLE = executable
process.env.ORCA_USER_DATA_PATH = userDataPath
const replacementOwner = new FakeChildProcess()
spawnMock.mockReturnValue(replacementOwner)
vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
const supervisor = serveOrcaApp({ json: true })
await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce())
replacementOwner.emit('error', new Error('spawn ENOENT'))
await expect(supervisor).rejects.toThrow('spawn ENOENT')
expect(spawnMock).toHaveBeenCalledOnce()
expect(parseServeUpdateHandoffState(JSON.parse(await readFile(handoffPath, 'utf8')))).toEqual(
expect.objectContaining({
phase: 'failed',
targetVersion: '1.0.61',
reason: expect.stringContaining('spawn ENOENT')
})
)
}
)
it.runIf(process.platform === 'darwin')(
'fails a replacement that never reports runtime readiness without retrying it',
async () => {
vi.useFakeTimers()
const root = await mkdtemp(join(tmpdir(), 'orca-serve-update-no-readiness-'))
temporaryDirectories.push(root)
const appPath = join(root, 'Orca.app')
const executable = join(appPath, 'Contents', 'MacOS', 'Orca')
const userDataPath = join(root, 'user-data')
await mkdir(join(appPath, 'Contents', 'MacOS'), { recursive: true })
await mkdir(userDataPath, { recursive: true })
await writeFile(
join(appPath, 'Contents', 'Info.plist'),
'<plist><dict><key>CFBundleShortVersionString</key><string>1.0.61</string></dict></plist>'
)
const handoffPath = getServeUpdateHandoffPath(userDataPath)
await writeFile(
handoffPath,
JSON.stringify({
schemaVersion: 1,
phase: 'install-requested',
fromVersion: '1.0.51',
targetVersion: '1.0.61',
servingPid: 4101
})
)
process.env.ORCA_APP_EXECUTABLE = executable
process.env.ORCA_USER_DATA_PATH = userDataPath
const replacementOwner = new FakeChildProcess()
spawnMock.mockReturnValue(replacementOwner)
vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
try {
const supervisor = serveOrcaApp({ json: true })
await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce())
await vi.advanceTimersByTimeAsync(SERVE_REPLACEMENT_READY_TIMEOUT_MS)
expect(replacementOwner.kill).toHaveBeenCalledWith('SIGTERM')
replacementOwner.emit('exit', 0, null)
await expect(supervisor).resolves.toBe(1)
expect(spawnMock).toHaveBeenCalledOnce()
expect(
parseServeUpdateHandoffState(JSON.parse(await readFile(handoffPath, 'utf8')))
).toEqual(
expect.objectContaining({
phase: 'failed',
reason: expect.stringContaining('did not report serving version')
})
)
} finally {
vi.useRealTimers()
}
}
)
it('pins the Electron child cwd to the app root instead of the caller cwd', async () => {
const child = {
kill: vi.fn(),
+50 -46
View File
@@ -1,10 +1,21 @@
import { spawn as spawnProcess, type SpawnOptions } from 'node:child_process'
import { dirname, resolve } from 'node:path'
import { resolve } from 'node:path'
import { StringDecoder } from 'node:string_decoder'
import {
SERVE_UPDATE_HANDOFF_PATH_ENV,
getServeUpdateHandoffPath
} from '../../shared/serve-update-handoff'
import {
getEphemeralVmRecipeResultConnection,
parseEphemeralVmRecipeResult
} from '../../shared/ephemeral-vm-recipes'
import { getDefaultUserDataPath } from './metadata'
import { getMacAppBundlePath } from './mac-app-update-bundle'
import {
readServeUpdateHandoffSync,
resumeInterruptedServeUpdate,
superviseForegroundServe
} from './serve-update-supervisor'
import { RuntimeClientError } from './types'
const IGNORED_NON_RECIPE_STDOUT = '[serve] ignored non-recipe stdout'
@@ -101,48 +112,51 @@ export function serveOrcaApp(
childArgs.push('--serve-recipe-json', '--serve-project-root', args.projectRoot)
}
const child = spawnProcess(executable, childArgs, {
const handoffPath =
args.recipeJson !== true && getMacAppBundlePath(executable)
? getServeUpdateHandoffPath(getDefaultUserDataPath())
: null
const childEnv = stripElectronRunAsNode(process.env)
if (handoffPath) {
childEnv[SERVE_UPDATE_HANDOFF_PATH_ENV] = handoffPath
}
const spawnOptions: SpawnOptions = {
detached: args.recipeJson === true,
cwd: resolveAppRoot(),
stdio: args.recipeJson === true ? ['ignore', 'pipe', 'inherit'] : 'inherit',
stdio:
args.recipeJson === true
? ['ignore', 'pipe', 'inherit']
: handoffPath
? ['inherit', 'inherit', 'inherit', 'ipc']
: 'inherit',
...getExecutableSpawnOptions(executable),
env: stripElectronRunAsNode(process.env)
})
env: childEnv
}
const interruptedHandoff = handoffPath ? readServeUpdateHandoffSync(handoffPath) : null
if (interruptedHandoff?.phase === 'install-requested') {
// Why: the node-mode CLI is not an NSRunningApplication, so it can retain launchd ownership while ShipIt swaps the app.
return resumeInterruptedServeUpdate({
executable,
childArgs,
spawnOptions,
spawnChild: spawnProcess,
handoffPath: handoffPath!,
handoff: interruptedHandoff
})
}
const child = spawnProcess(executable, childArgs, spawnOptions)
if (args.recipeJson) {
return waitForRecipeJson(child)
}
return new Promise((resolve, reject) => {
let forceKillTimer: ReturnType<typeof setTimeout> | null = null
const forwardSignal = (signal: NodeJS.Signals): void => {
child.kill(signal)
forceKillTimer ??= setTimeout(() => {
child.kill('SIGKILL')
}, 5000)
}
const cleanup = (): void => {
process.off('SIGINT', forwardSignal)
process.off('SIGTERM', forwardSignal)
if (forceKillTimer) {
clearTimeout(forceKillTimer)
forceKillTimer = null
}
}
process.on('SIGINT', forwardSignal)
process.on('SIGTERM', forwardSignal)
child.once('error', (error) => {
cleanup()
reject(error)
})
child.once('exit', (code, signal) => {
cleanup()
if (typeof code === 'number') {
resolve(code)
return
}
reject(new RuntimeClientError('runtime_serve_failed', `Orca serve exited via ${signal}`))
})
return superviseForegroundServe({
executable,
childArgs,
spawnOptions,
spawnChild: spawnProcess,
child,
handoffPath,
expectedHandoff: null
})
}
@@ -271,13 +285,3 @@ export function stripElectronRunAsNode(env: NodeJS.ProcessEnv): NodeJS.ProcessEn
delete next.ELECTRON_RUN_AS_NODE
return next
}
function getMacAppBundlePath(execPath: string): string | null {
if (process.platform !== 'darwin') {
return null
}
const macOsDir = dirname(execPath)
const contentsDir = dirname(macOsDir)
const appBundlePath = dirname(contentsDir)
return appBundlePath.endsWith('.app') ? appBundlePath : null
}
+87
View File
@@ -0,0 +1,87 @@
import { watch, type FSWatcher } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
const MAC_BUNDLE_UPDATE_TIMEOUT_MS = 120_000
export function getMacAppBundlePath(executable: string): string | null {
if (process.platform !== 'darwin') {
return null
}
const macOsDir = dirname(executable)
const contentsDir = dirname(macOsDir)
const appBundlePath = dirname(contentsDir)
return appBundlePath.endsWith('.app') ? appBundlePath : null
}
export async function waitForMacBundleVersion(
executable: string,
targetVersion: string,
timeoutMs = MAC_BUNDLE_UPDATE_TIMEOUT_MS
): Promise<boolean> {
const appBundlePath = getMacAppBundlePath(executable)
if (!appBundlePath) {
return false
}
const infoPlistPath = resolve(appBundlePath, 'Contents', 'Info.plist')
if ((await readMacBundleVersion(infoPlistPath)) === targetVersion) {
return true
}
return new Promise((resolveWait) => {
let settled = false
let checking = false
let watcher: FSWatcher | null = null
let poll: ReturnType<typeof setInterval> | null = null
const finish = (ready: boolean): void => {
if (settled) {
return
}
settled = true
clearTimeout(timeout)
if (poll) {
clearInterval(poll)
}
watcher?.close()
resolveWait(ready)
}
const check = (): void => {
if (checking || settled) {
return
}
checking = true
void readMacBundleVersion(infoPlistPath)
.then((version) => {
if (version === targetVersion) {
finish(true)
}
})
.finally(() => {
checking = false
})
}
const timeout = setTimeout(() => finish(false), timeoutMs)
poll = setInterval(check, 250)
try {
// Why: ShipIt replaces the whole .app, so watch its stable parent rather than an inode inside the old bundle.
watcher = watch(dirname(appBundlePath), check)
watcher.on('error', () => {
watcher?.close()
watcher = null
})
} catch {
watcher = null
}
check()
})
}
async function readMacBundleVersion(infoPlistPath: string): Promise<string | null> {
try {
const plist = await readFile(infoPlistPath, 'utf8')
const match = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(plist)
return match?.[1]?.trim() || null
} catch {
return null
}
}
+264
View File
@@ -0,0 +1,264 @@
import type { ChildProcess, SpawnOptions, spawn } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { readFile, rename, unlink, writeFile } from 'node:fs/promises'
import {
parseServeSupervisorMessage,
parseServeUpdateHandoffState,
type ServeUpdateHandoffState
} from '../../shared/serve-update-handoff'
import { RuntimeClientError } from './types'
import { waitForMacBundleVersion } from './mac-app-update-bundle'
export const SERVE_REPLACEMENT_READY_TIMEOUT_MS = 60_000
type InstallRequestedHandoff = Extract<ServeUpdateHandoffState, { phase: 'install-requested' }>
type ServeReadiness = 'not-expected' | 'pending' | 'verified' | 'failed'
type ServeSupervisorArgs = {
executable: string
childArgs: string[]
spawnOptions: SpawnOptions
spawnChild: typeof spawn
handoffPath: string | null
}
export async function resumeInterruptedServeUpdate(
args: ServeSupervisorArgs & { handoffPath: string; handoff: InstallRequestedHandoff }
): Promise<number> {
const installed = await waitForMacBundleVersion(args.executable, args.handoff.targetVersion)
if (!installed) {
await recordServeUpdateHandoffFailure(
args.handoffPath,
args.handoff,
`Timed out waiting for Orca ${args.handoff.targetVersion} to be installed.`
)
}
const child = args.spawnChild(args.executable, args.childArgs, args.spawnOptions)
return superviseForegroundServe({
...args,
child,
expectedHandoff: installed ? args.handoff : null
})
}
export async function superviseForegroundServe(
args: ServeSupervisorArgs & {
child: ChildProcess
expectedHandoff: InstallRequestedHandoff | null
}
): Promise<number> {
let child = args.child
let expectedHandoff = args.expectedHandoff
while (true) {
const result = await waitForForegroundChild(
child,
args.handoffPath && expectedHandoff
? { handoffPath: args.handoffPath, handoff: expectedHandoff }
: null
)
if (result.readiness === 'failed') {
return 1
}
if (expectedHandoff && result.readiness !== 'verified') {
if (args.handoffPath) {
await recordServeUpdateHandoffFailure(
args.handoffPath,
expectedHandoff,
`Replacement exited before serving version ${expectedHandoff.targetVersion}.`
)
}
return 1
}
const handoff = args.handoffPath ? await readServeUpdateHandoff(args.handoffPath) : null
if (
handoff?.phase !== 'install-requested' ||
(child.pid !== undefined && handoff.servingPid !== child.pid)
) {
if (typeof result.code === 'number') {
return result.code
}
throw new RuntimeClientError('runtime_serve_failed', `Orca serve exited via ${result.signal}`)
}
const installed = await waitForMacBundleVersion(args.executable, handoff.targetVersion)
if (!installed) {
await recordServeUpdateHandoffFailure(
args.handoffPath!,
handoff,
`Timed out waiting for Orca ${handoff.targetVersion} to be installed.`
)
expectedHandoff = null
} else {
expectedHandoff = handoff
}
child = args.spawnChild(args.executable, args.childArgs, args.spawnOptions)
}
}
function waitForForegroundChild(
child: ChildProcess,
expected: { handoffPath: string; handoff: InstallRequestedHandoff } | null
): Promise<{
code: number | null
signal: NodeJS.Signals | null
readiness: ServeReadiness
}> {
return new Promise((resolveWait, reject) => {
let forceKillTimer: ReturnType<typeof setTimeout> | null = null
let readyTimer: ReturnType<typeof setTimeout> | null = null
let readiness: ServeReadiness = expected ? 'pending' : 'not-expected'
let stateWrite = Promise.resolve()
const terminateChild = (): void => {
child.kill('SIGTERM')
forceKillTimer ??= setTimeout(() => child.kill('SIGKILL'), 5000)
}
const recordReplacementFailure = (reason: string): boolean => {
if (!expected || readiness !== 'pending') {
return false
}
readiness = 'failed'
if (readyTimer) {
clearTimeout(readyTimer)
readyTimer = null
}
stateWrite = recordServeUpdateHandoffFailure(
expected.handoffPath,
expected.handoff,
reason
).catch((error) => {
process.stderr.write(`[serve] could not record update handoff failure: ${String(error)}\n`)
})
return true
}
const rejectReplacement = (reason: string): void => {
if (!recordReplacementFailure(reason)) {
return
}
terminateChild()
}
const forwardSignal = (signal: NodeJS.Signals): void => {
child.kill(signal)
forceKillTimer ??= setTimeout(() => child.kill('SIGKILL'), 5000)
}
const handleMessage = (value: unknown): void => {
const message = parseServeSupervisorMessage(value)
if (!message || !expected || readiness !== 'pending') {
return
}
if (message.version !== expected.handoff.targetVersion) {
rejectReplacement(
`Replacement reported version ${message.version}; expected ${expected.handoff.targetVersion}.`
)
return
}
readiness = 'verified'
if (readyTimer) {
clearTimeout(readyTimer)
readyTimer = null
}
stateWrite = completeServeUpdateHandoff(
expected.handoffPath,
expected.handoff,
message.runtimeId
).catch((error) => {
readiness = 'failed'
process.stderr.write(`[serve] could not complete update handoff: ${String(error)}\n`)
terminateChild()
})
}
const cleanup = (): void => {
process.off('SIGINT', forwardSignal)
process.off('SIGTERM', forwardSignal)
if (typeof child.off === 'function') {
child.off('message', handleMessage)
}
if (forceKillTimer) {
clearTimeout(forceKillTimer)
}
if (readyTimer) {
clearTimeout(readyTimer)
}
}
process.on('SIGINT', forwardSignal)
process.on('SIGTERM', forwardSignal)
if (typeof child.on === 'function') {
child.on('message', handleMessage)
}
if (expected) {
readyTimer = setTimeout(() => {
rejectReplacement(
`Replacement did not report serving version ${expected.handoff.targetVersion} within ${SERVE_REPLACEMENT_READY_TIMEOUT_MS}ms.`
)
}, SERVE_REPLACEMENT_READY_TIMEOUT_MS)
}
const handleExit = (code: number | null, signal: NodeJS.Signals | null): void => {
cleanup()
void stateWrite.then(() => resolveWait({ code, signal, readiness }))
}
child.once('error', (error) => {
recordReplacementFailure(`Could not start the replacement process: ${String(error)}`)
cleanup()
child.off('exit', handleExit)
// Why: the LaunchAgent may restart this parent immediately, so durable failure must precede process rejection.
void stateWrite.then(() => reject(error))
})
child.once('exit', handleExit)
})
}
export async function readServeUpdateHandoff(
handoffPath: string
): Promise<ServeUpdateHandoffState | null> {
try {
return parseServeUpdateHandoffState(JSON.parse(await readFile(handoffPath, 'utf8')))
} catch {
return null
}
}
export function readServeUpdateHandoffSync(handoffPath: string): ServeUpdateHandoffState | null {
try {
return parseServeUpdateHandoffState(JSON.parse(readFileSync(handoffPath, 'utf8')))
} catch {
return null
}
}
export async function clearServeUpdateHandoff(handoffPath: string): Promise<void> {
await unlink(handoffPath).catch(() => undefined)
}
export async function completeServeUpdateHandoff(
handoffPath: string,
state: InstallRequestedHandoff,
runtimeId: string
): Promise<void> {
await writeServeUpdateHandoffState(handoffPath, {
...state,
phase: 'completed',
runtimeId
})
await clearServeUpdateHandoff(handoffPath)
}
export async function recordServeUpdateHandoffFailure(
handoffPath: string,
state: Extract<ServeUpdateHandoffState, { phase: 'install-requested' }>,
reason: string
): Promise<void> {
const failedState: ServeUpdateHandoffState = { ...state, phase: 'failed', reason }
await writeServeUpdateHandoffState(handoffPath, failedState)
process.stderr.write(`[serve] update handoff failed: ${reason}\n`)
}
async function writeServeUpdateHandoffState(
handoffPath: string,
state: ServeUpdateHandoffState
): Promise<void> {
const temporaryPath = `${handoffPath}.${process.pid}.tmp`
await writeFile(temporaryPath, JSON.stringify(state), { mode: 0o600 })
await rename(temporaryPath, handoffPath)
}