|
| 1 | +import * as Duration from "effect/Duration"; |
| 2 | +import * as Effect from "effect/Effect"; |
| 3 | +import * as Layer from "effect/Layer"; |
| 4 | +import * as ChildProcess from "effect/process/ChildProcess"; |
| 5 | +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 6 | +import type * as Scope from "effect/Scope"; |
| 7 | +import * as Stream from "effect/Stream"; |
| 8 | +import * as SqlClient from "effect/sql/SqlClient"; |
| 9 | + |
| 10 | +import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 11 | + |
| 12 | +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; |
| 13 | +import { forkParked } from "../serverActivation.ts"; |
| 14 | +import * as Settings from "../serverSettings.ts"; |
| 15 | + |
| 16 | +// Bridges gaps between back-to-back runs, so a long-idle machine does not sleep mid-queue. |
| 17 | +const RELEASE_GRACE = Duration.seconds(60); |
| 18 | + |
| 19 | +/** Each command holds its inhibitor until it exits, and exits on its own if the server dies. */ |
| 20 | +function inhibitorCommand( |
| 21 | + platform: NodeJS.Platform, |
| 22 | + serverPid: number, |
| 23 | +): { readonly command: string; readonly args: ReadonlyArray<string> } | undefined { |
| 24 | + switch (platform) { |
| 25 | + case "darwin": |
| 26 | + return { command: "caffeinate", args: ["-i", "-w", String(serverPid)] }; |
| 27 | + case "linux": |
| 28 | + return { |
| 29 | + command: "systemd-inhibit", |
| 30 | + args: [ |
| 31 | + "--what=idle:sleep", |
| 32 | + "--who=T3 Code", |
| 33 | + "--why=Agents are working", |
| 34 | + "--mode=block", |
| 35 | + "tail", |
| 36 | + `--pid=${serverPid}`, |
| 37 | + "-f", |
| 38 | + "/dev/null", |
| 39 | + ], |
| 40 | + }; |
| 41 | + case "win32": |
| 42 | + return { |
| 43 | + command: "powershell.exe", |
| 44 | + args: [ |
| 45 | + "-NoProfile", |
| 46 | + "-NonInteractive", |
| 47 | + "-Command", |
| 48 | + // ES_CONTINUOUS | ES_SYSTEM_REQUIRED, held by this thread until Wait-Process returns. |
| 49 | + `$t = Add-Type -Name Power -Namespace T3 -PassThru -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'; [void]$t::SetThreadExecutionState([uint32]2147483649); Wait-Process -Id ${serverPid}`, |
| 50 | + ], |
| 51 | + }; |
| 52 | + default: |
| 53 | + return undefined; |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +/** Holds while `wanted` is true and for `grace` after it turns false; a true inside the grace keeps the same hold. */ |
| 58 | +export const holdWhileWanted = <E, R>( |
| 59 | + wanted: Stream.Stream<boolean, E, R>, |
| 60 | + hold: Effect.Effect<void, never, Scope.Scope>, |
| 61 | + grace: Duration.Input = RELEASE_GRACE, |
| 62 | +) => |
| 63 | + wanted.pipe( |
| 64 | + Stream.changes, |
| 65 | + Stream.switchMap((on) => |
| 66 | + on ? Stream.succeed(true) : Stream.fromEffect(Effect.as(Effect.sleep(grace), false)), |
| 67 | + ), |
| 68 | + Stream.changes, |
| 69 | + Stream.switchMap((on) => (on ? Stream.unwrap(Effect.as(hold, Stream.never)) : Stream.empty)), |
| 70 | + Stream.runDrain, |
| 71 | + ); |
| 72 | + |
| 73 | +export const layer = Layer.effectDiscard( |
| 74 | + Effect.gen(function* () { |
| 75 | + const command = inhibitorCommand(yield* HostProcess.Platform, process.pid); |
| 76 | + if (command === undefined) return; |
| 77 | + const settings = yield* Settings.ServerSettingsService; |
| 78 | + const engine = yield* Orchestrator.OrchestratorV2; |
| 79 | + const sql = yield* SqlClient.SqlClient; |
| 80 | + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 81 | + |
| 82 | + const hasActiveRun = sql<{ readonly active: number }>` |
| 83 | + SELECT EXISTS ( |
| 84 | + SELECT 1 FROM orchestration_v2_projection_runs |
| 85 | + WHERE status IN ('preparing', 'starting', 'running') |
| 86 | + ) AS active |
| 87 | + `.pipe( |
| 88 | + Effect.map((rows) => rows[0]?.active === 1), |
| 89 | + Effect.catchCause((cause) => |
| 90 | + Effect.logWarning("keep-awake could not read active runs", { cause }).pipe( |
| 91 | + Effect.as(false), |
| 92 | + ), |
| 93 | + ), |
| 94 | + ); |
| 95 | + const active = Stream.concat( |
| 96 | + Stream.fromEffect(hasActiveRun), |
| 97 | + engine.streamDomainEvents.pipe( |
| 98 | + Stream.filter((event) => event.type === "run.created" || event.type === "run.updated"), |
| 99 | + Stream.mapEffect(() => hasActiveRun), |
| 100 | + ), |
| 101 | + ); |
| 102 | + const enabled = Stream.unwrap( |
| 103 | + Effect.gen(function* () { |
| 104 | + const changes = yield* settings.subscribeChanges; |
| 105 | + const current = yield* settings.getSettings.pipe( |
| 106 | + Effect.map((value) => value.keepAwakeWhileAgentsWork), |
| 107 | + Effect.orElseSucceed(() => true), |
| 108 | + ); |
| 109 | + return Stream.concat( |
| 110 | + Stream.succeed(current), |
| 111 | + Stream.map(changes, (value) => value.keepAwakeWhileAgentsWork), |
| 112 | + ); |
| 113 | + }), |
| 114 | + ); |
| 115 | + |
| 116 | + const hold = spawner |
| 117 | + .spawn( |
| 118 | + ChildProcess.make(command.command, command.args, { |
| 119 | + detached: false, |
| 120 | + shell: false, |
| 121 | + stdin: "ignore", |
| 122 | + stdout: "ignore", |
| 123 | + stderr: "ignore", |
| 124 | + }), |
| 125 | + ) |
| 126 | + .pipe( |
| 127 | + Effect.tap((child) => |
| 128 | + Effect.logInfo("keep-awake holding sleep inhibitor", { pid: Number(child.pid) }), |
| 129 | + ), |
| 130 | + Effect.tap(() => |
| 131 | + Effect.addFinalizer(() => Effect.logInfo("keep-awake released sleep inhibitor")), |
| 132 | + ), |
| 133 | + Effect.asVoid, |
| 134 | + Effect.catchCause((cause) => |
| 135 | + Effect.logWarning("keep-awake could not start the sleep inhibitor", { |
| 136 | + command: command.command, |
| 137 | + cause, |
| 138 | + }), |
| 139 | + ), |
| 140 | + ); |
| 141 | + |
| 142 | + yield* forkParked( |
| 143 | + holdWhileWanted( |
| 144 | + Stream.zipLatestWith(enabled, active, (on, busy) => on && busy), |
| 145 | + hold, |
| 146 | + ).pipe(Effect.catchCause((cause) => Effect.logWarning("keep-awake stopped", { cause }))), |
| 147 | + ); |
| 148 | + }), |
| 149 | +); |
0 commit comments