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

updatesTestHarness.ts

242 lines9.2 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 reveal: () => Effect.void,
115 sendAll: (_channel, state) =>
116 Effect.sync(() => {
117 sentStates.push(state as DesktopUpdateState);
118 }),
119 destroyAll: Effect.sync(() => {
120 installSteps.push("destroyAll");
121 }),
122 syncAllAppearance: () => Effect.void,
123 } satisfies ElectronWindow.ElectronWindow["Service"]);
124​
125 const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
126 id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
127 label: Effect.succeed("Windows"),
128 start: Effect.sync(() => {
129 installSteps.push("startBackend");
130 }).pipe(Effect.andThen(options.startBackend ?? Effect.void)),
131 stop: () => options.stopBackend ?? Effect.void,
132 currentConfig: Effect.succeed(Option.none()),
133 snapshot: Effect.succeed({
134 desiredRunning: false,
135 ready: false,
136 activePid: Option.none(),
137 restartAttempt: 0,
138 restartScheduled: false,
139 }),
140 waitForReady: () => Effect.succeed(true),
141 };
142 const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
143​
144 const environmentLayer = DesktopEnvironment.layer({
145 dirname: "/repo/apps/desktop/src",
146 homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
147 platform: "darwin",
148 processArch: "x64",
149 appVersion: "1.2.3",
150 appPath: "/repo",
151 isPackaged: true,
152 resourcesPath: "/missing/resources",
153 runningUnderArm64Translation: false,
154 }).pipe(
155 Layer.provide(
156 Layer.mergeAll(
157 NodeServices.layer,
158 DesktopConfig.layerTest({
159 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
160 T3CODE_DESKTOP_MOCK_UPDATES: "true",
161 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
162 ...options.env,
163 }),
164 ),
165 ),
166 );
167​
168 let testSettings: DesktopAppSettings.DesktopSettings = {
169 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
170 };
171 const setUpdateChannelError = options.setUpdateChannelError;
172 const settingsLayer =
173 setUpdateChannelError || options.beforeSetUpdateChannel
174 ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
175 get: Effect.sync(() => testSettings),
176 load: Effect.sync(() => testSettings),
177 setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
178 setServerExposureMode: () => Effect.die("unexpected server exposure update"),
179 setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
180 setUpdateChannel: (channel) =>
181 setUpdateChannelError
182 ? Effect.fail(setUpdateChannelError)
183 : (options.beforeSetUpdateChannel ?? Effect.void).pipe(
184 Effect.andThen(
185 Effect.sync(() => {
186 const changed = testSettings.updateChannel !== channel;
187 testSettings = {
188 ...testSettings,
189 updateChannel: channel,
190 updateChannelConfiguredByUser: true,
191 };
192 return { settings: testSettings, changed };
193 }),
194 ),
195 ),
196 setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
197 setWslDistro: () => Effect.die("unexpected WSL distro change"),
198 setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
199 applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
200 applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
201 } satisfies DesktopAppSettings.DesktopAppSettings["Service"])
202 : DesktopAppSettings.layer;
203​
204 const layer = DesktopUpdates.layer.pipe(
205 Layer.provideMerge(updaterLayer),
206 Layer.provideMerge(windowLayer),
207 Layer.provideMerge(backendLayer),
208 Layer.provideMerge(DesktopState.layer),
209 Layer.provideMerge(settingsLayer),
210 Layer.provideMerge(
211 DesktopConfig.layerTest({
212 T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
213 T3CODE_DESKTOP_MOCK_UPDATES: "true",
214 T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
215 ...options.env,
216 }),
217 ),
218 Layer.provideMerge(environmentLayer),
219 Layer.provideMerge(NodeServices.layer),
220 );
221​
222 return {
223 layer,
224 checkCount: () => checkCount,
225 quitAndInstalls: () => quitAndInstallCount,
226 installSteps,
227 downloadCount: () => downloadCount,
228 feedUrls: () => feedUrls,
229 fullChangelog: () => fullChangelog,
230 listenerCount: () =>
231 Array.from(listeners.values()).reduce(
232 (total, eventListeners) => total + eventListeners.size,
233 0,
234 ),
235 sentStates,
236 emit: (eventName: string, payload?: unknown) => {
237 for (const listener of listeners.get(eventName) ?? []) {
238 listener(payload);
239 }
240 },
241 };