@kaynooo/cli-proc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/read.ts ADDED
@@ -0,0 +1,175 @@
1
+ import type { Socket } from './parse'
2
+ import { readdir, readFile, readlink } from 'node:fs/promises'
3
+ import { cgroupContainer, cgroupUnit, parseCgroup, parseCmdline, parseNetTable, parseStat, parseStatus, socketInode, statusBytes, statusUid, userNameOf } from './parse'
4
+
5
+ // Linux counts process start times in ticks of 1/100 s; reading the real value would take a libc call.
6
+ const CLOCK_TICKS = 100
7
+
8
+ export interface ProcInfo {
9
+ pid: number
10
+ ppid: number
11
+ comm: string
12
+ args: string[]
13
+ uid: number
14
+ state: string
15
+ session: number
16
+ // Resident memory in bytes.
17
+ rss: number
18
+ // Epoch milliseconds.
19
+ startMs: number
20
+ cwd?: string | undefined
21
+ exe?: string | undefined
22
+ unit?: string | undefined
23
+ container?: string | undefined
24
+ }
25
+
26
+ async function text(path: string): Promise<string | undefined> {
27
+ try {
28
+ return await readFile(path, 'utf8')
29
+ }
30
+ catch {
31
+ return undefined
32
+ }
33
+ }
34
+
35
+ async function link(path: string): Promise<string | undefined> {
36
+ try {
37
+ return await readlink(path)
38
+ }
39
+ catch {
40
+ return undefined
41
+ }
42
+ }
43
+
44
+ const DIGITS = /^\d+$/
45
+ const BOOT_TIME = /^btime\s+(\d+)/m
46
+
47
+ export async function listPids(root = '/proc'): Promise<number[]> {
48
+ return (await readdir(root)).filter(name => DIGITS.test(name)).map(Number)
49
+ }
50
+
51
+ // The epoch milliseconds the machine booted at, from `btime` in /proc/stat.
52
+ export async function bootMs(root = '/proc'): Promise<number> {
53
+ const match = BOOT_TIME.exec(await text(`${root}/stat`) ?? '')
54
+
55
+ return match === null ? Date.now() : Number(match[1]) * 1000
56
+ }
57
+
58
+ // One process, undefined once it is gone or its stat cannot be read. `detail` adds what only the owner can read: the working directory, the executable and the cgroup.
59
+ export async function readProc(pid: number, boot: number, { root = '/proc', detail = true } = {}): Promise<ProcInfo | undefined> {
60
+ const dir = `${root}/${pid}`
61
+ const [statText, statusText, cmdline] = await Promise.all([text(`${dir}/stat`), text(`${dir}/status`), text(`${dir}/cmdline`)])
62
+ const stat = statText === undefined ? undefined : parseStat(statText)
63
+
64
+ if (stat === undefined || statusText === undefined)
65
+ return undefined
66
+
67
+ const status = parseStatus(statusText)
68
+ const info: ProcInfo = {
69
+ pid,
70
+ ppid: stat.ppid,
71
+ comm: stat.comm,
72
+ args: parseCmdline(cmdline ?? ''),
73
+ uid: statusUid(status) ?? -1,
74
+ state: stat.state,
75
+ session: stat.session,
76
+ rss: statusBytes(status, 'VmRSS') ?? 0,
77
+ startMs: boot + (stat.startTicks / CLOCK_TICKS) * 1000,
78
+ }
79
+
80
+ if (!detail)
81
+ return info
82
+
83
+ const [cwd, exe, cgroup] = await Promise.all([link(`${dir}/cwd`), link(`${dir}/exe`), text(`${dir}/cgroup`)])
84
+ const groups = parseCgroup(cgroup ?? '')
85
+
86
+ return { ...info, cwd, exe, unit: cgroupUnit(groups), container: cgroupContainer(groups) }
87
+ }
88
+
89
+ // Every process, with the detail only for those `detailed` accepts: the ones of the calling user, whose directories are readable.
90
+ export async function snapshot(root = '/proc', detailed: (uid: number) => boolean = () => true): Promise<ProcInfo[]> {
91
+ const boot = await bootMs(root)
92
+ const found: ProcInfo[] = []
93
+
94
+ for (const pid of await listPids(root)) {
95
+ const light = await readProc(pid, boot, { root, detail: false })
96
+
97
+ if (light === undefined)
98
+ continue
99
+
100
+ found.push(detailed(light.uid) ? await readProc(pid, boot, { root }) ?? light : light)
101
+ }
102
+
103
+ return found
104
+ }
105
+
106
+ // The pids from `pid` up to init, nearest first, `pid` included.
107
+ export function ancestry(pid: number, byPid: Map<number, { ppid: number }>): number[] {
108
+ const chain: number[] = []
109
+ let at: number | undefined = pid
110
+
111
+ while (at !== undefined && at > 0 && !chain.includes(at)) {
112
+ chain.push(at)
113
+ at = byPid.get(at)?.ppid
114
+ }
115
+
116
+ return chain
117
+ }
118
+
119
+ export async function readSockets(root = '/proc'): Promise<Socket[]> {
120
+ const tables = [['tcp', 'tcp', 4], ['tcp6', 'tcp', 6], ['udp', 'udp', 4], ['udp6', 'udp', 6]] as const
121
+ const sockets: Socket[] = []
122
+
123
+ for (const [file, protocol, family] of tables)
124
+ sockets.push(...parseNetTable(await text(`${root}/net/${file}`) ?? '', protocol, family))
125
+
126
+ return sockets
127
+ }
128
+
129
+ // The inodes of the sockets a process holds open, empty when its fd directory is not readable.
130
+ export async function socketsOf(pid: number, root = '/proc'): Promise<Set<number>> {
131
+ const inodes = new Set<number>()
132
+
133
+ try {
134
+ for (const fd of await readdir(`${root}/${pid}/fd`)) {
135
+ const inode = socketInode(await link(`${root}/${pid}/fd/${fd}`) ?? '')
136
+
137
+ if (inode !== undefined)
138
+ inodes.add(inode)
139
+ }
140
+ }
141
+ catch {}
142
+
143
+ return inodes
144
+ }
145
+
146
+ // Which pid holds each socket inode, for the processes whose fd directory can be read.
147
+ export async function socketOwners(root = '/proc'): Promise<Map<number, number>> {
148
+ const owners = new Map<number, number>()
149
+
150
+ for (const pid of await listPids(root)) {
151
+ for (const inode of await socketsOf(pid, root))
152
+ owners.set(inode, pid)
153
+ }
154
+
155
+ return owners
156
+ }
157
+
158
+ export async function fdCount(pid: number, root = '/proc'): Promise<number | undefined> {
159
+ try {
160
+ return (await readdir(`${root}/${pid}/fd`)).length
161
+ }
162
+ catch {
163
+ return undefined
164
+ }
165
+ }
166
+
167
+ let passwd: string | undefined
168
+
169
+ export async function userName(uid: number): Promise<string | undefined> {
170
+ passwd ??= await text('/etc/passwd') ?? ''
171
+
172
+ return userNameOf(passwd, uid)
173
+ }
174
+
175
+ export { text as readText }
package/src/select.ts ADDED
@@ -0,0 +1,201 @@
1
+ import type { Guard } from './kill'
2
+ import type { ProcInfo } from './read'
3
+ import { basename, join, relative } from 'node:path'
4
+ import { protectionOf } from './kill'
5
+
6
+ const BROWSERS = /^(?:chrom(?:e|ium)(?:-browser)?|google-chrome(?:-stable|-beta|-unstable)?|chrome_crashpad_handler|chrome-headless-shell|headless_shell|chromium-headless-shell|brave|brave-browser|msedge|microsoft-edge|webkitwebprocess|webkitnetworkprocess|webkitgpuprocess|minibrowser|webkitwebdriver|wpewebprocess|wpenetworkprocess|bun-webview.*)$/i
7
+ const NATIVE = new Set(['rust-analyzer', 'gopls', 'clangd', 'lua-language-server', 'pyright-langserver', 'pylsp', 'intelephense', 'phpactor', 'tsgo', 'esbuild', 'biome', 'ruff', 'phpunit', 'pytest', 'vitest', 'jest'])
8
+ const RUNTIMES = new Set(['node', 'bun', 'bunx', 'deno', 'nodejs'])
9
+ const SCRIPTS = new Set(['vite', 'vitest', 'nuxt', 'nuxi', 'next', 'jest', 'playwright', 'playwright-core', 'tsserver', 'typescript-language-server', 'vue-language-server', 'vtsls', 'eslint_d', 'esbuild', 'webpack', 'turbo', 'astro', 'tsgo', 'svelte-kit', 'remix', 'storybook', 'biome', 'prettierd', 'tailwindcss', 'bun-webview'])
10
+ const EXTENSION = /\.[cm]?[jt]s$/
11
+ const MARKERS = ['package.json', 'composer.json', 'Cargo.toml', 'go.mod', 'pyproject.toml']
12
+ // Chromium re-runs itself with these for helpers, and a main process with these is driven by a script rather than opened by hand.
13
+ const AUTOMATION = /^--(?:headless|remote-debugging-(?:pipe|port)|enable-automation)/
14
+
15
+ export const HEAVY_DEFAULT = 500 * 1024 ** 2
16
+
17
+ // The dev tool a process is, undefined for anything else: `chromium`, `vite`, `bun`, `rust-analyzer`.
18
+ export function toolOf(proc: Pick<ProcInfo, 'comm' | 'args' | 'exe'>): string | undefined {
19
+ const names = [proc.exe, proc.args[0], proc.comm].filter((name): name is string => name !== undefined && name !== '').map(name => basename(name))
20
+
21
+ for (const name of names) {
22
+ if (BROWSERS.test(name))
23
+ return name.toLowerCase().startsWith('webkit') || name.toLowerCase().startsWith('wpe') || name.toLowerCase() === 'minibrowser' ? 'webkit' : 'chromium'
24
+
25
+ if (NATIVE.has(name))
26
+ return name
27
+ }
28
+
29
+ const runtime = names.find(name => RUNTIMES.has(name))
30
+
31
+ if (runtime === undefined)
32
+ return undefined
33
+
34
+ for (const arg of proc.args.slice(1)) {
35
+ if (arg.startsWith('-'))
36
+ continue
37
+
38
+ const script = basename(arg).replace(EXTENSION, '')
39
+
40
+ if (SCRIPTS.has(script))
41
+ return script
42
+ }
43
+
44
+ return runtime === 'nodejs' ? 'node' : runtime
45
+ }
46
+
47
+ export function userDataDir(args: string[]): string | undefined {
48
+ const arg = args.find(word => word.startsWith('--user-data-dir='))
49
+
50
+ return arg?.slice('--user-data-dir='.length)
51
+ }
52
+
53
+ // The nearest folder up from `cwd` holding a `.git`, else one holding a package or build manifest, never the home folder or above.
54
+ export function projectOf(cwd: string | undefined, exists: (path: string) => boolean, home: string): string | undefined {
55
+ if (cwd === undefined || !cwd.startsWith(`${home}/`))
56
+ return undefined
57
+
58
+ const folders: string[] = []
59
+
60
+ for (let dir = cwd; dir.startsWith(`${home}/`); dir = join(dir, '..'))
61
+ folders.push(dir)
62
+
63
+ return folders.find(dir => exists(join(dir, '.git'))) ?? folders.find(dir => MARKERS.some(marker => exists(join(dir, marker))))
64
+ }
65
+
66
+ // Whether a process was left behind: reparented to init or to the user's systemd. A systemd service of its own is managed, not left over, and a browser is only one when a script drives it or it is a helper whose main process may be gone.
67
+ export function isOrphan(proc: ProcInfo, byPid: Map<number, ProcInfo>): boolean {
68
+ if (proc.unit?.endsWith('.service') === true)
69
+ return false
70
+
71
+ const parent = byPid.get(proc.ppid)
72
+ const userManager = parent !== undefined && parent.comm === 'systemd' && parent.uid === proc.uid && parent.uid !== 0
73
+ const reparented = proc.ppid === 1 || userManager
74
+
75
+ const tool = toolOf(proc)
76
+
77
+ if (!reparented || (tool !== 'chromium' && tool !== 'webkit'))
78
+ return reparented
79
+
80
+ // The crashpad handler detaches from its browser by design.
81
+ if (basename(proc.exe ?? proc.args[0] ?? proc.comm).includes('crashpad'))
82
+ return false
83
+
84
+ return proc.args.some(arg => arg.startsWith('--type=')) || proc.args.some(arg => AUTOMATION.test(arg))
85
+ }
86
+
87
+ export interface Member {
88
+ proc: ProcInfo
89
+ tool: string
90
+ orphan: boolean
91
+ heavy: boolean
92
+ ageMs: number
93
+ }
94
+
95
+ export type GroupKind = 'project' | 'profile' | 'command'
96
+
97
+ export interface Group {
98
+ key: string
99
+ origin: string
100
+ kind: GroupKind
101
+ members: Member[]
102
+ rss: number
103
+ oldestMs: number
104
+ orphans: number
105
+ }
106
+
107
+ export interface SelectOptions {
108
+ guard: Guard
109
+ now: number
110
+ home: string
111
+ exists: (path: string) => boolean
112
+ // Resident bytes from which a process is heavy, and when given also the least a left over one must use to be listed.
113
+ minMem?: number | undefined
114
+ // The least age of a process to be listed.
115
+ olderMs?: number | undefined
116
+ }
117
+
118
+ export interface Selection {
119
+ groups: Group[]
120
+ // Processes that qualified but must never be signalled, left out.
121
+ protectedCount: number
122
+ }
123
+
124
+ function originOf(proc: ProcInfo, tool: string, { exists, home }: SelectOptions): { key: string, origin: string, kind: GroupKind } {
125
+ const profile = userDataDir(proc.args)
126
+
127
+ if (profile !== undefined)
128
+ return { key: `profile:${profile}`, origin: `${tool} profile ${profile}`, kind: 'profile' }
129
+
130
+ const project = projectOf(proc.cwd, exists, home)
131
+
132
+ if (project !== undefined)
133
+ return { key: `project:${project}`, origin: `~/${relative(home, project)}`, kind: 'project' }
134
+
135
+ return { key: `command:${tool}`, origin: tool, kind: 'command' }
136
+ }
137
+
138
+ // The leftover or heavy dev processes of the calling user, grouped by origin. A selected process pulls in the dev processes below it, and those sharing its browser profile, so a browser whose main process is gone still groups with its helpers.
139
+ export function selectGroups(procs: ProcInfo[], options: SelectOptions): Selection {
140
+ const byPid = new Map(procs.map(proc => [proc.pid, proc]))
141
+ const heavyFrom = options.minMem ?? HEAVY_DEFAULT
142
+ const candidates = procs.filter(proc => proc.uid === options.guard.uid && proc.pid !== 1 && toolOf(proc) !== undefined)
143
+ const chosen = new Map<number, { orphan: boolean, heavy: boolean }>()
144
+ let protectedCount = 0
145
+
146
+ for (const proc of candidates) {
147
+ const ageMs = options.now - proc.startMs
148
+ const orphan = isOrphan(proc, byPid)
149
+ const heavy = proc.rss >= heavyFrom
150
+
151
+ if (!(heavy || (orphan && proc.rss >= (options.minMem ?? 0))) || ageMs < (options.olderMs ?? 0))
152
+ continue
153
+
154
+ if (protectionOf(proc, options.guard) !== undefined) {
155
+ protectedCount++
156
+
157
+ continue
158
+ }
159
+
160
+ chosen.set(proc.pid, { orphan, heavy })
161
+ }
162
+
163
+ const profiles = new Set([...chosen.keys()].map(pid => userDataDir(byPid.get(pid)!.args)).filter(dir => dir !== undefined))
164
+ let grew = true
165
+
166
+ while (grew) {
167
+ grew = false
168
+
169
+ for (const proc of candidates) {
170
+ const dir = userDataDir(proc.args)
171
+ const joins = chosen.has(proc.ppid) || (dir !== undefined && profiles.has(dir))
172
+
173
+ if (chosen.has(proc.pid) || !joins || protectionOf(proc, options.guard) !== undefined)
174
+ continue
175
+
176
+ chosen.set(proc.pid, { orphan: isOrphan(proc, byPid), heavy: proc.rss >= heavyFrom })
177
+ grew = true
178
+ }
179
+ }
180
+
181
+ const groups = new Map<string, Group>()
182
+
183
+ for (const [pid, flags] of chosen) {
184
+ const proc = byPid.get(pid)!
185
+ const tool = toolOf(proc)!
186
+ const { key, origin, kind } = originOf(proc, tool, options)
187
+ const group = groups.get(key) ?? { key, origin, kind, members: [], rss: 0, oldestMs: 0, orphans: 0 }
188
+ const ageMs = options.now - proc.startMs
189
+
190
+ group.members.push({ proc, tool, ageMs, ...flags })
191
+ group.rss += proc.rss
192
+ group.oldestMs = Math.max(group.oldestMs, ageMs)
193
+ group.orphans += flags.orphan ? 1 : 0
194
+ groups.set(key, group)
195
+ }
196
+
197
+ for (const group of groups.values())
198
+ group.members.sort((a, b) => a.proc.pid - b.proc.pid)
199
+
200
+ return { groups: [...groups.values()].sort((a, b) => b.rss - a.rss), protectedCount }
201
+ }