From 788a34842157b43691d57236b60fe2c4f33db045 Mon Sep 17 00:00:00 2001 From: feldrok Date: Fri, 20 Nov 2026 14:22:46 -0300 Subject: [PATCH 1/4] fix(cli): preserve the relay tunnel during service updates --- apps/server/src/cloud/bootService.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index d624e02c7ecfb..d0ebe4e9f3546 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -1,3 +1,4 @@ +import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Config from "effect/Config"; import * as Context from "effect/Context"; @@ -1336,7 +1337,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // restart while this launcher keeps running, then the restart is handed to the manager. const handOff = installed && start && runningInsideService && manager.kind === "schtasks"; if (installed && start && !handOff) { - yield* runSteps(manager.stop); + const marker = path.join(input.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); + // The running server consumes this marker during shutdown to keep its relay tunnel. + yield* fs.writeFileString(marker, "", { mode: 0o600 }).pipe( + Effect.mapError((cause) => new BootServiceInstallError({ cause })), + ); + yield* runSteps(manager.stop).pipe( + Effect.ensuring(fs.remove(marker, { force: true }).pipe(Effect.ignore)), + ); } // State first, then unit. The launcher acquires only one at a time, and a From acd9db43a012b39da80618f83e4c1edeee28d73c Mon Sep 17 00:00:00 2001 From: feldrok Date: Fri, 20 Nov 2026 14:31:09 -0300 Subject: [PATCH 2/4] fix(cli): mark deferred and handed-off service restarts --- apps/server/src/cloud/bootService.test.ts | 26 +++++++++++++++ apps/server/src/cloud/bootService.ts | 39 ++++++++++++++++------- 2 files changed, 54 insertions(+), 11 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 523f495a5d6e9..146a862cf0538 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -1,3 +1,4 @@ +import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- Cross-process launcher contention uses real filesystem leases and IPC barriers. import * as NodeChildProcess from "node:child_process"; import * as NodeSqlite from "node:sqlite"; @@ -204,6 +205,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( yield* fs.writeFileString(runtime.entryPath, "#!/bin/sh\n"); yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n"); + const markersAtStop: boolean[] = []; const commands: string[] = []; const invocations: ProcessRunner.ProcessRunInput[] = []; const timeouts = new Map(); @@ -240,6 +242,11 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( ) { const command = `${input.command} ${input.args.join(" ")}`; commands.push(command); + if (command === "systemctl --user stop t3code.service") { + markersAtStop.push( + yield* fs.exists(path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE)), + ); + } invocations.push(input); timeouts.set(command, input.timeout); if (command === "systemctl --user reset-failed t3code.service") control.startLimitHit = false; @@ -403,12 +410,31 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( commands, invocations, timeouts, + markersAtStop, control, runtime, }; }); it.layer(NodeServices.layer)("boot service install", (it) => { + it.effect("keeps the relay marker through a service stop and cleans up after a failed stop", () => + Effect.gen(function* () { + const { service, fs, baseDir, control, markersAtStop } = yield* makeHarness(); + const path = yield* Path.Path; + const marker = path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); + yield* service.install(); + yield* service.restart(); + expect(markersAtStop.at(-1)).toBe(true); + expect(yield* fs.exists(marker)).toBe(false); + + control.failCommand = "systemctl --user stop t3code.service"; + const error = yield* service.restart().pipe(Effect.flip); + expect(error._tag).toBe("BootServiceCommandError"); + expect(markersAtStop.slice(-2)).toEqual([true, true]); + expect(yield* fs.exists(marker)).toBe(false); + }), + ); + it.effect( "fails before installing files or validating a runtime when lingering needs an administrator", () => diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index d0ebe4e9f3546..94087618e0335 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -1212,6 +1212,30 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { return problems; }); + const restartMarker = path.join(input.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); + const markRestart = fs.writeFileString(restartMarker, "", { mode: 0o600 }).pipe( + Effect.as(true), + Effect.catch((cause) => + Effect.logWarning("Could not mark the service restart to preserve its relay tunnel", { + cause, + }).pipe(Effect.as(false)), + ), + ); + const clearRestartMarker = fs.remove(restartMarker, { force: true }).pipe(Effect.ignore); + const stopForRestart = (steps: ReadonlyArray) => + markRestart.pipe( + Effect.flatMap((marked) => + runSteps(steps).pipe(Effect.ensuring(marked ? clearRestartMarker : Effect.void)), + ), + ); + // The manager may return before shutdown. Let the server consume the marker. + const handOffRestart = (steps: ReadonlyArray) => + markRestart.pipe( + Effect.flatMap((marked) => + runSteps(steps).pipe(Effect.tapError(() => (marked ? clearRestartMarker : Effect.void))), + ), + ); + const install = Effect.fn("cloud.boot_service.install")(function* (options?: { readonly allowDowngrade?: boolean; readonly start?: boolean; @@ -1337,14 +1361,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // restart while this launcher keeps running, then the restart is handed to the manager. const handOff = installed && start && runningInsideService && manager.kind === "schtasks"; if (installed && start && !handOff) { - const marker = path.join(input.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); - // The running server consumes this marker during shutdown to keep its relay tunnel. - yield* fs.writeFileString(marker, "", { mode: 0o600 }).pipe( - Effect.mapError((cause) => new BootServiceInstallError({ cause })), - ); - yield* runSteps(manager.stop).pipe( - Effect.ensuring(fs.remove(marker, { force: true }).pipe(Effect.ignore)), - ); + yield* stopForRestart(manager.stop); } // State first, then unit. The launcher acquires only one at a time, and a @@ -1423,7 +1440,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { Effect.tap( Effect.gen(function* () { if (handOff) { - yield* runSteps(manager.handoff ?? []); + yield* handOffRestart(manager.handoff ?? []); } else if (start) { yield* runSteps(manager.activate); yield* withSelectionLock( @@ -1465,10 +1482,10 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // Writes no state, and the launcher lets an update transition in flight // finish before the queued stop tears it down. if (runningInsideService && manager.handoff !== undefined) { - yield* runSteps(manager.handoff); + yield* handOffRestart(manager.handoff); return "queued" as const; } - yield* runSteps(manager.stop); + yield* stopForRestart(manager.stop); yield* runSteps(manager.activate).pipe( Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)), ); From 8f090e024c6a58e6125ac4e48d7dbe0e94c1a8de Mon Sep 17 00:00:00 2001 From: feldrok Date: Fri, 20 Nov 2026 14:42:28 -0300 Subject: [PATCH 3/4] test(cli): exercise relay markers through service handoffs --- apps/server/src/cloud/bootService.test.ts | 72 +++++++++++++++++------ 1 file changed, 55 insertions(+), 17 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 146a862cf0538..b4608dd414010 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -242,7 +242,10 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( ) { const command = `${input.command} ${input.args.join(" ")}`; commands.push(command); - if (command === "systemctl --user stop t3code.service") { + if ( + command === "systemctl --user stop t3code.service" || + (input.command === "schtasks" && input.args[0] === "/End") + ) { markersAtStop.push( yield* fs.exists(path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE)), ); @@ -417,22 +420,41 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( }); it.layer(NodeServices.layer)("boot service install", (it) => { - it.effect("keeps the relay marker through a service stop and cleans up after a failed stop", () => - Effect.gen(function* () { - const { service, fs, baseDir, control, markersAtStop } = yield* makeHarness(); - const path = yield* Path.Path; - const marker = path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); - yield* service.install(); - yield* service.restart(); - expect(markersAtStop.at(-1)).toBe(true); - expect(yield* fs.exists(marker)).toBe(false); + it.effect( + "marks immediate and deferred service restarts without blocking on a marker error", + () => + Effect.gen(function* () { + const { service, fs, baseDir, control, markersAtStop, makeService } = yield* makeHarness(); + const path = yield* Path.Path; + const marker = path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); + yield* service.install(); + expect(markersAtStop).toEqual([]); + expect(yield* fs.exists(marker)).toBe(false); - control.failCommand = "systemctl --user stop t3code.service"; - const error = yield* service.restart().pipe(Effect.flip); - expect(error._tag).toBe("BootServiceCommandError"); - expect(markersAtStop.slice(-2)).toEqual([true, true]); - expect(yield* fs.exists(marker)).toBe(false); - }), + const newer = yield* makeService(undefined, "1.2.4"); + yield* newer.install(); + expect(markersAtStop).toEqual([true]); + expect(yield* fs.exists(marker)).toBe(false); + + const next = yield* makeService(undefined, "1.2.5"); + yield* next.install({ start: false }); + expect(markersAtStop).toEqual([true]); + expect(yield* fs.exists(marker)).toBe(false); + yield* next.restart; + expect(markersAtStop).toEqual([true, true]); + expect(yield* fs.exists(marker)).toBe(false); + + control.failCommand = "systemctl --user stop t3code.service"; + const error = yield* next.restart.pipe(Effect.flip); + expect(error._tag).toBe("BootServiceCommandError"); + expect(markersAtStop).toEqual([true, true, true]); + expect(yield* fs.exists(marker)).toBe(false); + + control.failCommand = undefined; + yield* fs.makeDirectory(marker); + expect(yield* next.restart).toBe("restarted"); + expect((yield* fs.stat(marker)).type).toBe("Directory"); + }), ); it.effect( @@ -1328,6 +1350,7 @@ process.disconnect(); const { service, fs, statePath, commands, control, makeService } = yield* makeHarness(); const plan = yield* service.install(); const state = yield* fs.readFileString(statePath); + const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`; const marker = `${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`; yield* fs.writeFileString(marker, "1.2.3\n"); const inside = yield* makeService(undefined, "1.2.3", undefined, true); @@ -1338,6 +1361,7 @@ process.disconnect(); expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 }); expect(commands).toEqual(["systemctl --user daemon-reload"]); expect(control.active).toBe(true); + expect(yield* fs.exists(relayMarker)).toBe(false); control.failCommand = undefined; commands.length = 0; @@ -1349,6 +1373,7 @@ process.disconnect(); "systemctl --user restart --no-block t3code.service", ]); expect(outcome).toBe("queued"); + expect(yield* fs.exists(relayMarker)).toBe(true); expect(yield* fs.readFileString(statePath)).toBe(state); expect(yield* fs.readFileString(marker)).toBe("1.2.3\n"); }), @@ -1558,9 +1583,11 @@ process.disconnect(); it.effect("hands an in-service install and restart to Task Scheduler on Windows", () => Effect.gen(function* () { - const { service, fs, statePath, commands, makeService } = yield* makeHarness("win32"); + const { service, fs, statePath, commands, control, makeService, markersAtStop } = + yield* makeHarness("win32"); const plan = yield* service.install(); const inside = yield* makeService(undefined, "1.2.4", undefined, true); + const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`; const handoff = [ `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, "schtasks /End /TN t3code-PC-theo", @@ -1575,9 +1602,20 @@ process.disconnect(); yield* fs.readFileString(`${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`), ).toBe("1.2.4\n"); + expect(markersAtStop).toEqual([true]); + expect(yield* fs.exists(relayMarker)).toBe(true); + yield* fs.remove(relayMarker); + commands.length = 0; expect(yield* inside.restart).toBe("queued"); expect(commands).toEqual(handoff); + expect(markersAtStop).toEqual([true, true]); + expect(yield* fs.exists(relayMarker)).toBe(true); + yield* fs.remove(relayMarker); + + control.failCommand = handoff[0]; + expect((yield* inside.restart.pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); + expect(yield* fs.exists(relayMarker)).toBe(false); }), ); From 69eafd60b57aa7f6095e1ea1d7f4f33725e464b2 Mon Sep 17 00:00:00 2001 From: feldrok Date: Fri, 20 Nov 2026 14:48:48 -0300 Subject: [PATCH 4/4] fix(cli): scope relay markers to the restart handoff --- apps/server/src/cloud/bootService.test.ts | 74 +++++++++++++++-- apps/server/src/cloud/bootService.ts | 96 +++++++++++++---------- 2 files changed, 121 insertions(+), 49 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index b4608dd414010..ad926f2b5154d 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -206,11 +206,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n"); const markersAtStop: boolean[] = []; + const markersAtPreparation: boolean[] = []; const commands: string[] = []; const invocations: ProcessRunner.ProcessRunInput[] = []; const timeouts = new Map(); const control: { failCommand: string | undefined; + interruptCommand?: string; stateAfterStop?: string; /** `undefined` makes `loginctl show-user` fail, as when logind does not know the user. */ linger: string | undefined; @@ -242,14 +244,23 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( ) { const command = `${input.command} ${input.args.join(" ")}`; commands.push(command); + const marker = path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); if ( command === "systemctl --user stop t3code.service" || + command === "systemctl --user disable --now t3code.service" || + command === "systemctl --user restart --no-block t3code.service" || + command.startsWith("launchctl bootout --wait ") || (input.command === "schtasks" && input.args[0] === "/End") ) { - markersAtStop.push( - yield* fs.exists(path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE)), - ); + markersAtStop.push(yield* fs.exists(marker)); } + if ( + command === "systemctl --user daemon-reload" || + (input.command === "schtasks" && input.args[0] === "/Create") + ) { + markersAtPreparation.push(yield* fs.exists(marker)); + } + if (command === control.interruptCommand) return yield* Effect.interrupt; invocations.push(input); timeouts.set(command, input.timeout); if (command === "systemctl --user reset-failed t3code.service") control.startLimitHit = false; @@ -414,6 +425,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( invocations, timeouts, markersAtStop, + markersAtPreparation, control, runtime, }; @@ -1206,12 +1218,13 @@ process.disconnect(); it.effect("pauses only this home's running service for maintenance, even when it fails", () => Effect.gen(function* () { - const { service, commands, control, makeService } = yield* makeHarness(); + const { service, commands, control, makeService, markersAtStop } = yield* makeHarness(); yield* service.install(); const failure = yield* service .withStopped(Effect.failSync(() => (control.active ? "running" : "repair failed"))) .pipe(Effect.flip); expect(failure).toBe("repair failed"); + expect(markersAtStop).toEqual([false]); expect(control.active).toBe(true); control.failCommand = "systemctl --user stop t3code.service"; @@ -1347,7 +1360,16 @@ process.disconnect(); "queues an in-service restart without stopping the caller, even on handoff failure", () => Effect.gen(function* () { - const { service, fs, statePath, commands, control, makeService } = yield* makeHarness(); + const { + service, + fs, + statePath, + commands, + control, + makeService, + markersAtStop, + markersAtPreparation, + } = yield* makeHarness(); const plan = yield* service.install(); const state = yield* fs.readFileString(statePath); const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`; @@ -1362,6 +1384,22 @@ process.disconnect(); expect(commands).toEqual(["systemctl --user daemon-reload"]); expect(control.active).toBe(true); expect(yield* fs.exists(relayMarker)).toBe(false); + expect(markersAtPreparation.at(-1)).toBe(false); + expect(markersAtStop).toEqual([]); + + const queueCommand = "systemctl --user restart --no-block t3code.service"; + control.failCommand = queueCommand; + expect((yield* inside.restart.pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); + expect(markersAtStop).toEqual([true]); + expect(yield* fs.exists(relayMarker)).toBe(false); + + control.failCommand = undefined; + control.interruptCommand = queueCommand; + const interrupted = yield* inside.restart.pipe(Effect.forkScoped); + expect((yield* Fiber.await(interrupted))._tag).toBe("Failure"); + expect(markersAtStop).toEqual([true, true]); + expect(yield* fs.exists(relayMarker)).toBe(false); + delete control.interruptCommand; control.failCommand = undefined; commands.length = 0; @@ -1373,6 +1411,8 @@ process.disconnect(); "systemctl --user restart --no-block t3code.service", ]); expect(outcome).toBe("queued"); + expect(markersAtStop).toEqual([true, true, true]); + expect(markersAtPreparation).not.toContain(true); expect(yield* fs.exists(relayMarker)).toBe(true); expect(yield* fs.readFileString(statePath)).toBe(state); expect(yield* fs.readFileString(marker)).toBe("1.2.3\n"); @@ -1457,7 +1497,8 @@ process.disconnect(); it.effect("installs, reports current state, and uninstalls on macOS", () => Effect.gen(function* () { - const { service, fs, statePath, commands, timeouts, runtime } = yield* makeHarness("darwin"); + const { service, fs, statePath, commands, timeouts, runtime, markersAtStop } = + yield* makeHarness("darwin"); const path = yield* Path.Path; const plan = yield* service.install(); @@ -1480,7 +1521,13 @@ process.disconnect(); current: true, installedVersion: "1.2.3", }); + const relayMarker = path.join(plan.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); + expect(yield* service.restart).toBe("restarted"); + expect(markersAtStop).toEqual([true]); + expect(yield* fs.exists(relayMarker)).toBe(false); expect(yield* service.uninstall).toBe(true); + expect(markersAtStop).toEqual([true, false]); + expect(yield* fs.exists(relayMarker)).toBe(false); expect((yield* service.status).installed).toBe(false); expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false); // launchd can take 90s to bootout; the runner's 60s default could let bootstrap race it. @@ -1583,8 +1630,16 @@ process.disconnect(); it.effect("hands an in-service install and restart to Task Scheduler on Windows", () => Effect.gen(function* () { - const { service, fs, statePath, commands, control, makeService, markersAtStop } = - yield* makeHarness("win32"); + const { + service, + fs, + statePath, + commands, + control, + makeService, + markersAtStop, + markersAtPreparation, + } = yield* makeHarness("win32"); const plan = yield* service.install(); const inside = yield* makeService(undefined, "1.2.4", undefined, true); const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`; @@ -1613,9 +1668,12 @@ process.disconnect(); expect(yield* fs.exists(relayMarker)).toBe(true); yield* fs.remove(relayMarker); + expect(markersAtPreparation).not.toContain(true); control.failCommand = handoff[0]; expect((yield* inside.restart.pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); expect(yield* fs.exists(relayMarker)).toBe(false); + expect(markersAtPreparation.at(-1)).toBe(false); + expect(markersAtStop).toEqual([true, true]); }), ); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 94087618e0335..4f81ec8641931 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -286,6 +286,11 @@ export type BootServiceStep = { /** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */ const STOP_STEP_TIMEOUT = Duration.seconds(120); +interface BootServiceHandoff { + readonly prepare: ReadonlyArray; + readonly restart: ReadonlyArray; +} + export interface BootServiceManager { readonly kind: "systemd" | "launchd" | "schtasks"; readonly unitPath: string; @@ -294,7 +299,7 @@ export interface BootServiceManager { readonly activate: ReadonlyArray; readonly restart: ReadonlyArray; /** Queue a restart owned by the manager, since stopping would kill the caller. */ - readonly handoff?: ReadonlyArray; + readonly handoff?: BootServiceHandoff; readonly deactivate: ReadonlyArray; readonly finalize: ReadonlyArray; } @@ -365,14 +370,16 @@ function systemdManager(input: { args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE], }, ], - handoff: [ - ...prepareActivation, - { - step: "restarting the service", - command: "systemctl", - args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE], - }, - ], + handoff: { + prepare: prepareActivation, + restart: [ + { + step: "restarting the service", + command: "systemctl", + args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE], + }, + ], + }, deactivate: [ { step: "stopping the service", @@ -515,16 +522,18 @@ function schtasksManager(input: { ], // Ending the task kills only its console host; the launcher sees the console close and // stops gracefully while the replacement waits for its lock. - handoff: [ - register, - { - step: "ending the scheduled task", - command: "schtasks", - args: ["/End", ...task], - optional: true, - }, - { ...run, step: "restarting the service" }, - ], + handoff: { + prepare: [register], + restart: [ + { + step: "ending the scheduled task", + command: "schtasks", + args: ["/End", ...task], + optional: true, + }, + { ...run, step: "restarting the service" }, + ], + }, deactivate: [...stop, { step: "removing the scheduled task", run: input.steps.remove }], finalize: [], }; @@ -1212,29 +1221,28 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { return problems; }); + // Reuse the desktop marker so already released servers recognize the restart. const restartMarker = path.join(input.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE); const markRestart = fs.writeFileString(restartMarker, "", { mode: 0o600 }).pipe( Effect.as(true), - Effect.catch((cause) => + Effect.catch((error) => Effect.logWarning("Could not mark the service restart to preserve its relay tunnel", { - cause, + errorTag: error._tag, }).pipe(Effect.as(false)), ), ); - const clearRestartMarker = fs.remove(restartMarker, { force: true }).pipe(Effect.ignore); - const stopForRestart = (steps: ReadonlyArray) => - markRestart.pipe( - Effect.flatMap((marked) => - runSteps(steps).pipe(Effect.ensuring(marked ? clearRestartMarker : Effect.void)), - ), - ); - // The manager may return before shutdown. Let the server consume the marker. - const handOffRestart = (steps: ReadonlyArray) => - markRestart.pipe( - Effect.flatMap((marked) => - runSteps(steps).pipe(Effect.tapError(() => (marked ? clearRestartMarker : Effect.void))), - ), + const stopForRestart = (steps: ReadonlyArray, queued = false) => + Effect.acquireUseRelease( + markRestart, + () => runSteps(steps), + (marked, exit) => + // When a restart is queued, the outgoing server still needs to read the marker. + marked && (!queued || Exit.isFailure(exit)) + ? fs.remove(restartMarker, { force: true }).pipe(Effect.ignore) + : Effect.void, ); + const handOffRestart = (handoff: BootServiceHandoff) => + runSteps(handoff.prepare).pipe(Effect.andThen(stopForRestart(handoff.restart, true))); const install = Effect.fn("cloud.boot_service.install")(function* (options?: { readonly allowDowngrade?: boolean; @@ -1359,8 +1367,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { } // Task Scheduler restarts the task itself, so the files are written as for a deferred // restart while this launcher keeps running, then the restart is handed to the manager. - const handOff = installed && start && runningInsideService && manager.kind === "schtasks"; - if (installed && start && !handOff) { + const handoff = + installed && start && runningInsideService && manager.kind === "schtasks" + ? manager.handoff + : undefined; + if (installed && start && handoff === undefined) { yield* stopForRestart(manager.stop); } @@ -1421,7 +1432,10 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { 2, )}\n`, ); - if ((!start || handOff) && (currentlyInstalled || Option.isSome(previousStateText))) { + if ( + (!start || handoff !== undefined) && + (currentlyInstalled || Option.isSome(previousStateText)) + ) { const written = yield* fs.readFileString(statePath); if (serviceStateActiveVersion(written) !== input.cliVersion) { return yield* new BootServiceUpdatePendingError(); @@ -1439,8 +1453,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ).pipe( Effect.tap( Effect.gen(function* () { - if (handOff) { - yield* handOffRestart(manager.handoff ?? []); + if (handoff !== undefined) { + yield* handOffRestart(handoff); } else if (start) { yield* runSteps(manager.activate); yield* withSelectionLock( @@ -1460,12 +1474,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause, ), Effect.tapError(() => - installed && start && !handOff + installed && start && handoff === undefined ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void, ), ); - return handOff ? { ...installedPlan, handedOff: true } : installedPlan; + return handoff !== undefined ? { ...installedPlan, handedOff: true } : installedPlan; }); const restart: BootService["Service"]["restart"] = Effect.gen(function* () {