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

updatesTestHarness.ts

244 lines9.4 KB

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