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

updatesTestHarness.ts

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