Repository navigation
fix(desktop): stop stale dev runners from crash-looping Electron #137
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7b30686
fix(desktop): stop stale dev runners from crash-looping Electron
yordis df6371a
fix(desktop): close the gaps that let a stale dev runner survive or loop
yordis 6bcfe32
fix(desktop): never let two runners share a checkout or stop one blindly
yordis 35c0148
fix(desktop): a runner exiting during takeover no longer blocks the n…
yordis 2b03baf
fix(desktop): an exiting runner no longer kills its replacement's app
yordis 33be296
fix(desktop): stop and reset fail when the runner survives SIGKILL
yordis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| #!/usr/bin/env bash | ||
| #MISE description="Stop this checkout's desktop dev runner and delete its Electron bundle so the next start rebuilds it" | ||
| #MISE depends=["dev:desktop:stop"] | ||
| set -euo pipefail | ||
| cd "$MISE_PROJECT_ROOT" | ||
| rm -rf apps/desktop/.electron-runtime | ||
| echo "[desktop-dev] removed apps/desktop/.electron-runtime" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| #!/usr/bin/env bash | ||
| #MISE description="Stop this checkout's desktop dev runner" | ||
| set -euo pipefail | ||
| cd "$MISE_PROJECT_ROOT" | ||
| node apps/desktop/scripts/stop-dev-electron.mjs |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| import * as NodeChildProcess from "node:child_process"; | ||
| import * as NodeFS from "node:fs"; | ||
| import * as NodeOS from "node:os"; | ||
| import * as NodePath from "node:path"; | ||
|
|
||
| import { decideTakeover, parseRunnerRecord } from "./dev-runner-guards.mjs"; | ||
|
|
||
| const stopGracePeriodMs = 4_000; | ||
| const stopPollIntervalMs = 100; | ||
| const maxClaimAttempts = 5; | ||
|
|
||
| // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime. | ||
| const hostPlatform = NodeOS.platform(); | ||
|
|
||
| function runnerRecordPath(desktopDir) { | ||
| return NodePath.join(desktopDir, ".electron-runtime", "runner.json"); | ||
| } | ||
|
|
||
| function readRunnerRecordText(desktopDir) { | ||
| try { | ||
| return NodeFS.readFileSync(runnerRecordPath(desktopDir), "utf8"); | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| function readRunnerRecord(desktopDir) { | ||
| const text = readRunnerRecordText(desktopDir); | ||
| return text === null ? null : parseRunnerRecord(text); | ||
| } | ||
|
|
||
| function readProcessCwd(pid) { | ||
| if (hostPlatform === "linux") { | ||
| try { | ||
| return NodeFS.readlinkSync(`/proc/${pid}/cwd`); | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
| const result = NodeChildProcess.spawnSync("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], { | ||
| encoding: "utf8", | ||
| }); | ||
| const line = result.stdout?.split("\n").find((entry) => entry.startsWith("n")); | ||
| return line ? line.slice(1) : null; | ||
| } | ||
|
|
||
| function inspectProcess(pid) { | ||
| const result = NodeChildProcess.spawnSync("ps", ["-p", String(pid), "-o", "command="], { | ||
| encoding: "utf8", | ||
| }); | ||
| const command = result.stdout?.trim(); | ||
| if (result.status !== 0 || !command) { | ||
| return null; | ||
| } | ||
| return { command, cwd: readProcessCwd(pid) }; | ||
| } | ||
|
|
||
| function isAlive(pid) { | ||
| try { | ||
| process.kill(pid, 0); | ||
| return true; | ||
| } catch (error) { | ||
| return error?.code === "EPERM"; | ||
| } | ||
| } | ||
|
|
||
| async function waitForExit(pid, timeoutMs) { | ||
| for (let waited = 0; waited < timeoutMs; waited += stopPollIntervalMs) { | ||
| if (!isAlive(pid)) { | ||
| return true; | ||
| } | ||
| await new Promise((resolve) => setTimeout(resolve, stopPollIntervalMs)); | ||
| } | ||
| return !isAlive(pid); | ||
| } | ||
|
|
||
| function removeRunnerRecordIfUnchanged(desktopDir, text) { | ||
| if (readRunnerRecordText(desktopDir) === text) { | ||
| NodeFS.rmSync(runnerRecordPath(desktopDir), { force: true }); | ||
| } | ||
| } | ||
|
|
||
| // The runner can exit on its own between inspection and each signal. | ||
| function signalIfAlive(pid, signal) { | ||
| try { | ||
| process.kill(pid, signal); | ||
| } catch (error) { | ||
| if (error?.code !== "ESRCH") { | ||
| throw error; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| async function terminate(pid) { | ||
| signalIfAlive(pid, "SIGTERM"); | ||
| if (!(await waitForExit(pid, stopGracePeriodMs))) { | ||
| signalIfAlive(pid, "SIGKILL"); | ||
| return waitForExit(pid, stopGracePeriodMs); | ||
| } | ||
| return true; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| async function clearRecordedRunner(desktopDir, selfPid) { | ||
| const text = readRunnerRecordText(desktopDir); | ||
| if (text === null) { | ||
| return { action: "none" }; | ||
| } | ||
| const record = parseRunnerRecord(text); | ||
| const decision = decideTakeover({ | ||
| record, | ||
| selfPid, | ||
| processInfo: record === null ? null : inspectProcess(record.pid), | ||
| desktopDir, | ||
| }); | ||
| if (decision.action === "unverifiable") { | ||
| return decision; | ||
| } | ||
| if (decision.action === "stop" && !(await terminate(decision.pid))) { | ||
| return { action: "survived", pid: decision.pid }; | ||
| } | ||
| removeRunnerRecordIfUnchanged(desktopDir, text); | ||
| return decision; | ||
| } | ||
|
|
||
| export async function stopRecordedRunner(desktopDir) { | ||
| if (hostPlatform === "win32") { | ||
| return { action: "unsupported" }; | ||
| } | ||
| return clearRecordedRunner(desktopDir, 0); | ||
| } | ||
|
|
||
| // The record is published with link() so it appears atomically with its full contents and two | ||
| // runners starting together cannot both believe they own the checkout. | ||
| export async function acquireRunnerRecord(desktopDir, pid = process.pid) { | ||
| const recordPath = runnerRecordPath(desktopDir); | ||
| const contents = `${JSON.stringify({ pid })}\n`; | ||
| NodeFS.mkdirSync(NodePath.dirname(recordPath), { recursive: true }); | ||
| if (hostPlatform === "win32") { | ||
| NodeFS.writeFileSync(recordPath, contents); | ||
| return { claimed: true, stoppedPids: [] }; | ||
| } | ||
|
|
||
| const stagingPath = `${recordPath}.${pid}.tmp`; | ||
| NodeFS.writeFileSync(stagingPath, contents); | ||
| const stoppedPids = []; | ||
| try { | ||
| for (let attempt = 0; attempt < maxClaimAttempts; attempt += 1) { | ||
| try { | ||
| NodeFS.linkSync(stagingPath, recordPath); | ||
| return { claimed: true, stoppedPids }; | ||
| } catch (error) { | ||
| if (error?.code !== "EEXIST") { | ||
| throw error; | ||
| } | ||
| } | ||
| const decision = await clearRecordedRunner(desktopDir, pid); | ||
| if (decision.action === "unverifiable" || decision.action === "survived") { | ||
| return { claimed: false, blocker: decision }; | ||
| } | ||
| if (decision.action === "stop") { | ||
| stoppedPids.push(decision.pid); | ||
| } | ||
| } | ||
| throw new Error(`another runner keeps claiming ${recordPath}`); | ||
| } finally { | ||
| NodeFS.rmSync(stagingPath, { force: true }); | ||
| } | ||
| } | ||
|
|
||
| export function releaseRunnerRecord(desktopDir, pid = process.pid) { | ||
| if (readRunnerRecord(desktopDir)?.pid === pid) { | ||
| NodeFS.rmSync(runnerRecordPath(desktopDir), { force: true }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| const RUNNER_SCRIPT_NAME = "dev-electron.mjs"; | ||
|
|
||
| export function parseRunnerRecord(text) { | ||
| let parsed; | ||
| try { | ||
| parsed = JSON.parse(text); | ||
| } catch { | ||
| return null; | ||
| } | ||
| const pid = parsed?.pid; | ||
| return Number.isInteger(pid) && pid > 1 ? { pid } : null; | ||
| } | ||
|
|
||
| function isRunnerCommand(command) { | ||
| const [executable = "", ...args] = command.trim().split(/\s+/); | ||
| const script = args.find((arg) => !arg.startsWith("-")); | ||
| return ( | ||
| /^node(?:\.exe)?$/.test(executable.split(/[\\/]/).at(-1)) && | ||
| script !== undefined && | ||
| script.split(/[\\/]/).at(-1) === RUNNER_SCRIPT_NAME | ||
| ); | ||
| } | ||
|
|
||
| export function isVerifiedRunner(processInfo, desktopDir) { | ||
| return ( | ||
| processInfo !== null && isRunnerCommand(processInfo.command) && processInfo.cwd === desktopDir | ||
| ); | ||
| } | ||
|
|
||
| // `processInfo` is null when the pid is not alive. Only a verified runner is signaled: a pid | ||
| // running something else was reused, so its record is stale, while a runner whose working | ||
| // directory cannot be read may belong to this checkout and must be neither signaled nor replaced. | ||
| export function decideTakeover({ record, selfPid, processInfo, desktopDir }) { | ||
| if (record === null || record.pid === selfPid || processInfo === null) { | ||
| return { action: "none" }; | ||
| } | ||
| if (isVerifiedRunner(processInfo, desktopDir)) { | ||
| return { action: "stop", pid: record.pid }; | ||
| } | ||
| if (isRunnerCommand(processInfo.command) && processInfo.cwd === null) { | ||
| return { action: "unverifiable", pid: record.pid }; | ||
| } | ||
| return { action: "stale", pid: record.pid }; | ||
| } | ||
|
|
||
| export function createCrashLoopBreaker({ maxAbnormalExits = 3, windowMs = 10_000 } = {}) { | ||
| let exitTimes = []; | ||
| return { | ||
| recordAbnormalExit(nowMs) { | ||
| exitTimes = [...exitTimes.filter((time) => nowMs - time < windowMs), nowMs]; | ||
| return { tripped: exitTimes.length >= maxAbnormalExits }; | ||
| }, | ||
| rearm() { | ||
| exitTimes = []; | ||
| }, | ||
| }; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.