Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

KeepAwake.ts

255 lines8.8 KB

1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Ref from "effect/Ref";
7import * as ChildProcess from "effect/process/ChildProcess";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9import * as Schedule from "effect/Schedule";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import * as SqlClient from "effect/sql/SqlClient";
13​
14import * as HostProcess from "@t3tools/shared/HostProcess";
15​
16import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
17import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem";
18import { forkParked } from "../serverActivation.ts";
19import * as Settings from "../serverSettings.ts";
20​
21// Bridges gaps between back-to-back runs, so a long-idle machine does not sleep mid-queue.
22const RELEASE_GRACE = Duration.seconds(60);
23​
24// ES_CONTINUOUS | ES_SYSTEM_REQUIRED, held by the calling thread until the script ends.
25const WINDOWS_HOLD_SCRIPT = `$t = Add-Type -Name Power -Namespace T3 -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'; [void]$t::SetThreadExecutionState([uint32]2147483649); [Console]::Out.WriteLine()`;
26​
27/**
28 * Each command writes a line to stdout once it holds its inhibitor, holds it until it exits, and
29 * exits on its own if the server dies.
30 */
31export function inhibitorCommand(
32 platform: NodeJS.Platform,
33 serverPid: number,
34 isWsl: boolean,
35 env: NodeJS.ProcessEnv,
36):
37 | {
38 readonly command: string;
39 readonly args: ReadonlyArray<string>;
40 readonly stdin: "ignore" | "pipe";
41 }
42 | undefined {
43 // logind inside the WSL VM cannot block Windows sleep. Windows cannot wait on a Linux pid, so
44 // the hold ends when its stdin pipe closes, which also happens if the server dies.
45 if (isWsl) {
46 return {
47 command: "powershell.exe",
48 args: [
49 "-NoProfile",
50 "-NonInteractive",
51 "-Command",
52 `${WINDOWS_HOLD_SCRIPT}; [void][Console]::In.ReadToEnd()`,
53 ],
54 stdin: "pipe",
55 };
56 }
57 switch (platform) {
58 case "darwin":
59 return {
60 command: "sh",
61 args: ["-c", 'echo && exec caffeinate -i -w "$0"', String(serverPid)],
62 stdin: "ignore",
63 };
64 case "linux":
65 return {
66 command: "systemd-inhibit",
67 args: [
68 "--what=sleep",
69 "--who=T3 Code",
70 "--why=Agents are working",
71 "--mode=block",
72 // systemd-inhibit starts this only after logind grants the lock.
73 "sh",
74 "-c",
75 'echo && exec tail --pid="$0" -f /dev/null',
76 String(serverPid),
77 ],
78 stdin: "ignore",
79 };
80 case "win32":
81 return {
82 command: windowsPowerShellPath(env),
83 args: [
84 "-NoProfile",
85 "-NonInteractive",
86 "-Command",
87 `${WINDOWS_HOLD_SCRIPT}; Wait-Process -Id ${serverPid}`,
88 ],
89 stdin: "ignore",
90 };
91 default:
92 return undefined;
93 }
95​
96/**
97 * Runs `hold` while `wanted` is true and for `grace` after it turns false; a true inside the
98 * grace keeps the same hold. `hold` runs until interrupted.
99 */
100export const holdWhileWanted = <E, R>(
101 wanted: Stream.Stream<boolean, E, R>,
102 hold: Effect.Effect<void>,
103 grace: Duration.Input = RELEASE_GRACE,
104) =>
105 wanted.pipe(
106 Stream.changes,
107 Stream.switchMap((on) =>
108 on ? Stream.succeed(true) : Stream.fromEffect(Effect.as(Effect.sleep(grace), false)),
109 ),
110 Stream.changes,
111 Stream.switchMap((on) => (on ? Stream.fromEffect(hold) : Stream.empty)),
112 Stream.runDrain,
113 );
114​
115// Reads, the event subscription and the inhibitor retry until they succeed; the cap keeps a
116// host without an inhibitor (e.g. no logind) from retrying and warning constantly.
117const backoff = Schedule.exponential("5 seconds").pipe(
118 Schedule.modifyDelay(({ duration }) =>
119 Effect.succeed(Duration.min(duration, Duration.minutes(10))),
120 ),
121);
122const retryWithBackoff =
123 (message: string) =>
124 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
125 effect.pipe(
126 Effect.tapCause((cause) => Effect.logWarning(message, { cause })),
127 Effect.retry(backoff),
128 );
129​
130class KeepAwakeInhibitorExited extends Schema.TaggedError<KeepAwakeInhibitorExited>()(
131 "KeepAwakeInhibitorExited",
132 { exitCode: Schema.Number, stderr: Schema.String },
133) {
134 override get message(): string {
135 return `sleep inhibitor exited with code ${this.exitCode}${this.stderr ? `: ${this.stderr}` : ""}`;
136 }
138​
139export const layer = Layer.effectDiscard(
140 Effect.gen(function* () {
141 const platform = yield* HostProcess.Platform;
142 const fileSystem = yield* FileSystem.FileSystem;
143 // Services started by systemd lack WSL_DISTRO_NAME and WSL_INTEROP; the kernel release does not.
144 const isWsl =
145 platform === "linux" &&
146 (yield* fileSystem.readFileString("/proc/sys/kernel/osrelease").pipe(
147 Effect.map((release) => release.toLowerCase().includes("microsoft")),
148 Effect.orElseSucceed(() => false),
149 ));
150 const command = inhibitorCommand(platform, process.pid, isWsl, yield* HostProcess.Environment);
151 if (command === undefined) return;
152 const settings = yield* Settings.ServerSettingsService;
153 const events = yield* OrchestrationEventStore.OrchestrationEventStore;
154 const sql = yield* SqlClient.SqlClient;
155 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
156​
157 const hasActiveRun = sql<{ readonly active: number }>`
158 SELECT EXISTS (
159 SELECT 1 FROM orchestration_v2_projection_runs
160 WHERE status IN ('preparing', 'starting', 'running')
161 ) AS active
162 `.pipe(
163 Effect.map((rows) => rows[0]?.active === 1),
164 retryWithBackoff("keep-awake could not read active runs"),
165 );
166 // Read the cursor before the snapshot so a run changing in between is replayed, not missed.
167 const active = Stream.unwrap(
168 events.latestApplicationSequence.pipe(
169 retryWithBackoff("keep-awake could not read the event cursor"),
170 Effect.map((afterSequence) =>
171 Stream.concat(
172 Stream.succeed(undefined),
173 events
174 .streamApplicationEvents({ afterSequence })
175 .pipe(
176 Stream.filter(
177 (stored) =>
178 "event" in stored &&
179 (stored.event.type === "run.created" || stored.event.type === "run.updated"),
180 ),
181 ),
182 ),
183 ),
184 ),
185 ).pipe(
186 Stream.mapEffect(() => hasActiveRun),
187 // A failed subscription resubscribes, which re-reads the cursor and the snapshot.
188 Stream.tapCause((cause) =>
189 Effect.logWarning("keep-awake run event stream failed", { cause }),
190 ),
191 Stream.retry(backoff),
192 );
193 const enabled = Stream.unwrap(
194 Effect.gen(function* () {
195 const changes = yield* settings.subscribeChanges;
196 const current = yield* settings.getSettings.pipe(
197 Effect.map((value) => value.keepAwakeWhileAgentsWork),
198 Effect.orElseSucceed(() => true),
199 );
200 return Stream.concat(
201 Stream.succeed(current),
202 Stream.map(changes, (value) => value.keepAwakeWhileAgentsWork),
203 );
204 }),
205 );
206​
207 const holdOnce = Effect.gen(function* () {
208 const child = yield* spawner.spawn(
209 ChildProcess.make(command.command, command.args, {
210 detached: false,
211 shell: false,
212 stdin: command.stdin,
213 stdout: "pipe",
214 stderr: "pipe",
215 }),
216 );
217 const stderr = yield* child.stderr.pipe(
218 Stream.decodeText(),
219 Stream.mkString,
220 Effect.forkScoped,
221 );
222 const held = yield* Ref.make(false);
223 yield* Effect.addFinalizer(() =>
224 Effect.when(Effect.logInfo("keep-awake released sleep inhibitor"), Ref.get(held)),
225 );
226 yield* child.stdout.pipe(
227 Stream.take(1),
228 Stream.runForEach(() =>
229 Ref.set(held, true).pipe(
230 Effect.andThen(
231 Effect.logInfo("keep-awake holding sleep inhibitor", { pid: Number(child.pid) }),
232 ),
233 ),
234 ),
235 Effect.forkScoped,
236 );
237 const exitCode = yield* child.exitCode;
238 return yield* new KeepAwakeInhibitorExited({
239 exitCode: Number(exitCode),
240 stderr: (yield* Fiber.join(stderr)).trim(),
241 });
242 }).pipe(Effect.scoped);
243 const hold = holdOnce.pipe(
244 retryWithBackoff("keep-awake sleep inhibitor stopped"),
245 Effect.ignore,
246 );
247​
248 yield* forkParked(
249 holdWhileWanted(
250 Stream.zipLatestWith(enabled, active, (on, busy) => on && busy),
251 hold,
252 ).pipe(Effect.catchCause((cause) => Effect.logWarning("keep-awake stopped", { cause }))),
253 );
254 }),
255);