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

updatesTestHarness.ts

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