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

updatesTestHarness.ts

277 lines10.6 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​
18/** Shared DesktopUpdates test harness: a fully stubbed updater layer whose
19 electron-updater events are driven by hand via `emit`. Used by
20 DesktopUpdates.test.ts and DesktopRemoteUpdates.test.ts. */
21​
22export const flushCallbacks = Effect.yieldNow;
23​
24export interface UpdatesHarnessOptions {
25 readonly checkForUpdates?: Effect.Effect<
26 void,
27 ElectronUpdater.ElectronUpdaterCheckForUpdatesError
28 >;
29 readonly beforeSetUpdateChannel?: Effect.Effect<void>;
30 readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
31 readonly setDisableDifferentialDownload?: Effect.Effect<void>;
32 readonly downloadUpdate?: Effect.Effect<void>;
33 readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
34 readonly stopBackend?: Effect.Effect<void>;
35 readonly startBackend?: Effect.Effect<void>;
36 readonly env?: Record<string, string | undefined>;
37 readonly platform?: NodeJS.Platform;
38 /** Contents of the resources/package-type marker a Linux package ships. */
39 readonly packageType?: string | undefined;
41​
42export function makeHarness(options: UpdatesHarnessOptions = {}) {
43 let checkCount = 0;
44 let quitAndInstallCount = 0;
45 let downloadCount = 0;
46 let allowDowngrade = false;
47 let fullChangelog = false;
48 const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
49 const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
50 const sentStates: DesktopUpdateState[] = [];
51 const installSteps: string[] = [];
52​
53 const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
54 const eventListeners = listeners.get(eventName) ?? new Set();
55 eventListeners.add(listener);
56 listeners.set(eventName, eventListeners);
57 };
58​
59 const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
60 const eventListeners = listeners.get(eventName);
61 if (!eventListeners) {
62 return;
63 }
64 eventListeners.delete(listener);
65 if (eventListeners.size === 0) {
66 listeners.delete(eventName);
67 }
68 };
69​
70 const layerUpdater = Layer.succeed(ElectronUpdater.ElectronUpdater, {
71 setFeedURL: (options) =>
72 Effect.sync(() => {
73 feedUrls.push(options);
74 }),
75 setAutoDownload: () => Effect.void,
76 setAutoInstallOnAppQuit: () => Effect.void,
77 setChannel: () => Effect.void,
78 setAllowPrerelease: () => Effect.void,
79 allowDowngrade: Effect.sync(() => allowDowngrade),
80 setAllowDowngrade: (value) =>
81 Effect.sync(() => {
82 allowDowngrade = value;
83 }),
84 setFullChangelog: (value) =>
85 Effect.sync(() => {
86 fullChangelog = value;
87 }),
88 setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
89 checkForUpdates: Effect.sync(() => {
90 checkCount += 1;
91 }).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
92 downloadUpdate: Effect.sync(() => {
93 downloadCount += 1;
94 }).pipe(Effect.andThen(options.downloadUpdate ?? Effect.void)),
95 quitAndInstall: () =>
96 Effect.sync(() => {
97 quitAndInstallCount += 1;
98 installSteps.push("quitAndInstall");
99 }).pipe(Effect.andThen(options.quitAndInstall ?? Effect.void)),
100 on: (eventName, listener) =>
101 Effect.acquireRelease(
102 Effect.sync(() => {
103 addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
104 }),
105 () =>
106 Effect.sync(() => {
107 removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
108 }),
109 ).pipe(Effect.asVoid),
110 } satisfies ElectronUpdater.ElectronUpdater["Service"]);
111​
112 const layerWindow = Layer.succeed(ElectronWindow.ElectronWindow, {
113 create: () => Effect.die("unexpected BrowserWindow creation"),
114 main: Effect.succeedNone,
115 currentMainOrFirst: Effect.succeedNone,
116 focusedMainOrFirst: Effect.succeedNone,
117 setMain: () => Effect.void,
118 clearMain: () => Effect.void,
119 prepareReveal: () => Effect.succeed(false),
120 reveal: () => Effect.void,
121 sendAll: (_channel, state) =>
122 Effect.sync(() => {
123 sentStates.push(state as DesktopUpdateState);
124 }),
125 destroyAll: Effect.sync(() => {
126 installSteps.push("destroyAll");
127 }),
128 syncAllAppearance: () => Effect.void,
129 } satisfies ElectronWindow.ElectronWindow["Service"]);
130​
131 const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
132 id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
133 label: Effect.succeed("Windows"),
134 start: Effect.sync(() => {
135 installSteps.push("startBackend");
136 }).pipe(Effect.andThen(options.startBackend ?? Effect.void)),
137 stop: () => options.stopBackend ?? Effect.void,
138 currentConfig: Effect.succeedNone,
139 snapshot: Effect.succeed({
140 desiredRunning: false,
141 ready: false,
142 activePid: Option.none(),
143 restartAttempt: 0,
144 restartScheduled: false,
145 }),
146 waitForReady: () => Effect.succeed(true),
147 };
148 const layerBackend = DesktopBackendPool.layerTest([stubBackendInstance]);
149​
150 const layerEnvironment = DesktopEnvironment.layer({
151 dirname: "/repo/apps/desktop/src",
152 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
153 platform: options.platform ?? "darwin",
154 processArch: "x64",
155 appVersion: "1.2.3",
156 appPath: "/repo",
157 isPackaged: true,
158 resourcesPath: "/missing/resources",
159 runningUnderArm64Translation: false,
160 }).pipe(
161 Layer.provide(
162 Layer.mergeAll(
163 NodeServices.layer,
164 DesktopConfig.layerTest({
165 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
166 T3CODE_DESKTOP_MOCK_UPDATES: "true",
167 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
168 ...options.env,
169 }),
170 ),
171 ),
172 );
173​
174 let testSettings: DesktopAppSettings.DesktopSettings = {
175 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
176 };
177 const setUpdateChannelError = options.setUpdateChannelError;
178 const layerSettings =
179 setUpdateChannelError || options.beforeSetUpdateChannel
180 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
181 get: Effect.sync(() => testSettings),
182 load: Effect.sync(() => testSettings),
183 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
184 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
185 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
186 setUpdateChannel: (channel) =>
187 setUpdateChannelError
188 ? Effect.fail(setUpdateChannelError)
189 : (options.beforeSetUpdateChannel ?? Effect.void).pipe(
190 Effect.andThen(
191 Effect.sync(() => {
192 const changed = testSettings.updateChannel !== channel;
193 testSettings = {
194 ...testSettings,
195 updateChannel: channel,
196 updateChannelConfiguredByUser: true,
197 };
198 return { settings: testSettings, changed };
199 }),
200 ),
201 ),
202 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
203 setWslDistro: () => Effect.die("unexpected WSL distro change"),
204 setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"),
205 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
206 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
207 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
208 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
209 : DesktopAppSettings.layer;
210​
211 // Tracks the restart markers installs leave, so installs stay free of real
212 // disk I/O that would outrun the tests' settle loops.
213 const updateRestartMarkers = new Set<string>();
214 const layerFileSystem = FileSystem.layerNoop({
215 readFileString: (path) =>
216 path === "/missing/resources/package-type" && options.packageType !== undefined
217 ? Effect.succeed(options.packageType)
218 : Effect.fail(
219 PlatformError.systemError({
220 module: "FileSystem",
221 method: "readFileString",
222 _tag: "NotFound",
223 pathOrDescriptor: path,
224 }),
225 ),
226 makeDirectory: () => Effect.void,
227 writeFileString: (path) =>
228 Effect.sync(() => {
229 updateRestartMarkers.add(path);
230 }),
231 remove: (path) =>
232 Effect.sync(() => {
233 updateRestartMarkers.delete(path);
234 }),
235 });
236​
237 const layer = DesktopUpdates.layer.pipe(
238 Layer.provide(layerFileSystem),
239 Layer.provideMerge(layerUpdater),
240 Layer.provideMerge(layerWindow),
241 Layer.provideMerge(layerBackend),
242 Layer.provideMerge(DesktopState.layer),
243 Layer.provideMerge(layerSettings),
244 Layer.provideMerge(
245 DesktopConfig.layerTest({
246 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
247 T3CODE_DESKTOP_MOCK_UPDATES: "true",
248 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
249 ...options.env,
250 }),
251 ),
252 Layer.provideMerge(layerEnvironment),
253 Layer.provideMerge(NodeServices.layer),
254 );
255​
256 return {
257 layer,
258 checkCount: () => checkCount,
259 quitAndInstalls: () => quitAndInstallCount,
260 installSteps,
261 updateRestartMarkers,
262 downloadCount: () => downloadCount,
263 feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls,
264 fullChangelog: () => fullChangelog,
265 listenerCount: () =>
266 Array.from(listeners.values()).reduce(
267 (total, eventListeners) => total + eventListeners.size,
268 0,
269 ),
270 sentStates,
271 emit: (eventName: string, payload?: unknown) => {
272 for (const listener of listeners.get(eventName) ?? []) {
273 listener(payload);
274 }
275 },
276 };