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

DesktopPackagedSmoke.ts

308 lines11.4 KB

1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6​
7import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
8import type { DesktopBackendInstance, DesktopBackendSnapshot } from "../backend/DesktopBackendManager.ts";
9import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
10import * as ElectronApp from "../electron/ElectronApp.ts";
11import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
12import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
13import * as DesktopEnvironment from "./DesktopEnvironment.ts";
14import { resolveDesktopBackendPort } from "./DesktopApp.ts";
15​
16export const PACKAGED_SMOKE_FLAG = "T3CODE_DESKTOP_PACKAGED_SMOKE";
17export const PACKAGED_SMOKE_RECEIPT = "T3CODE_DESKTOP_PACKAGED_SMOKE_RECEIPT";
18export const PACKAGED_SMOKE_WSL_DISTRO = "T3CODE_DESKTOP_PACKAGED_SMOKE_WSL_DISTRO";
19​
20const WINDOWS_READY_TIMEOUT = Duration.seconds(45);
21const WSL_READY_TIMEOUT = Duration.seconds(120);
22const STOP_TIMEOUT = Duration.seconds(15);
23​
24export class DesktopPackagedSmokeConfigurationError extends Schema.TaggedErrorClass<DesktopPackagedSmokeConfigurationError>()(
25 "DesktopPackagedSmokeConfigurationError",
26 {
27 reason: Schema.String,
28 },
29) {
30 override get message(): string {
31 return `Packaged desktop smoke configuration is invalid: ${this.reason}`;
32 }
34​
35export class DesktopPackagedSmokeBackendError extends Schema.TaggedErrorClass<DesktopPackagedSmokeBackendError>()(
36 "DesktopPackagedSmokeBackendError",
37 {
38 backendId: Schema.String,
39 reason: Schema.String,
40 },
41) {
42 override get message(): string {
43 return `Packaged desktop smoke backend ${this.backendId} failed: ${this.reason}`;
44 }
46​
47export function isPackagedSmokeRequested(env: NodeJS.ProcessEnv = process.env): boolean {
48 return env[PACKAGED_SMOKE_FLAG]?.trim() === "1";
50​
51function optionalSmokeValue(name: string): string | null {
52 const value = process.env[name]?.trim();
53 return value ? value : null;
55​
56function snapshotJson(snapshot: DesktopBackendSnapshot) {
57 return {
58 desiredRunning: snapshot.desiredRunning,
59 ready: snapshot.ready,
60 activePid: Option.getOrNull(snapshot.activePid),
61 restartAttempt: snapshot.restartAttempt,
62 restartScheduled: snapshot.restartScheduled,
63 };
65​
66const describeReadyInstance = Effect.fn("desktop.packagedSmoke.describeReadyInstance")(
67 function* (instance: DesktopBackendInstance, timeout: Duration.Duration) {
68 const ready = yield* instance.waitForReady(timeout);
69 if (!ready) {
70 const snapshot = yield* instance.snapshot;
71 return yield* new DesktopPackagedSmokeBackendError({
72 backendId: instance.id,
73 reason: `did not become HTTP-ready before timeout (snapshot=${JSON.stringify(snapshotJson(snapshot))})`,
74 });
75 }
76​
77 const config = yield* instance.currentConfig;
78 if (Option.isNone(config)) {
79 return yield* new DesktopPackagedSmokeBackendError({
80 backendId: instance.id,
81 reason: "became ready without a resolved backend configuration",
82 });
83 }
84 const snapshot = yield* instance.snapshot;
85 return {
86 id: instance.id,
87 label: yield* instance.label,
88 httpBaseUrl: config.value.httpBaseUrl.href,
89 executablePath: config.value.executablePath,
90 entryPath: config.value.entryPath,
91 cwd: config.value.cwd,
92 port: config.value.bootstrap.port,
93 bindHost: config.value.bootstrap.host,
94 pid: Option.getOrNull(snapshot.activePid),
95 runningDistro: config.value.runningDistro ?? null,
96 wslNodePath: config.value.wslNodePath ?? null,
97 snapshot: snapshotJson(snapshot),
98 };
99 },
100);
101​
102function stopAll(instances: readonly DesktopBackendInstance[]) {
103 return Effect.forEach(instances, (instance) => instance.stop({ timeout: STOP_TIMEOUT }), {
104 concurrency: "unbounded",
105 }).pipe(Effect.asVoid);
107​
108function writeReceipt(receiptPath: string, value: unknown) {
109 return Effect.gen(function* () {
110 const fs = yield* FileSystem.FileSystem;
111 const environment = yield* DesktopEnvironment.DesktopEnvironment;
112 yield* fs.makeDirectory(environment.path.dirname(receiptPath), { recursive: true });
113 const temporaryPath = `${receiptPath}.${process.pid}.tmp`;
114 yield* fs.writeFileString(temporaryPath, `${JSON.stringify(value, null, 2)}\n`);
115 yield* fs.rename(temporaryPath, receiptPath);
116 });
118​
119const runSmoke = Effect.gen(function* () {
120 const environment = yield* DesktopEnvironment.DesktopEnvironment;
121 if (!environment.isPackaged) {
122 return yield* new DesktopPackagedSmokeConfigurationError({
123 reason: "the packaged smoke path may only run from an Electron packaged artifact",
124 });
125 }
126 if (environment.platform !== "win32") {
127 return yield* new DesktopPackagedSmokeConfigurationError({
128 reason: `the packaged lifecycle smoke currently targets Windows, got ${environment.platform}`,
129 });
130 }
131​
132 const receiptPath = optionalSmokeValue(PACKAGED_SMOKE_RECEIPT);
133 if (receiptPath === null) {
134 return yield* new DesktopPackagedSmokeConfigurationError({
135 reason: `${PACKAGED_SMOKE_RECEIPT} must name an absolute receipt path`,
136 });
137 }
138 if (!environment.path.isAbsolute(receiptPath)) {
139 return yield* new DesktopPackagedSmokeConfigurationError({
140 reason: `${PACKAGED_SMOKE_RECEIPT} must be absolute: ${receiptPath}`,
141 });
142 }
143​
144 const electronApp = yield* ElectronApp.ElectronApp;
145 const settingsService = yield* DesktopAppSettings.DesktopAppSettings;
146 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
147 const pool = yield* DesktopBackendPool.DesktopBackendPool;
148 const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
149 const startedAt = new Date().toISOString();
150 const requestedDistro = optionalSmokeValue(PACKAGED_SMOKE_WSL_DISTRO);
151​
152 yield* electronApp.whenReady;
153 yield* settingsService.load;
154 yield* settingsService.setServerExposureMode("local-only");
155 yield* settingsService.setWslOnly(false);
156​
157 if (requestedDistro === null) {
158 yield* settingsService.setWslBackendEnabled(false);
159 } else {
160 yield* settingsService.setWslDistro(requestedDistro);
161 yield* settingsService.setWslBackendEnabled(true);
162 }
163​
164 const portSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
165 yield* serverExposure.configureFromSettings({ port: portSelection.port });
166​
167 const primary = yield* pool.primary;
168 yield* primary.start;
169 const windowsBackend = yield* describeReadyInstance(primary, WINDOWS_READY_TIMEOUT);
170​
171 let wslBackendReceipt: {
172 readonly id: string;
173 readonly label: string;
174 readonly httpBaseUrl: string;
175 readonly executablePath: string;
176 readonly entryPath: string;
177 readonly cwd: string;
178 readonly port: number;
179 readonly bindHost: string;
180 readonly pid: number | null;
181 readonly runningDistro: string | null;
182 readonly wslNodePath: string | null;
183 readonly snapshot: ReturnType<typeof snapshotJson>;
184 } | null = null;
185 if (requestedDistro !== null) {
186 yield* wslBackend.retry;
187 const targetId = DesktopBackendPool.BackendInstanceId(
188 `${DesktopWslBackend.WSL_INSTANCE_ID_PREFIX}${requestedDistro}`,
189 );
190 const target = yield* pool.get(targetId);
191 if (Option.isNone(target)) {
192 const diagnostic = yield* wslBackend.lastDiagnostic;
193 return yield* new DesktopPackagedSmokeBackendError({
194 backendId: targetId,
195 reason: Option.match(diagnostic, {
196 onNone: () => "WSL orchestrator did not register the requested backend",
197 onSome: (value) => value.message,
198 }),
199 });
200 }
201 wslBackendReceipt = yield* describeReadyInstance(target.value, WSL_READY_TIMEOUT);
202 }
203​
204 const beforeStopInstances = yield* pool.list;
205 const beforeStop = yield* Effect.forEach(beforeStopInstances, (instance) =>
206 instance.snapshot.pipe(Effect.map((snapshot) => ({ id: instance.id, snapshot: snapshotJson(snapshot) }))),
207 );
208​
209 yield* stopAll(beforeStopInstances);
210​
211 const afterFirstStopInstances = yield* pool.list;
212 const afterFirstStop = yield* Effect.forEach(afterFirstStopInstances, (instance) =>
213 instance.snapshot.pipe(Effect.map((snapshot) => ({ id: instance.id, snapshot: snapshotJson(snapshot) }))),
214 );
215 for (const entry of afterFirstStop) {
216 if (entry.snapshot.ready || entry.snapshot.activePid !== null || entry.snapshot.desiredRunning) {
217 return yield* new DesktopPackagedSmokeBackendError({
218 backendId: entry.id,
219 reason: `backend remained active after first shutdown: ${JSON.stringify(entry.snapshot)}`,
220 });
221 }
222 }
223​
224 // A second cycle catches lifecycle bugs that only appear after the first
225 // process tree has exited: stale ports, stale desiredRunning state, and WSL
226 // retry/re-registration problems. This still uses the same packaged process.
227 yield* primary.start;
228 const restartedWindowsBackend = yield* describeReadyInstance(primary, WINDOWS_READY_TIMEOUT);
229 let restartedWslBackend: typeof wslBackendReceipt = null;
230 if (requestedDistro !== null) {
231 yield* wslBackend.retry;
232 const targetId = DesktopBackendPool.BackendInstanceId(
233 `${DesktopWslBackend.WSL_INSTANCE_ID_PREFIX}${requestedDistro}`,
234 );
235 const target = yield* pool.get(targetId);
236 if (Option.isNone(target)) {
237 return yield* new DesktopPackagedSmokeBackendError({
238 backendId: targetId,
239 reason: "WSL orchestrator did not re-register the backend during packaged restart verification",
240 });
241 }
242 restartedWslBackend = yield* describeReadyInstance(target.value, WSL_READY_TIMEOUT);
243 }
244​
245 const finalStopInstances = yield* pool.list;
246 yield* stopAll(finalStopInstances);
247 const afterStopInstances = yield* pool.list;
248 const afterStop = yield* Effect.forEach(afterStopInstances, (instance) =>
249 instance.snapshot.pipe(Effect.map((snapshot) => ({ id: instance.id, snapshot: snapshotJson(snapshot) }))),
250 );
251​
252 for (const entry of afterStop) {
253 if (entry.snapshot.ready || entry.snapshot.activePid !== null || entry.snapshot.desiredRunning) {
254 return yield* new DesktopPackagedSmokeBackendError({
255 backendId: entry.id,
256 reason: `backend remained active after final shutdown: ${JSON.stringify(entry.snapshot)}`,
257 });
258 }
259 }
260​
261 const receipt = {
262 schemaVersion: 1,
263 status: "success",
264 startedAt,
265 finishedAt: new Date().toISOString(),
266 app: {
267 version: environment.appVersion,
268 platform: environment.platform,
269 arch: environment.processArch,
270 isPackaged: environment.isPackaged,
271 resourcesPath: environment.resourcesPath,
272 appRoot: environment.appRoot,
273 stateDir: environment.stateDir,
274 pid: process.pid,
275 },
276 portSelection: {
277 port: portSelection.port,
278 selectedByScan: portSelection.selectedByScan,
279 },
280 requestedWslDistro: requestedDistro,
281 windowsBackend,
282 wslBackend: wslBackendReceipt,
283 beforeStop,
284 afterFirstStop,
285 restartCycle: {
286 windowsBackend: restartedWindowsBackend,
287 wslBackend: restartedWslBackend,
288 },
289 afterStop,
290 };
291​
292 yield* writeReceipt(receiptPath, receipt);
293 yield* electronApp.quit;
294});
295​
296export const program = Effect.scoped(
297 Effect.gen(function* () {
298 const electronApp = yield* ElectronApp.ElectronApp;
299 yield* runSmoke.pipe(Effect.ensuring(electronApp.quit));
300 }),
301).pipe(
302 Effect.withSpan("desktop.packagedSmoke"),
303 Effect.tapErrorCause((cause) =>
304 Effect.logError("packaged desktop lifecycle smoke failed").pipe(
305 Effect.annotateLogs({ cause: String(cause) }),
306 ),
307 ),
308);