@jjanczur/tyran 0.1.12 → 0.1.14

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.
@@ -0,0 +1,187 @@
1
+ /**
2
+ * keepawake — hold the SYSTEM awake for as long as a Tyran watcher is waiting.
3
+ *
4
+ * The measured failure: a laptop whose screensaver starts at five minutes
5
+ * suspends, the network goes with it, and the running session dies mid-task
6
+ * with an API error. The overnight resume watcher is the worst case — its
7
+ * whole job is to be asleep for hours waiting for a usage window to reset,
8
+ * which is exactly the interval a machine chooses to suspend in.
9
+ *
10
+ * Three constraints shape every line here.
11
+ *
12
+ * - **System sleep only, never the display.** `caffeinate -d` would also
13
+ * block the screen lock, and a machine left running overnight that never
14
+ * locks is a security regression. `-i` is idle sleep, `-s` is sleep while
15
+ * on AC power; the display and the lock stay exactly as the operator set
16
+ * them. The platforms are NOT symmetric behind this one knob, and the
17
+ * difference is documented rather than papered over: macOS still honours
18
+ * an explicit sleep request, while a logind `block` lock refuses the
19
+ * operator's own deliberate suspend too (see `inhibitorArgv`, and the
20
+ * `limits.keep_awake` section of docs/overnight.md).
21
+ * - **A leak is worse than a no-op.** An inhibitor that outlives its reason
22
+ * keeps someone's laptop awake indefinitely. So: the child is `unref`'d
23
+ * (it can never hold this process open), it is released on every exit path
24
+ * including SIGINT/SIGTERM, and the release is idempotent. SIGKILL is the
25
+ * one signal nothing can catch — stated in docs/overnight.md rather than
26
+ * pretended away.
27
+ * - **Degrade silently, never refuse.** An unsupported platform, a missing
28
+ * binary or a failed spawn returns a no-op release. Keeping the machine
29
+ * awake is an optimization on the real work; it is never a precondition
30
+ * for it, and it must never be the reason a run fails to start.
31
+ *
32
+ * Nothing foreign ever reaches the child: the command is an argv ARRAY, never
33
+ * a shell string, and `--why` is a module constant rather than an operator's,
34
+ * a config's or a pause marker's words.
35
+ */
36
+ import { spawn } from 'node:child_process';
37
+
38
+ /** Our own words, deliberately: the only free text the child ever sees. */
39
+ export const KEEP_AWAKE_REASON = 'Tyran is waiting for a usage-limit window to reset';
40
+
41
+ /**
42
+ * systemd-inhibit holds its lock only while its COMMAND runs, so it needs one.
43
+ * POSIX `sleep` takes an integer — GNU's `sleep infinity` is not portable to
44
+ * every userland systemd ships on, and an inhibitor whose command exits at
45
+ * once is a lock nobody is holding. 2^31-1 seconds is ~68 years.
46
+ */
47
+ export const INHIBIT_SLEEP_SECONDS = '2147483647';
48
+
49
+ /**
50
+ * Signals we release on. Each handler re-raises after releasing, so a caller's
51
+ * `kill` still kills: overnight's `cancel` SIGTERMs the watcher and expects it
52
+ * to die, and a handler that only cleaned up would make it unkillable.
53
+ */
54
+ const RELEASE_SIGNALS = Object.freeze(['SIGINT', 'SIGTERM', 'SIGHUP']);
55
+
56
+ const NOOP_RELEASE = () => {};
57
+
58
+ /**
59
+ * The inhibitor command for a platform, or `null` where no mechanism exists.
60
+ * Pure — the platform matrix is decidable without spawning anything.
61
+ */
62
+ export function inhibitorArgv(platform = process.platform) {
63
+ // -i: no idle sleep. -s: no sleep while on AC power. NEVER -d: that is the
64
+ // DISPLAY, and blocking it blocks the screen lock.
65
+ if (platform === 'darwin') return ['caffeinate', '-i', '-s'];
66
+ if (platform === 'linux') {
67
+ // `sleep` is not droppable: GNOME's automatic suspend goes through
68
+ // logind's Suspend(), which only a `sleep` lock stops — `idle` alone
69
+ // would leave the laptop suspending on its own timer. The cost is that
70
+ // `block` refuses the operator's DELIBERATE suspend as well (lid close,
71
+ // `systemctl suspend`), which is stated in docs/overnight.md rather than
72
+ // engineered around: `delay` merely postpones by InhibitDelayMaxSec and
73
+ // then lets the machine go, and `block-weak` (systemd 255+) exempts
74
+ // privileged callers — logind itself — so it would not stop the
75
+ // automatic suspend this exists for. `cancel` releases the lock at once.
76
+ return [
77
+ 'systemd-inhibit',
78
+ '--what=idle:sleep',
79
+ `--why=${KEEP_AWAKE_REASON}`,
80
+ '--mode=block',
81
+ 'sleep',
82
+ INHIBIT_SLEEP_SECONDS,
83
+ ];
84
+ }
85
+ // Windows and everything else: no mechanism, and that is not an error.
86
+ return null;
87
+ }
88
+
89
+ function note(onNote, message) {
90
+ if (typeof onNote !== 'function') return;
91
+ try {
92
+ onNote(message);
93
+ } catch {
94
+ /* a note is a courtesy; its failure must not reach the caller */
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Acquire the inhibitor and return the function that releases it.
100
+ *
101
+ * ALWAYS returns a function — off, unsupported, or failed all return a no-op,
102
+ * so a caller's `finally` needs no null check and can never crash on the path
103
+ * where the machine was already going to be fine.
104
+ *
105
+ * `argv` and `spawnFn` are injection points for tests only. Neither is
106
+ * reachable from any CLI: nothing constructs them from a file, a flag or an
107
+ * environment variable.
108
+ */
109
+ export function keepAwake({ enabled = false, platform = process.platform, argv = null, spawnFn = spawn, onNote = null } = {}) {
110
+ // Strict true: a knob that changes the operator's machine is never enabled
111
+ // by a truthy string that drifted in from a parser.
112
+ if (enabled !== true) return NOOP_RELEASE;
113
+
114
+ const command = argv ?? inhibitorArgv(platform);
115
+ if (command === null) {
116
+ note(onNote, `keep-awake: no inhibitor on ${platform} — this machine may still sleep and take the run with it`);
117
+ return NOOP_RELEASE;
118
+ }
119
+ note(
120
+ onNote,
121
+ `keep-awake: holding the system awake with ${command[0]} — the display and the screen lock are untouched`,
122
+ );
123
+
124
+ let child;
125
+ try {
126
+ child = spawnFn(command[0], command.slice(1), {
127
+ // Never the caller's stdio: the watcher's log is a record, not a pipe.
128
+ stdio: 'ignore',
129
+ // The argv above is the whole command. No shell, ever.
130
+ shell: false,
131
+ });
132
+ } catch {
133
+ // Silent degrade: the work matters, the inhibitor does not.
134
+ return NOOP_RELEASE;
135
+ }
136
+
137
+ // spawn reports a MISSING BINARY asynchronously, as an 'error' event. With
138
+ // no listener that event is thrown and takes the watcher down — a machine
139
+ // without caffeinate would lose the very run this exists to protect.
140
+ if (typeof child?.on === 'function') child.on('error', () => {});
141
+ // The inhibitor must never be the reason this process is still alive.
142
+ if (typeof child?.unref === 'function') child.unref();
143
+
144
+ const handlers = new Map();
145
+ let released = false;
146
+ const release = () => {
147
+ if (released) return; // idempotent: killing twice is harmless, by construction
148
+ released = true;
149
+ for (const [event, fn] of handlers) process.removeListener(event, fn);
150
+ handlers.clear();
151
+ try {
152
+ child.kill('SIGTERM');
153
+ } catch {
154
+ /* already gone, or never really there */
155
+ }
156
+ };
157
+
158
+ for (const signal of RELEASE_SIGNALS) {
159
+ const fn = () => {
160
+ release();
161
+ // release() removed this listener, so the default disposition is back:
162
+ // re-raising kills us exactly as it would have without the handler.
163
+ process.kill(process.pid, signal);
164
+ };
165
+ handlers.set(signal, fn);
166
+ process.on(signal, fn);
167
+ }
168
+ const onExit = () => release();
169
+ handlers.set('exit', onExit);
170
+ process.on('exit', onExit);
171
+
172
+ return release;
173
+ }
174
+
175
+ /**
176
+ * Run `fn` with the machine held awake. The release is in a `finally`, so it
177
+ * runs on the thrown path too — the path where a forgotten release would leave
178
+ * a laptop awake with nothing left to explain why.
179
+ */
180
+ export async function withKeepAwake(options, fn) {
181
+ const release = keepAwake(options);
182
+ try {
183
+ return await fn();
184
+ } finally {
185
+ release();
186
+ }
187
+ }