Repository navigation
Expand file tree
/
Copy pathkill-all.ts
More file actions
144 lines (124 loc) · 4.42 KB
/
Copy pathkill-all.ts
File metadata and controls
144 lines (124 loc) · 4.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import { Data, Effect } from "effect"
import {
ACN_EXECUTABLE_NAME,
ICN_EXECUTABLE_NAME,
} from "@magnitudedev/release/executables"
export type MagnitudeProcessKind = "ICN" | "ACN" | "CLI"
export interface ProcessInfo {
readonly pid: number
readonly parentPid: number
readonly command: string
}
export interface MagnitudeProcess extends ProcessInfo {
readonly kind: MagnitudeProcessKind
}
class ProcessListError extends Data.TaggedError("ProcessListError")<{
readonly cause?: unknown
readonly message: string
}> {}
const executable = (name: string): RegExp =>
new RegExp(`^\\s*(?:\\S*[/\\\\])?${name}(?:\\.exe)?(?:\\s|$)`, "i")
const scriptInvocation = (path: string): RegExp =>
new RegExp(
`(?:^|\\s)(?:\\S*[/\\\\])?(?:bun|node)(?:\\.exe)?(?:\\s+run)?\\s+\\S*${path.replaceAll("/", "[/\\\\]")}(?:\\s|$)`,
"i",
)
const icnExecutable = executable(`(?:${ICN_EXECUTABLE_NAME}|icn-server)`)
const acnExecutable = executable(ACN_EXECUTABLE_NAME)
const cliExecutable = executable("magnitude-cli")
const acnSource = scriptInvocation("packages/acn/src/binary\\.ts")
const cliSource = scriptInvocation("cli/src/index\\.tsx")
const npmCliSource = scriptInvocation("packages/launcher/bin/magnitude\\.js")
export const classifyMagnitudeProcess = (
command: string,
): MagnitudeProcessKind | undefined => {
if (
icnExecutable.test(command) ||
/(?:^|\s)(?:icn:dev|icn:serve)(?:\s|$)/i.test(command) ||
/(?:^|\s)-p\s+icn-server(?:\s|$)/i.test(command)
) return "ICN"
if (acnExecutable.test(command) || (acnSource.test(command) && /(?:^|\s)serve(?:\s|$)/.test(command))) {
return "ACN"
}
if (cliExecutable.test(command) || cliSource.test(command) || npmCliSource.test(command)) {
return "CLI"
}
return undefined
}
export const parseProcessList = (output: string): readonly ProcessInfo[] =>
output.split("\n").flatMap((line) => {
const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line)
if (!match) return []
return [{
pid: Number(match[1]),
parentPid: Number(match[2]),
command: match[3],
}]
})
const collectProcesses = Effect.tryPromise({
try: async () => {
const processList = Bun.spawn(["ps", "-axo", "pid=,ppid=,command="], {
stdout: "pipe",
stderr: "pipe",
})
const [exitCode, stdout, stderr] = await Promise.all([
processList.exited,
new Response(processList.stdout).text(),
new Response(processList.stderr).text(),
])
if (exitCode !== 0) {
throw new ProcessListError({
message: `ps exited with code ${exitCode}: ${stderr.trim()}`,
})
}
return parseProcessList(stdout)
},
catch: (cause) => cause instanceof ProcessListError
? cause
: new ProcessListError({ cause, message: "Could not list processes" }),
})
const isRunning = (pid: number): boolean => {
try {
process.kill(pid, 0)
return true
} catch (cause) {
return cause instanceof Error && "code" in cause && cause.code === "EPERM"
}
}
const signal = (target: MagnitudeProcess, name: NodeJS.Signals): void => {
try {
process.kill(target.pid, name)
console.log(`${name === "SIGTERM" ? "Stopping" : "Killing"} ${target.kind} pid ${target.pid}: ${target.command}`)
} catch (cause) {
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH")) throw cause
}
}
const waitForExit = (targets: readonly MagnitudeProcess[], timeoutMs: number) =>
Effect.gen(function* () {
const deadline = Date.now() + timeoutMs
let running = targets.filter(({ pid }) => isRunning(pid))
while (running.length > 0 && Date.now() < deadline) {
yield* Effect.sleep("50 millis")
running = running.filter(({ pid }) => isRunning(pid))
}
return running
})
export const killAllMagnitudeProcesses = Effect.gen(function* () {
const ownPid = process.pid
const targets = (yield* collectProcesses).flatMap((candidate): readonly MagnitudeProcess[] => {
if (candidate.pid === ownPid) return []
const kind = classifyMagnitudeProcess(candidate.command)
return kind ? [{ ...candidate, kind }] : []
})
if (targets.length === 0) {
console.log("No Magnitude ICN, ACN, or CLI processes found.")
return
}
for (const target of targets) signal(target, "SIGTERM")
const remaining = yield* waitForExit(targets, 2_000)
for (const target of remaining) signal(target, "SIGKILL")
yield* waitForExit(remaining, 1_000)
})
if (import.meta.main) {
await Effect.runPromise(killAllMagnitudeProcesses)
}