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

KeepAwake.ts

226 lines7.8 KB

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