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

DesktopPowerRecovery.ts

146 lines5.5 KB

1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Ref from "effect/Ref";
7import * as Scope from "effect/Scope";
8import * as Semaphore from "effect/Semaphore";
9​
10import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
11import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
12import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
13import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
14import * as DesktopEnvironment from "./DesktopEnvironment.ts";
15import { makeComponentLogger } from "./DesktopObservability.ts";
16import * as DesktopState from "./DesktopState.ts";
17​
18const RESUME_SETTLE_DELAY = Duration.seconds(2);
19const BACKEND_PROBE_TIMEOUT = Duration.seconds(2);
20const BACKEND_STOP_TIMEOUT = Duration.seconds(6);
21const BACKEND_RESTART_READY_TIMEOUT = Duration.seconds(20);
22​
23const { logInfo: logRecoveryInfo, logWarning: logRecoveryWarning } =
24 makeComponentLogger("desktop-power-recovery");
25​
26export type DesktopPowerRecoveryRuntimeServices =
27 | DesktopBackendPool.DesktopBackendPool
28 | DesktopEnvironment.DesktopEnvironment
29 | DesktopState.DesktopState
30 | DesktopWslBackend.DesktopWslBackend
31 | ElectronPowerMonitor.ElectronPowerMonitor;
32​
33export class DesktopPowerRecovery extends Context.Service<
34 DesktopPowerRecovery,
35 {
36 readonly register: Effect.Effect<
37 void,
38 never,
39 Scope.Scope | DesktopPowerRecoveryRuntimeServices
40 >;
41 }
42>()("@t3tools/desktop/app/DesktopPowerRecovery") {}
43​
44export const reconcileInstanceAfterResume = Effect.fn("desktop.powerRecovery.reconcileInstance")(
45 function* (instance: DesktopBackendManager.DesktopBackendInstance) {
46 const before = yield* instance.snapshot;
47 if (!before.desiredRunning) return;
48​
49 const healthy = before.ready
50 ? yield* instance.probeReady(BACKEND_PROBE_TIMEOUT)
51 : false;
52 if (healthy) {
53 yield* logRecoveryInfo("backend remained healthy after resume", { id: instance.id });
54 return;
55 }
56​
57 yield* logRecoveryWarning("backend unhealthy after resume; restarting", {
58 id: instance.id,
59 readyBeforeProbe: before.ready,
60 pid: Option.getOrNull(before.activePid),
61 restartScheduled: before.restartScheduled,
62 });
63​
64 yield* instance.stop({ timeout: BACKEND_STOP_TIMEOUT });
65 yield* instance.start;
66 const ready = yield* instance.waitForReady(BACKEND_RESTART_READY_TIMEOUT);
67 if (ready) {
68 yield* logRecoveryInfo("backend recovered after resume", { id: instance.id });
69 return;
70 }
71​
72 yield* logRecoveryWarning("backend did not recover inside resume window", {
73 id: instance.id,
74 timeoutMs: Duration.toMillis(BACKEND_RESTART_READY_TIMEOUT),
75 });
76 },
77);
78​
79export const make = DesktopPowerRecovery.of({
80 register: Effect.gen(function* () {
81 const environment = yield* DesktopEnvironment.DesktopEnvironment;
82 if (environment.platform !== "win32") return;
83​
84 const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
85 const pool = yield* DesktopBackendPool.DesktopBackendPool;
86 const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
87 const state = yield* DesktopState.DesktopState;
88 const scope = yield* Scope.Scope;
89 const generationRef = yield* Ref.make(0);
90 const recoveryMutex = yield* Semaphore.make(1);
91 const context = yield* Effect.context<DesktopPowerRecoveryRuntimeServices>();
92 const runEffect = Effect.runPromiseWith(context);
93​
94 const invalidatePendingRecovery = Ref.update(generationRef, (generation) => generation + 1);
95​
96 const recoverAfterResume = Effect.gen(function* () {
97 const generation = yield* Ref.updateAndGet(generationRef, (current) => current + 1);
98 yield* logRecoveryInfo("Windows resume observed; scheduling backend health reconciliation", {
99 generation,
100 settleDelayMs: Duration.toMillis(RESUME_SETTLE_DELAY),
101 });
102 yield* Effect.sleep(RESUME_SETTLE_DELAY);
103 yield* recoveryMutex.withPermits(1)(
104 Effect.gen(function* () {
105 if ((yield* Ref.get(generationRef)) !== generation) return;
106 if (yield* Ref.get(state.quitting)) return;
107​
108 const instances = yield* pool.list;
109 yield* Effect.forEach(instances, reconcileInstanceAfterResume, {
110 concurrency: 1,
111 discard: true,
112 });
113​
114 // A WSL secondary may have disappeared entirely while Windows slept.
115 // Reconcile after existing instances are probed/restarted so the normal
116 // orchestrator can recreate a missing secondary and re-resolve its distro
117 // address with the current WSL network state.
118 yield* wslBackend.reconcile;
119 }),
120 );
121 }).pipe(
122 Effect.catchCause((cause) =>
123 logRecoveryWarning("resume recovery failed", { cause: String(cause) }),
124 ),
125 Effect.withSpan("desktop.powerRecovery.resume"),
126 );
127​
128 const launchScoped = (effect: Effect.Effect<void>) => {
129 void runEffect(Effect.forkIn(effect, scope).pipe(Effect.asVoid));
130 };
131​
132 yield* powerMonitor.onSimpleEvent("suspend", () => {
133 launchScoped(
134 invalidatePendingRecovery.pipe(
135 Effect.andThen(logRecoveryInfo("Windows suspend observed")),
136 Effect.withSpan("desktop.powerRecovery.suspend"),
137 ),
138 );
139 });
140 yield* powerMonitor.onSimpleEvent("resume", () => {
141 launchScoped(recoverAfterResume);
142 });
143 }),
144});
145​
146export const layer = Layer.succeed(DesktopPowerRecovery, make);