Showing the changes to apps/server/src/cloud/bootService.ts (1 of 12 files). Show all
Unified · Split
| @@ -11,16 +11,19 @@ import * as Schema from "effect/Schema"; · 10 unmodified lines | |||
| 11 | 11 | ||
| 12 | import { | 12 | import { |
| 13 | HostProcessArguments, | 13 | HostProcessArguments, |
| 14 | HostProcessEnvironment, | ||
| 14 | HostProcessExecutablePath, | 15 | HostProcessExecutablePath, |
| 15 | HostProcessPlatform, | 16 | HostProcessPlatform, |
| 17 | HostProcessUserId, | ||
| 16 | } from "@t3tools/shared/hostProcess"; | 18 | } from "@t3tools/shared/hostProcess"; |
| 17 | 19 | ||
| 20 | import { writeFileStringAtomically, writeSymbolicLinkAtomically } from "../atomicWrite.ts"; | ||
| 18 | import * as ProcessRunner from "../processRunner.ts"; | 21 | import * as ProcessRunner from "../processRunner.ts"; |
| 19 | import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts"; | 22 | import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts"; |
| 20 | 23 | ||
| 21 | /** | 24 | /** |
| 22 | * Installs T3 Code as a per-user boot service. Linux-only for now: systemd | 25 | * Installs T3 Code as a per-user background service: systemd + linger on |
| 23 | * user unit + loginctl enable-linger. The service runs a stable or pinned | 26 | * Linux, or a LaunchAgent on macOS. The service runs a stable or pinned |
| 24 | * runtime — never an ephemeral `npx t3` cache whose eviction could break | 27 | * runtime — never an ephemeral `npx t3` cache whose eviction could break |
| 25 | * startup. | 28 | * startup. |
| 26 | */ | 29 | */ |
| @@ -29,6 +32,8 @@ const BOOT_SERVICE_NAME = "t3code"; · 2 unmodified lines | |||
| 29 | 32 | ||
| 30 | export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`; | 33 | export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`; |
| 31 | export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT"; | 34 | export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT"; |
| 35 | export const BOOT_SERVICE_LAUNCH_AGENT_LABEL = "com.t3tools.t3code.server"; | ||
| 36 | export const BOOT_SERVICE_LAUNCH_AGENT_FILE = `${BOOT_SERVICE_LAUNCH_AGENT_LABEL}.plist`; | ||
| 32 | 37 | ||
| 33 | const EPHEMERAL_CACHE_SEGMENTS = [ | 38 | const EPHEMERAL_CACHE_SEGMENTS = [ |
| 34 | "/_npx/", // npx | 39 | "/_npx/", // npx |
| @@ -76,6 +81,39 @@ export interface BootServicePlan { · 41 unmodified lines | |||
| 76 | readonly baseDir: string; | 81 | readonly baseDir: string; |
| 77 | readonly logPath: string; | 82 | readonly logPath: string; |
| 78 | readonly unitPath: string; | 83 | readonly unitPath: string; |
| 84 | /** Captured for launchd, whose default PATH omits common CLI install locations. */ | ||
| 85 | readonly pathEnvironment?: string; | ||
| 86 | } | ||
| 87 | |||
| 88 | export interface LaunchAgentPaths { | ||
| 89 | readonly unitPath: string; | ||
| 90 | readonly activeRuntimeLinkPath: string; | ||
| 91 | readonly activeEntryPath: string; | ||
| 92 | readonly serviceTarget: string; | ||
| 93 | } | ||
| 94 | |||
| 95 | export function launchAgentPaths( | ||
| 96 | path: Path.Path, | ||
| 97 | homeDir: string, | ||
| 98 | baseDir: string, | ||
| 99 | userId: number, | ||
| 100 | ): LaunchAgentPaths { | ||
| 101 | const activeRuntimeLinkPath = path.join(baseDir, "runtime", "service", "current"); | ||
| 102 | return { | ||
| 103 | unitPath: path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_LAUNCH_AGENT_FILE), | ||
| 104 | activeRuntimeLinkPath, | ||
| 105 | activeEntryPath: path.join(activeRuntimeLinkPath, "node_modules", "t3", "dist", "bin.mjs"), | ||
| 106 | serviceTarget: `gui/${String(userId)}/${BOOT_SERVICE_LAUNCH_AGENT_LABEL}`, | ||
| 107 | }; | ||
| 108 | } | ||
| 109 | |||
| 110 | export function escapeLaunchdXml(value: string): string { | ||
| 111 | return value | ||
| 112 | .replaceAll("&", "&") | ||
| 113 | .replaceAll("<", "<") | ||
| 114 | .replaceAll(">", ">") | ||
| 115 | .replaceAll('"', """) | ||
| 116 | .replaceAll("'", "'"); | ||
| 79 | } | 117 | } |
| 80 | 118 | ||
| 81 | /** | 119 | /** |
| @@ -114,12 +152,61 @@ export function renderBootServiceUnit(plan: BootServicePlan): string { · 32 unmodified lines | |||
| 114 | ].join("\n"); | 152 | ].join("\n"); |
| 115 | } | 153 | } |
| 116 | 154 | ||
| 155 | /** | ||
| 156 | * LaunchAgents are loaded for a user's GUI session after login. KeepAlive | ||
| 157 | * restarts crashes, while the stable entry path lets remote updates switch | ||
| 158 | * exact runtimes without rewriting or unloading the plist from inside the | ||
| 159 | * process it owns. | ||
| 160 | */ | ||
| 161 | export function renderBootServiceLaunchAgent(plan: BootServicePlan): string { | ||
| 162 | const value = escapeLaunchdXml; | ||
| 163 | return [ | ||
| 164 | '<?xml version="1.0" encoding="UTF-8"?>', | ||
| 165 | '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">', | ||
| 166 | '<plist version="1.0">', | ||
| 167 | "<dict>", | ||
| 168 | " <key>Label</key>", | ||
| 169 | ` <string>${BOOT_SERVICE_LAUNCH_AGENT_LABEL}</string>`, | ||
| 170 | " <key>ProgramArguments</key>", | ||
| 171 | " <array>", | ||
| 172 | ` <string>${value(plan.nodePath)}</string>`, | ||
| 173 | ` <string>${value(plan.t3EntryPath)}</string>`, | ||
| 174 | " <string>serve</string>", | ||
| 175 | " </array>", | ||
| 176 | " <key>EnvironmentVariables</key>", | ||
| 177 | " <dict>", | ||
| 178 | " <key>T3CODE_HOME</key>", | ||
| 179 | ` <string>${value(plan.baseDir)}</string>`, | ||
| 180 | ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`, | ||
| 181 | ` <string>${BOOT_SERVICE_LAUNCH_AGENT_LABEL}</string>`, | ||
| 182 | ...(plan.pathEnvironment === undefined | ||
| 183 | ? [] | ||
| 184 | : [" <key>PATH</key>", ` <string>${value(plan.pathEnvironment)}</string>`]), | ||
| 185 | " </dict>", | ||
| 186 | " <key>WorkingDirectory</key>", | ||
| 187 | ` <string>${value(plan.baseDir)}</string>`, | ||
| 188 | " <key>RunAtLoad</key>", | ||
| 189 | " <true/>", | ||
| 190 | " <key>KeepAlive</key>", | ||
| 191 | " <true/>", | ||
| 192 | " <key>ThrottleInterval</key>", | ||
| 193 | " <integer>5</integer>", | ||
| 194 | " <key>StandardOutPath</key>", | ||
| 195 | ` <string>${value(plan.logPath)}</string>`, | ||
| 196 | " <key>StandardErrorPath</key>", | ||
| 197 | ` <string>${value(plan.logPath)}</string>`, | ||
| 198 | "</dict>", | ||
| 199 | "</plist>", | ||
| 200 | "", | ||
| 201 | ].join("\n"); | ||
| 202 | } | ||
| 203 | |||
| 117 | export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()( | 204 | export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()( |
| 118 | "BootServiceUnsupportedError", | 205 | "BootServiceUnsupportedError", |
| 119 | { platform: Schema.String }, | 206 | { platform: Schema.String }, |
| 120 | ) { | 207 | ) { |
| 121 | override get message(): string { | 208 | override get message(): string { |
| 122 | return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`; | 209 | return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`; |
| 123 | } | 210 | } |
| 124 | } | 211 | } |
| 125 | 212 | ||
| @@ -134,9 +221,13 @@ export class BootServiceCommandError extends Schema.TaggedErrorClass<BootService · 8 unmodified lines | |||
| 134 | }, | 221 | }, |
| 135 | ) { | 222 | ) { |
| 136 | override get message(): string { | 223 | override get message(): string { |
| 137 | return this.exitCode === undefined | 224 | const detail = |
| 138 | ? `Background setup failed while ${this.step}.` | 225 | this.exitCode === undefined |
| 139 | : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`; | 226 | ? `Background setup failed while ${this.step}.` |
| 227 | : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`; | ||
| 228 | return this.step.includes("LaunchAgent") | ||
| 229 | ? `${detail} If macOS blocked the background item, allow T3 Code in System Settings > General > Login Items & Extensions.` | ||
| 230 | : detail; | ||
| 140 | } | 231 | } |
| 141 | } | 232 | } |
| 142 | 233 | ||
| @@ -157,7 +248,7 @@ export type BootServiceError = · 14 unmodified lines | |||
| 157 | export interface BootServiceStatus { | 248 | export interface BootServiceStatus { |
| 158 | readonly supported: boolean; | 249 | readonly supported: boolean; |
| 159 | readonly installed: boolean; | 250 | readonly installed: boolean; |
| 160 | /** False when the installed unit no longer matches what install would write. */ | 251 | /** False when the installed service no longer matches what install would write. */ |
| 161 | readonly current: boolean; | 252 | readonly current: boolean; |
| 162 | readonly unitPath: string; | 253 | readonly unitPath: string; |
| 163 | readonly logPath: string; | 254 | readonly logPath: string; |
| @@ -166,7 +257,7 @@ export interface BootServiceStatus { · 2 unmodified lines | |||
| 166 | export class BootService extends Context.Service< | 257 | export class BootService extends Context.Service< |
| 167 | BootService, | 258 | BootService, |
| 168 | { | 259 | { |
| 169 | /** Installs the pinned runtime + unit, enables linger, starts the service. */ | 260 | /** Installs the runtime + user service and starts it immediately. */ |
| 170 | readonly install: Effect.Effect<BootServicePlan, BootServiceError>; | 261 | readonly install: Effect.Effect<BootServicePlan, BootServiceError>; |
| 171 | /** | 262 | /** |
| 172 | * Stops and removes the unit; leaves the pinned runtime for reuse. | 263 | * Stops and removes the unit; leaves the pinned runtime for reuse. |
| @@ -192,23 +283,37 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 19 unmodified lines | |||
| 192 | const hostArguments = yield* HostProcessArguments; | 283 | const hostArguments = yield* HostProcessArguments; |
| 193 | const host = input.host ?? { | 284 | const host = input.host ?? { |
| 194 | execPath: hostExecPath, | 285 | execPath: hostExecPath, |
| 195 | // When running the packed CLI this is dist/bin.mjs; when stable (global | 286 | // When running the packed CLI this is dist/bin.mjs. Linux can reuse a |
| 196 | // install, repo checkout) the boot service runs this same artifact. | 287 | // stable global install or checkout; macOS pins the exact CLI version. |
| 197 | cliEntryPath: hostArguments[1] ?? "", | 288 | cliEntryPath: hostArguments[1] ?? "", |
| 198 | }; | 289 | }; |
| 199 | const platform = yield* HostProcessPlatform; | 290 | const platform = yield* HostProcessPlatform; |
| 291 | const hostEnvironment = yield* HostProcessEnvironment; | ||
| 292 | const userId = yield* HostProcessUserId; | ||
| 200 | const homeDir = yield* Config.string("HOME").pipe(Config.withDefault("")); | 293 | const homeDir = yield* Config.string("HOME").pipe(Config.withDefault("")); |
| 201 | const fs = yield* FileSystem.FileSystem; | 294 | const fs = yield* FileSystem.FileSystem; |
| 202 | const path = yield* Path.Path; | 295 | const path = yield* Path.Path; |
| 203 | const runner = yield* ProcessRunner.ProcessRunner; | 296 | const runner = yield* ProcessRunner.ProcessRunner; |
| 204 | 297 | ||
| 205 | const unitDir = path.join(homeDir, ".config", "systemd", "user"); | 298 | const systemdUnitDir = path.join(homeDir, ".config", "systemd", "user"); |
| 206 | const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE); | 299 | const systemdUnitPath = path.join(systemdUnitDir, BOOT_SERVICE_UNIT_FILE); |
| 300 | const launchAgent = | ||
| 301 | userId === null ? null : launchAgentPaths(path, homeDir, input.baseDir, userId); | ||
| 302 | const unitDir = | ||
| 303 | platform === "darwin" && launchAgent !== null | ||
| 304 | ? path.dirname(launchAgent.unitPath) | ||
| 305 | : systemdUnitDir; | ||
| 306 | const unitPath = | ||
| 307 | platform === "darwin" && launchAgent !== null ? launchAgent.unitPath : systemdUnitPath; | ||
| 207 | const logPath = path.join(input.logsDir, "boot-service.log"); | 308 | const logPath = path.join(input.logsDir, "boot-service.log"); |
| 208 | const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion); | 309 | const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion); |
| 209 | 310 | ||
| 210 | const requireSystemdLinux = Effect.gen(function* () { | 311 | const requireSupportedPlatform = Effect.gen(function* () { |
| 211 | if (platform !== "linux" || homeDir === "") { | 312 | if ( |
| 313 | homeDir === "" || | ||
| 314 | (platform !== "linux" && platform !== "darwin") || | ||
| 315 | (platform === "darwin" && userId === null) | ||
| 316 | ) { | ||
| 212 | return yield* new BootServiceUnsupportedError({ platform }); | 317 | return yield* new BootServiceUnsupportedError({ platform }); |
| 213 | } | 318 | } |
| 214 | }); | 319 | }); |
| @@ -244,15 +349,24 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 29 unmodified lines | |||
| 244 | ); | 349 | ); |
| 245 | }); | 350 | }); |
| 246 | 351 | ||
| 352 | const runOptionalStep = Effect.fn("cloud.boot_service.run_optional_step")(function* ( | ||
| 353 | command: string, | ||
| 354 | args: ReadonlyArray<string>, | ||
| 355 | ) { | ||
| 356 | return yield* runner.run({ command, args }).pipe( | ||
| 357 | Effect.map((result) => result.code === 0), | ||
| 358 | Effect.orElseSucceed(() => false), | ||
| 359 | ); | ||
| 360 | }); | ||
| 361 | |||
| 247 | /** | 362 | /** |
| 248 | * Ensures plannedEntryPath exists before the unit points at it. A stable | 363 | * Ensures plannedRuntimeEntryPath exists before the service points at it. |
| 249 | * install (global bin, repo checkout) is used as-is; an ephemeral cache | 364 | * macOS always gets an exact managed runtime so the LaunchAgent can use a |
| 250 | * entry is replaced by `npm install --prefix`-ing the exact running | 365 | * stable symlink across remote updates. Linux can reuse a stable global or |
| 251 | * version into <baseDir>/runtime/versions/<v>. A real install (not a copy | 366 | * checkout entry; ephemeral cache entries are pinned on both platforms. |
| 252 | * of bin.mjs) because t3 ships native deps like node-pty. | ||
| 253 | */ | 367 | */ |
| 254 | const ensurePinnedRuntime = Effect.gen(function* () { | 368 | const ensurePinnedRuntime = Effect.gen(function* () { |
| 255 | if (!isEphemeralCacheEntry(host.cliEntryPath)) { | 369 | if (platform !== "darwin" && !isEphemeralCacheEntry(host.cliEntryPath)) { |
| 256 | return; | 370 | return; |
| 257 | } | 371 | } |
| 258 | yield* ensurePinnedRuntimeInstalled({ | 372 | yield* ensurePinnedRuntimeInstalled({ |
| @@ -286,21 +400,44 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 27 unmodified lines | |||
| 286 | ); | 400 | ); |
| 287 | }); | 401 | }); |
| 288 | 402 | ||
| 289 | // Where the unit will point: derivable without touching the network, so | 403 | // Where the service definition will point; install materializes it first. |
| 290 | // status can compare units purely; install materializes it first. | 404 | const plannedRuntimeEntryPath = |
| 291 | const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath) | 405 | platform === "darwin" || isEphemeralCacheEntry(host.cliEntryPath) |
| 292 | ? runtimePaths.entryPath | 406 | ? runtimePaths.entryPath |
| 293 | : host.cliEntryPath; | 407 | : host.cliEntryPath; |
| 408 | const plannedEntryPath = | ||
| 409 | platform === "darwin" && launchAgent !== null | ||
| 410 | ? launchAgent.activeEntryPath | ||
| 411 | : plannedRuntimeEntryPath; | ||
| 294 | const plan: BootServicePlan = { | 412 | const plan: BootServicePlan = { |
| 295 | nodePath: host.execPath, | 413 | nodePath: host.execPath, |
| 296 | t3EntryPath: plannedEntryPath, | 414 | t3EntryPath: plannedEntryPath, |
| 297 | baseDir: input.baseDir, | 415 | baseDir: input.baseDir, |
| 298 | logPath, | 416 | logPath, |
| 299 | unitPath, | 417 | unitPath, |
| 418 | pathEnvironment: hostEnvironment.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin", | ||
| 419 | }; | ||
| 420 | |||
| 421 | const writeUnit = (contents: string) => | ||
| 422 | writeFileStringAtomically({ filePath: unitPath, contents }).pipe( | ||
| 423 | Effect.provideService(FileSystem.FileSystem, fs), | ||
| 424 | Effect.provideService(Path.Path, path), | ||
| 425 | ); | ||
| 426 | const writeActiveRuntimeLink = (targetPath: string) => { | ||
| 427 | if (launchAgent === null) { | ||
| 428 | return Effect.void; | ||
| 429 | } | ||
| 430 | return writeSymbolicLinkAtomically({ | ||
| 431 | linkPath: launchAgent.activeRuntimeLinkPath, | ||
| 432 | targetPath, | ||
| 433 | }).pipe( | ||
| 434 | Effect.provideService(FileSystem.FileSystem, fs), | ||
| 435 | Effect.provideService(Path.Path, path), | ||
| 436 | ); | ||
| 300 | }; | 437 | }; |
| 301 | 438 | ||
| 302 | const install: BootService["Service"]["install"] = Effect.gen(function* () { | 439 | const install: BootService["Service"]["install"] = Effect.gen(function* () { |
| 303 | yield* requireSystemdLinux; | 440 | yield* requireSupportedPlatform; |
| 304 | yield* fs | 441 | yield* fs |
| 305 | .makeDirectory(input.logsDir, { recursive: true }) | 442 | .makeDirectory(input.logsDir, { recursive: true }) |
| 306 | .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); | 443 | .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); |
| @@ -316,15 +453,54 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 9 unmodified lines | |||
| 316 | Effect.mapError((cause) => new BootServiceInstallError({ cause })), | 453 | Effect.mapError((cause) => new BootServiceInstallError({ cause })), |
| 317 | ); | 454 | ); |
| 318 | 455 | ||
| 456 | const previousRuntimeLink = | ||
| 457 | platform === "darwin" && launchAgent !== null | ||
| 458 | ? yield* fs.exists(launchAgent.activeRuntimeLinkPath).pipe( | ||
| 459 | Effect.flatMap((exists) => | ||
| 460 | exists | ||
| 461 | ? fs.readLink(launchAgent.activeRuntimeLinkPath).pipe(Effect.map(Option.some)) | ||
| 462 | : Effect.succeed(Option.none<string>()), | ||
| 463 | ), | ||
| 464 | Effect.mapError((cause) => new BootServiceInstallError({ cause })), | ||
| 465 | ) | ||
| 466 | : Option.none<string>(); | ||
| 467 | |||
| 319 | yield* fs.makeDirectory(unitDir, { recursive: true }).pipe( | 468 | yield* fs.makeDirectory(unitDir, { recursive: true }).pipe( |
| 320 | Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))), | 469 | Effect.andThen( |
| 470 | platform === "darwin" | ||
| 471 | ? writeActiveRuntimeLink(runtimePaths.versionDir).pipe( | ||
| 472 | Effect.andThen(writeUnit(renderBootServiceLaunchAgent(plan))), | ||
| 473 | ) | ||
| 474 | : writeUnit(renderBootServiceUnit(plan)), | ||
| 475 | ), | ||
| 321 | Effect.mapError((cause) => new BootServiceInstallError({ cause })), | 476 | Effect.mapError((cause) => new BootServiceInstallError({ cause })), |
| 477 | Effect.tapError(() => rollbackFailedInstall(previousUnit, previousRuntimeLink)), | ||
| 322 | ); | 478 | ); |
| 323 | 479 | ||
| 324 | // If any activation step fails, remove the unit again: a leftover file | ||
| 325 | // would make service status report it as installed even though it was | ||
| 326 | // never enabled or lingered. | ||
| 327 | yield* Effect.gen(function* () { | 480 | yield* Effect.gen(function* () { |
| 481 | if (platform === "darwin" && launchAgent !== null && userId !== null) { | ||
| 482 | const domain = `gui/${String(userId)}`; | ||
| 483 | // An explicit install repairs a background item the user previously | ||
| 484 | // disabled in System Settings. | ||
| 485 | yield* runStep("enabling the LaunchAgent", "/bin/launchctl", [ | ||
| 486 | "enable", | ||
| 487 | launchAgent.serviceTarget, | ||
| 488 | ]); | ||
| 489 | // bootout is expected to fail on first install. On repair it stops | ||
| 490 | // the old job before bootstrap loads the new definition. | ||
| 491 | yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]); | ||
| 492 | yield* runStep("loading the LaunchAgent", "/bin/launchctl", [ | ||
| 493 | "bootstrap", | ||
| 494 | domain, | ||
| 495 | unitPath, | ||
| 496 | ]); | ||
| 497 | yield* runStep("checking the LaunchAgent", "/bin/launchctl", [ | ||
| 498 | "print", | ||
| 499 | launchAgent.serviceTarget, | ||
| 500 | ]); | ||
| 501 | return; | ||
| 502 | } | ||
| 503 | |||
| 328 | yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]); | 504 | yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]); |
| 329 | yield* runStep("enabling the service", "systemctl", [ | 505 | yield* runStep("enabling the service", "systemctl", [ |
| 330 | "--user", | 506 | "--user", |
| @@ -344,7 +520,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 13 unmodified lines | |||
| 344 | // username argument: loginctl defaults to the calling user, which is | 520 | // username argument: loginctl defaults to the calling user, which is |
| 345 | // always right, while $USER can be stale (su without -l) or unset. | 521 | // always right, while $USER can be stale (su without -l) or unset. |
| 346 | yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]); | 522 | yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]); |
| 347 | }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit))); | 523 | }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit, previousRuntimeLink))); |
| 348 | 524 | ||
| 349 | return plan; | 525 | return plan; |
| 350 | }).pipe(Effect.withSpan("cloud.boot_service.install")); | 526 | }).pipe(Effect.withSpan("cloud.boot_service.install")); |
| @@ -356,9 +532,26 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 5 unmodified lines | |||
| 356 | // next lifecycle command misreports the state. | 532 | // next lifecycle command misreports the state. |
| 357 | const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* ( | 533 | const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* ( |
| 358 | previousUnit: Option.Option<string>, | 534 | previousUnit: Option.Option<string>, |
| 535 | previousRuntimeLink: Option.Option<string>, | ||
| 359 | ) { | 536 | ) { |
| 537 | if (platform === "darwin" && launchAgent !== null && userId !== null) { | ||
| 538 | yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]); | ||
| 539 | if (Option.isSome(previousRuntimeLink)) { | ||
| 540 | yield* writeActiveRuntimeLink(previousRuntimeLink.value).pipe(Effect.ignore); | ||
| 541 | } else { | ||
| 542 | yield* fs.remove(launchAgent.activeRuntimeLinkPath).pipe(Effect.ignore); | ||
| 543 | } | ||
| 544 | if (Option.isSome(previousUnit)) { | ||
| 545 | yield* writeUnit(previousUnit.value).pipe(Effect.ignore); | ||
| 546 | yield* runOptionalStep("/bin/launchctl", ["bootstrap", `gui/${String(userId)}`, unitPath]); | ||
| 547 | } else { | ||
| 548 | yield* fs.remove(unitPath).pipe(Effect.ignore); | ||
| 549 | } | ||
| 550 | return; | ||
| 551 | } | ||
| 552 | |||
| 360 | if (Option.isSome(previousUnit)) { | 553 | if (Option.isSome(previousUnit)) { |
| 361 | yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore); | 554 | yield* writeUnit(previousUnit.value).pipe(Effect.ignore); |
| 362 | } else { | 555 | } else { |
| 363 | yield* runStep("cleaning up the service", "systemctl", [ | 556 | yield* runStep("cleaning up the service", "systemctl", [ |
| 364 | "--user", | 557 | "--user", |
| @@ -381,13 +574,22 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 16 unmodified lines | |||
| 381 | }); | 574 | }); |
| 382 | 575 | ||
| 383 | const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () { | 576 | const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () { |
| 384 | yield* requireSystemdLinux; | 577 | yield* requireSupportedPlatform; |
| 385 | const exists = yield* fs | 578 | const exists = yield* fs |
| 386 | .exists(unitPath) | 579 | .exists(unitPath) |
| 387 | .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); | 580 | .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); |
| 388 | if (!exists) { | 581 | if (!exists) { |
| 389 | return false; | 582 | return false; |
| 390 | } | 583 | } |
| 584 | if (platform === "darwin" && launchAgent !== null) { | ||
| 585 | // A disabled or already-unloaded agent returns non-zero from bootout; | ||
| 586 | // the plist is still safe to remove and is the durable source of truth. | ||
| 587 | yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]); | ||
| 588 | yield* fs | ||
| 589 | .remove(unitPath) | ||
| 590 | .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); | ||
| 591 | return true; | ||
| 592 | } | ||
| 391 | yield* runStep("stopping the service", "systemctl", [ | 593 | yield* runStep("stopping the service", "systemctl", [ |
| 392 | "--user", | 594 | "--user", |
| 393 | "disable", | 595 | "disable", |
| @@ -402,7 +604,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 8 unmodified lines | |||
| 402 | }).pipe(Effect.withSpan("cloud.boot_service.uninstall")); | 604 | }).pipe(Effect.withSpan("cloud.boot_service.uninstall")); |
| 403 | 605 | ||
| 404 | const status: BootService["Service"]["status"] = Effect.gen(function* () { | 606 | const status: BootService["Service"]["status"] = Effect.gen(function* () { |
| 405 | if (platform !== "linux" || homeDir === "") { | 607 | if ( |
| 608 | homeDir === "" || | ||
| 609 | (platform !== "linux" && platform !== "darwin") || | ||
| 610 | (platform === "darwin" && launchAgent === null) | ||
| 611 | ) { | ||
| 406 | return { supported: false, installed: false, current: false, unitPath, logPath }; | 612 | return { supported: false, installed: false, current: false, unitPath, logPath }; |
| 407 | } | 613 | } |
| 408 | const unitExists = yield* fs.exists(unitPath); | 614 | const unitExists = yield* fs.exists(unitPath); |
| @@ -410,11 +616,25 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 1 unmodified line | |||
| 410 | return { supported: true, installed: false, current: false, unitPath, logPath }; | 616 | return { supported: true, installed: false, current: false, unitPath, logPath }; |
| 411 | } | 617 | } |
| 412 | const unit = yield* fs.readFileString(unitPath); | 618 | const unit = yield* fs.readFileString(unitPath); |
| 619 | const entryExists = yield* fs.exists(plannedEntryPath); | ||
| 620 | if (platform === "darwin" && launchAgent !== null) { | ||
| 621 | const activeRuntimeIsCurrent = yield* fs.readLink(launchAgent.activeRuntimeLinkPath).pipe( | ||
| 622 | Effect.map((target) => target === runtimePaths.versionDir), | ||
| 623 | Effect.orElseSucceed(() => false), | ||
| 624 | ); | ||
| 625 | const loaded = yield* runOptionalStep("/bin/launchctl", ["print", launchAgent.serviceTarget]); | ||
| 626 | const current = | ||
| 627 | unit === renderBootServiceLaunchAgent(plan) && | ||
| 628 | entryExists && | ||
| 629 | activeRuntimeIsCurrent && | ||
| 630 | loaded; | ||
| 631 | return { supported: true, installed: true, current, unitPath, logPath }; | ||
| 632 | } | ||
| 633 | |||
| 413 | // A unit is current only if it matches what install would write now (an | 634 | // A unit is current only if it matches what install would write now (an |
| 414 | // older CLI wrote a different runtime/node path) AND the entry point it | 635 | // older CLI wrote a different runtime/node path) AND the entry point it |
| 415 | // references still exists (a pinned runtime under ~/.t3 can be deleted to | 636 | // references still exists (a pinned runtime under ~/.t3 can be deleted to |
| 416 | // reclaim space). Either mismatch makes connect offer a repair. | 637 | // reclaim space). Either mismatch makes connect offer a repair. |
| 417 | const entryExists = yield* fs.exists(plannedEntryPath); | ||
| 418 | const current = unit === renderBootServiceUnit(plan) && entryExists; | 638 | const current = unit === renderBootServiceUnit(plan) && entryExists; |
| 419 | return { supported: true, installed: true, current, unitPath, logPath }; | 639 | return { supported: true, installed: true, current, unitPath, logPath }; |
| 420 | }).pipe( | 640 | }).pipe( |