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

update.test.ts

242 lines10.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as NetService from "@t3tools/shared/Net";
5import * as ConfigProvider from "effect/ConfigProvider";
6import * as Console from "effect/Console";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import { Command } from "effect/cli";
13import { HttpClient, HttpClientResponse } from "effect/http";
14import { afterEach, vi } from "vite-plus/test";
15​
16import packageJson from "../../package.json" with { type: "json" };
17import * as BootService from "../cloud/bootService.ts";
18import { pinnedRuntimePaths } from "../cloud/pinnedRuntime.ts";
19import {
20 repointLauncher,
21 resolveLauncherPath,
22 resolveNewestVersion,
23 updateCommand,
24} from "./update.ts";
25​
26afterEach(() => vi.restoreAllMocks());
27​
28it.effect.each([
29 { environment: { GH_TOKEN: " gh-token ", GITHUB_TOKEN: "github-token" }, token: "gh-token" },
30 { environment: { GH_TOKEN: " ", GITHUB_TOKEN: " github-token " }, token: "github-token" },
31 { environment: { GITHUB_TOKEN: "github-token" }, token: "github-token" },
32 { environment: { GH_TOKEN: " ", GITHUB_TOKEN: " " }, token: undefined },
33 { environment: {}, token: undefined },
34])("selects release authentication from $environment", ({ environment, token }) =>
35 Effect.gen(function* () {
36 const authorizations: Array<string | undefined> = [];
37 const httpClient = HttpClient.make((request) => {
38 authorizations.push(request.headers.authorization);
39 return Effect.succeed(
40 HttpClientResponse.fromWeb(request, Response.json([{ tag_name: "v1.2.3" }])),
41 );
42 });
43 const version = yield* resolveNewestVersion("stable").pipe(
44 Effect.provideService(HostProcess.Environment, environment),
45 Effect.provideService(HttpClient.HttpClient, httpClient),
46 );
47 assert.equal(version, "1.2.3");
48 assert.deepStrictEqual(authorizations, [token === undefined ? undefined : `Bearer ${token}`]);
49 }),
50);
51​
52it.effect("authenticates each release page until the requested channel is found", () =>
53 Effect.gen(function* () {
54 const pages: string[] = [];
55 const httpClient = HttpClient.make((request) => {
56 const url = new URL(request.url);
57 assert.equal(url.origin, "https://api.github.com");
58 assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases");
59 assert.equal(request.headers.accept, "application/vnd.github+json");
60 assert.equal(request.headers.authorization, "Bearer gh-token");
61 const page = url.searchParams.get("page") ?? "";
62 pages.push(page);
63 const tag_name = page === "1" ? "v1.2.4-preview.20260101.1" : "v1.2.3";
64 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([{ tag_name }])));
65 });
66 const version = yield* resolveNewestVersion("stable").pipe(
67 Effect.provideService(HostProcess.Environment, { GH_TOKEN: "gh-token" }),
68 Effect.provideService(HttpClient.HttpClient, httpClient),
69 );
70 assert.equal(version, "1.2.3");
71 assert.deepStrictEqual(pages, ["1", "2"]);
72 }),
73);
74​
75it.layer(NodeServices.layer)("t3 update launcher", (it) => {
76 it.effect("repoints a symlink that lives in a runtime versions tree", () =>
77 Effect.gen(function* () {
78 const fs = yield* FileSystem.FileSystem;
79 const path = yield* Path.Path;
80 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
81 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
82 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
83 const launcher = path.join(root, "bin/t3");
84 for (const file of [oldExe, newExe]) {
85 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
86 yield* fs.writeFileString(file, "");
87 }
88 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
89 yield* fs.symlink(oldExe, launcher);
90​
91 const repointed = yield* repointLauncher({
92 launchedAs: launcher,
93 versionsDir: path.join(root, "runtime/versions"),
94 targetEntryPath: newExe,
95 });
96​
97 assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
98 assert.equal(yield* fs.readLink(launcher), newExe);
99 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
100 );
101​
102 it.effect("leaves a plain copy or a foreign symlink alone", () =>
103 Effect.gen(function* () {
104 const fs = yield* FileSystem.FileSystem;
105 const path = yield* Path.Path;
106 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
107 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
108 const copy = path.join(root, "copy/t3");
109 const foreign = path.join(root, "foreign/t3");
110 const elsewhere = path.join(root, "elsewhere/t3");
111 const otherHome = path.join(root, "other/runtime/versions/1.0.0/t3");
112 const otherLauncher = path.join(root, "other/bin/t3");
113 for (const file of [newExe, copy, elsewhere, otherHome]) {
114 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
115 yield* fs.writeFileString(file, "");
116 }
117 yield* fs.makeDirectory(path.dirname(foreign), { recursive: true });
118 yield* fs.symlink(elsewhere, foreign);
119 yield* fs.makeDirectory(path.dirname(otherLauncher), { recursive: true });
120 yield* fs.symlink(otherHome, otherLauncher);
121​
122 for (const launchedAs of [copy, foreign, otherLauncher, undefined]) {
123 const repointed = yield* repointLauncher({
124 launchedAs,
125 versionsDir: path.join(root, "runtime/versions"),
126 targetEntryPath: newExe,
127 });
128 assert.equal(repointed._tag, "None", launchedAs ?? "undefined");
129 }
130 assert.equal(yield* fs.readLink(foreign), elsewhere);
131 assert.equal(yield* fs.readLink(otherLauncher), otherHome);
132 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
133 );
134​
135 it.effect("finds the launcher a bare command name resolved to on PATH", () =>
136 Effect.gen(function* () {
137 const fs = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
140 const launcher = path.join(root, "bin/t3");
141 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
142 yield* fs.writeFileString(launcher, "");
143​
144 const bare = yield* resolveLauncherPath.pipe(
145 Effect.provideService(HostProcess.InvokedAs, "t3"),
146 Effect.provideService(HostProcess.Environment, {
147 PATH: `${path.join(root, "missing")}:${path.join(root, "bin")}`,
148 }),
149 Effect.provideService(HostProcess.WorkingDirectory, root),
150 );
151 const relative = yield* resolveLauncherPath.pipe(
152 Effect.provideService(HostProcess.InvokedAs, "./bin/t3"),
153 Effect.provideService(HostProcess.Environment, { PATH: "" }),
154 Effect.provideService(HostProcess.WorkingDirectory, root),
155 );
156 const absent = yield* resolveLauncherPath.pipe(
157 Effect.provideService(HostProcess.InvokedAs, "t3"),
158 Effect.provideService(HostProcess.Environment, { PATH: path.join(root, "missing") }),
159 Effect.provideService(HostProcess.WorkingDirectory, root),
160 );
161​
162 assert.equal(bare, launcher);
163 assert.equal(relative, launcher);
164 assert.equal(absent, undefined);
165 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
166 );
167});
168​
169it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 update service", (it) => {
170 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
171 "reports the service switch as pending after installing the target runtime",
172 () =>
173 Effect.gen(function* () {
174 const fs = yield* FileSystem.FileSystem;
175 const path = yield* Path.Path;
176 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-service-" });
177 const targetVersion = "999.0.0";
178 const runtime = pinnedRuntimePaths(path, baseDir, targetVersion, "linux");
179 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
180 yield* fs.writeFileString(
181 runtime.entryPath,
182 `#!/bin/sh\nprintf 't3 v${targetVersion}\\n'\n`,
183 );
184 yield* fs.chmod(runtime.entryPath, 0o755);
185 yield* fs.writeFileString(runtime.sentinelPath, `${targetVersion}\n`);
186 const logPath = path.join(baseDir, "userdata/logs/boot-service.log");
187 const unitPath = path.join(baseDir, "t3code.service");
188 const installs: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];
189 vi.spyOn(BootService, "layer").mockReturnValue(
190 Layer.succeed(BootService.BootService, {
191 status: Effect.succeed({
192 supported: true,
193 installed: true,
194 current: true,
195 installedVersion: packageJson.version,
196 installedBaseDir: baseDir,
197 logPath,
198 unitPath,
199 }),
200 install: (options) =>
201 Effect.sync(() => {
202 installs.push(options);
203 return {
204 program: [runtime.entryPath],
205 baseDir,
206 logPath,
207 unitPath,
208 handedOff: true,
209 };
210 }),
211 restart: Effect.die("unexpected restart"),
212 uninstall: Effect.die("unexpected uninstall"),
213 withStopped: () => Effect.die("unexpected maintenance"),
214 }),
215 );
216 const lines: string[] = [];
217 yield* Command.runWith(updateCommand, { version: packageJson.version })([
218 targetVersion,
219 "--yes",
220 "--base-dir",
221 baseDir,
222 ]).pipe(
223 Effect.provideService(HostProcess.Platform, "linux"),
224 Effect.provideService(HostProcess.IsExecutable, false),
225 Effect.provideService(HostProcess.Environment, {}),
226 Effect.provideService(Console.Console, {
227 ...globalThis.console,
228 log: (...args) => {
229 lines.push(args.map(String).join(" "));
230 },
231 }),
232 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
233 );
234​
235 expect(installs).toEqual([{ allowDowngrade: false, start: true }]);
236 const output = lines.join("\n");
237 expect(output).not.toContain("Background service restarted");
238 expect(output).toContain(`Background service switching to ${targetVersion}`);
239 expect(output).toContain(logPath);
240 }),
241 );
242});