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

updatesTestHarness.ts

317 lines12.3 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import type { DesktopUpdateState } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as PlatformError from "effect/PlatformError";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8​
9import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
10import * as DesktopConfig from "../app/DesktopConfig.ts";
11import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
12import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
13import * as ElectronWindow from "../electron/ElectronWindow.ts";
14import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
15import * as DesktopState from "../app/DesktopState.ts";
16import * as DesktopUpdates from "./DesktopUpdates.ts";
17​
18export const flushCallbacks = Effect.yieldNow;
19​
20export interface UpdatesHarnessOptions {
21 readonly checkForUpdates?: Effect.Effect<
22 void,
23 ElectronUpdater.ElectronUpdaterCheckForUpdatesError
24 >;
25 readonly beforeSetUpdateChannel?: Effect.Effect<void>;
26 readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
27 readonly setDisableDifferentialDownload?: Effect.Effect<void>;
28 readonly downloadUpdate?: Effect.Effect<void>;
29 readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
30 readonly stopBackend?: Effect.Effect<void>;
31 readonly startBackend?: Effect.Effect<void>;
32 readonly backendDesiredRunning?: boolean;
33 readonly backendInstances?: ReadonlyArray<DesktopBackendPool.DesktopBackendInstance>;
34 readonly env?: Record<string, string | undefined>;
35 readonly platform?: NodeJS.Platform;
36 readonly packageType?: string | undefined;
37 readonly installRecord?: string | undefined;
38 readonly appVersion?: string;
39 /** Starts from in-memory settings with this track saved, as after a restart. */
40 readonly savedChannel?: DesktopAppSettings.DesktopSettings["updateChannel"];
41 /** Adds a WSL backend beside the primary, as on a Windows host with WSL enabled. */
42 readonly wslBackend?: boolean;
44​
45export function makeHarness(options: UpdatesHarnessOptions = {}) {
46 let checkCount = 0;
47 let quitAndInstallCount = 0;
48 let downloadCount = 0;
49 let allowDowngrade = false;
50 const checkAllowedDowngrade: boolean[] = [];
51 let fullChangelog = false;
52 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
53 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
54 const sentStates: DesktopUpdateState[] = [];
55 const installSteps: string[] = [];
56​
57 const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
58 const eventListeners = listeners.get(eventName) ?? new Set();
59 eventListeners.add(listener);
60 listeners.set(eventName, eventListeners);
61 };
62​
63 const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
64 const eventListeners = listeners.get(eventName);
65 if (!eventListeners) {
66 return;
67 }
68 eventListeners.delete(listener);
69 if (eventListeners.size === 0) {
70 listeners.delete(eventName);
71 }
72 };
73​
74 const layerUpdater = Layer.succeed(ElectronUpdater.ElectronUpdater, {
75 setFeedURL: (options) =>
76 Effect.sync(() => {
77 feedUrls.push(options);
78 }),
79 setAutoDownload: () => Effect.void,
80 setAutoInstallOnAppQuit: () => Effect.void,
81 setChannel: () => Effect.void,
82 setAllowPrerelease: () => Effect.void,
83 allowDowngrade: Effect.sync(() => allowDowngrade),
84 setAllowDowngrade: (value) =>
85 Effect.sync(() => {
86 allowDowngrade = value;
87 }),
88 setFullChangelog: (value) =>
89 Effect.sync(() => {
90 fullChangelog = value;
91 }),
92 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
93 checkForUpdates: Effect.sync(() => {
94 checkCount += 1;
95 checkAllowedDowngrade.push(allowDowngrade);
96 }).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
97 downloadUpdate: Effect.sync(() => {
98 downloadCount += 1;
99 }).pipe(Effect.andThen(options.downloadUpdate ?? Effect.void)),
100 quitAndInstall: () =>
101 Effect.sync(() => {
102 quitAndInstallCount += 1;
103 installSteps.push("quitAndInstall");
104 }).pipe(Effect.andThen(options.quitAndInstall ?? Effect.void)),
105 on: (eventName, listener) =>
106 Effect.acquireRelease(
107 Effect.sync(() => {
108 addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
109 }),
110 () =>
111 Effect.sync(() => {
112 removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
113 }),
114 ).pipe(Effect.asVoid),
115 } satisfies ElectronUpdater.ElectronUpdater["Service"]);
116​
117 const layerWindow = Layer.succeed(ElectronWindow.ElectronWindow, {
118 create: () => Effect.die("unexpected BrowserWindow creation"),
119 main: Effect.succeedNone,
120 currentMainOrFirst: Effect.succeedNone,
121 focusedMainOrFirst: Effect.succeedNone,
122 setMain: () => Effect.void,
123 clearMain: () => Effect.void,
124 prepareReveal: () => Effect.succeed(false),
125 reveal: () => Effect.void,
126 sendAll: (_channel, state) =>
127 Effect.sync(() => {
128 sentStates.push(state as DesktopUpdateState);
129 }),
130 destroyAll: Effect.sync(() => {
131 installSteps.push("destroyAll");
132 }),
133 syncAllAppearance: () => Effect.void,
134 } satisfies ElectronWindow.ElectronWindow["Service"]);
135​
136 let backendDesiredRunning = options.backendDesiredRunning ?? true;
137 const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
138 id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
139 label: Effect.succeed("Windows"),
140 start: Effect.sync(() => {
141 backendDesiredRunning = true;
142 installSteps.push("startBackend");
143 }).pipe(Effect.andThen(options.startBackend ?? Effect.void)),
144 stop: () =>
145 Effect.sync(() => {
146 backendDesiredRunning = false;
147 }).pipe(Effect.andThen(options.stopBackend ?? Effect.void)),
148 currentConfig: Effect.succeedNone,
149 snapshot: Effect.sync(() => ({
150 desiredRunning: backendDesiredRunning,
151 ready: false,
152 activePid: Option.none(),
153 restartAttempt: 0,
154 restartScheduled: false,
155 })),
156 waitForReady: () => Effect.succeed(true),
157 };
158 const layerBackend = DesktopBackendPool.layerTest(
159 options.backendInstances ??
160 (options.wslBackend
161 ? [
162 stubBackendInstance,
163 {
164 ...stubBackendInstance,
165 id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
166 label: Effect.succeed("Ubuntu"),
167 },
168 ]
169 : [stubBackendInstance]),
170 );
171​
172 const layerEnvironment = DesktopEnvironment.layer({
173 dirname: "/repo/apps/desktop/src",
174 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
175 platform: options.platform ?? "darwin",
176 processArch: "x64",
177 appVersion: options.appVersion ?? "1.2.3",
178 appPath: "/repo",
179 isPackaged: true,
180 resourcesPath: "/missing/resources",
181 runningUnderArm64Translation: false,
182 }).pipe(
183 Layer.provide(
184 Layer.mergeAll(
185 NodeServices.layer,
186 DesktopConfig.layerTest({
187 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
188 T3CODE_DESKTOP_MOCK_UPDATES: "true",
189 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
190 ...options.env,
191 }),
192 ),
193 ),
194 );
195​
196 let testSettings: DesktopAppSettings.DesktopSettings = {
197 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
198 ...(options.savedChannel === undefined
199 ? {}
200 : { updateChannel: options.savedChannel, updateChannelConfiguredByUser: true }),
201 };
202 const setUpdateChannelError = options.setUpdateChannelError;
203 const layerSettings =
204 setUpdateChannelError || options.beforeSetUpdateChannel || options.savedChannel
205 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
206 get: Effect.sync(() => testSettings),
207 load: Effect.sync(() => testSettings),
208 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
209 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
210 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
211 setUpdateChannel: (channel) =>
212 setUpdateChannelError
213 ? Effect.fail(setUpdateChannelError)
214 : (options.beforeSetUpdateChannel ?? Effect.void).pipe(
215 Effect.andThen(
216 Effect.sync(() => {
217 const changed = testSettings.updateChannel !== channel;
218 testSettings = {
219 ...testSettings,
220 updateChannel: channel,
221 updateChannelConfiguredByUser: true,
222 };
223 return { settings: testSettings, changed };
224 }),
225 ),
226 ),
227 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
228 setWslDistro: () => Effect.die("unexpected WSL distro change"),
229 setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"),
230 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
231 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
232 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
233 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
234 : DesktopAppSettings.layer;
235​
236 const updateRestartMarkers = new Set<string>();
237 const installRecords = new Map<string, string>();
238 let previousInstallRecord = options.installRecord;
239 const isInstallRecord = (path: string) =>
240 path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE);
241 const layerFileSystem = FileSystem.layerNoop({
242 readFileString: (path) => {
243 const installRecord = isInstallRecord(path)
244 ? (installRecords.get(path) ?? previousInstallRecord)
245 : undefined;
246 if (installRecord !== undefined) return Effect.succeed(installRecord);
247 return path === "/missing/resources/package-type" && options.packageType !== undefined
248 ? Effect.succeed(options.packageType)
249 : Effect.fail(
250 PlatformError.systemError({
251 module: "FileSystem",
252 method: "readFileString",
253 _tag: "NotFound",
254 pathOrDescriptor: path,
255 }),
256 );
257 },
258 makeDirectory: () => Effect.void,
259 writeFileString: (path, data) =>
260 Effect.sync(() => {
261 if (isInstallRecord(path)) installRecords.set(path, data);
262 else updateRestartMarkers.add(path);
263 }),
264 remove: (path) =>
265 Effect.sync(() => {
266 updateRestartMarkers.delete(path);
267 installRecords.delete(path);
268 if (isInstallRecord(path)) previousInstallRecord = undefined;
269 }),
270 });
271​
272 const layer = DesktopUpdates.layer.pipe(
273 Layer.provide(layerFileSystem),
274 Layer.provideMerge(layerUpdater),
275 Layer.provideMerge(layerWindow),
276 Layer.provideMerge(layerBackend),
277 Layer.provideMerge(DesktopState.layer),
278 Layer.provideMerge(layerSettings),
279 Layer.provideMerge(
280 DesktopConfig.layerTest({
281 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
282 T3CODE_DESKTOP_MOCK_UPDATES: "true",
283 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
284 ...options.env,
285 }),
286 ),
287 Layer.provideMerge(layerEnvironment),
288 Layer.provideMerge(NodeServices.layer),
289 );
290​
291 return {
292 layer,
293 checkCount: () => checkCount,
294 quitAndInstalls: () => quitAndInstallCount,
295 installSteps,
296 updateRestartMarkers,
297 installRecords,
298 previousInstallRecord: () => previousInstallRecord,
299 downloadCount: () => downloadCount,
300 feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls,
301 fullChangelog: () => fullChangelog,
302 /** Whether each feed check could offer an older release, and the flag now. */
303 checkAllowedDowngrade,
304 allowDowngrade: () => allowDowngrade,
305 listenerCount: () =>
306 Array.from(listeners.values()).reduce(
307 (total, eventListeners) => total + eventListeners.size,
308 0,
309 ),
310 sentStates,
311 emit: (eventName: string, payload?: unknown) => {
312 for (const listener of listeners.get(eventName) ?? []) {
313 listener(payload);
314 }
315 },
316 };