Repository navigation
Expand file tree
/
Copy pathupdate.test.ts
More file actions
532 lines (497 loc) · 21.5 KB
/
Copy pathupdate.test.ts
File metadata and controls
532 lines (497 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import type { ManagedUpdatesPolicy } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as TestClock from "effect/testing/TestClock";
import * as TestConsole from "effect/testing/TestConsole";
import { HttpClient, HttpClientResponse } from "effect/http";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { afterEach, vi } from "vite-plus/test";
import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
import { pinnedRuntimePaths, prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts";
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
repointLauncher,
resolveLauncherPath,
resolveMirrorVersion,
resolveNewestVersion,
runUpdate,
} from "./update.ts";
// lsof listing one process, so prune sees a process list in which no runtime is running.
const unrelatedLsof = ProcessRunner.ProcessRunner.of({
run: () =>
Effect.succeed({
stdout: "p1\nftxt\nn/usr/bin/true\n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
});
afterEach(() => vi.restoreAllMocks());
it.effect("authenticates each release page until the requested channel is found", () =>
Effect.gen(function* () {
const pages: string[] = [];
const httpClient = HttpClient.make((request) => {
const url = new URL(request.url);
assert.equal(url.origin, "https://api.github.com");
assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases");
assert.equal(request.headers.accept, "application/vnd.github+json");
assert.equal(request.headers.authorization, "Bearer gh-token");
const page = url.searchParams.get("page") ?? "";
pages.push(page);
const tag_name = page === "1" ? "v1.2.4-preview.20260101.1" : "v1.2.3";
return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([{ tag_name }])));
});
const version = yield* resolveNewestVersion("stable").pipe(
Effect.provideService(HostProcess.Environment, { GH_TOKEN: "gh-token" }),
Effect.provideService(HttpClient.HttpClient, httpClient),
);
assert.equal(version, "1.2.3");
assert.deepStrictEqual(pages, ["1", "2"]);
}),
);
it.effect("reads the newest version from the update feed file a mirror publishes", () =>
Effect.gen(function* () {
const requested: string[] = [];
const mirror = {
organization: "Example Corp",
feedUrl: "https://updates.example.com/t3code/?token=abc",
};
const resolve = (
channel: "stable" | "nightly" | "preview",
platform: NodeJS.Platform,
arch: string,
feed: string,
) =>
resolveMirrorVersion(mirror, channel).pipe(
Effect.map((version): string => version),
Effect.catchTags({ CliUpdateError: (error) => Effect.succeed(`error: ${error.reason}`) }),
Effect.provideService(HostProcess.Platform, platform),
Effect.provideService(HostProcess.Architecture, arch),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make((request) => {
requested.push(request.url);
return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(feed)));
}),
),
);
assert.equal(
yield* resolve("stable", "darwin", "arm64", "version: 1.4.0\nfiles: []\n"),
"1.4.0",
);
assert.equal(
yield* resolve("nightly", "linux", "arm64", "version: '1.5.0-nightly.20261101.2'\n"),
"1.5.0-nightly.20261101.2",
);
assert.deepStrictEqual(requested, [
"https://updates.example.com/t3code/latest-mac.yml?token=abc",
"https://updates.example.com/t3code/nightly-linux-arm64.yml?token=abc",
]);
// A feed for the wrong track is not trusted to mean the requested one.
assert.include(
yield* resolve("stable", "win32", "x64", "version: 1.5.0-nightly.20261101.2\n"),
"Could not read latest.yml from Example Corp's update mirror.",
);
assert.include(yield* resolve("preview", "win32", "x64", ""), "has no preview builds");
}),
);
it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
const runWithPolicy = (
updates: ManagedUpdatesPolicy,
input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
httpClient = HttpClient.make(() => Effect.die("unexpected release lookup")),
) =>
runUpdate({
baseDir: "/unused",
logsDir: "/unused",
serverRuntimeStatePath: "/unused",
channel: input.channel,
requestedVersion: input.requestedVersion,
allowDowngrade: false,
assumeYes: true,
}).pipe(
Effect.flip,
Effect.provide(
Layer.mergeAll(
ManagedPolicy.layerTest({
schemaVersion: 1,
organization: "Example Corp",
limits: { updates },
}),
// Refusals happen before the update touches the network, the service, or a process.
Layer.mock(BootService.BootService, {}),
Layer.mock(ProcessRunner.ProcessRunner, {}),
Layer.succeed(HttpClient.HttpClient, httpClient),
),
),
);
it.effect("refuses to update when updates are off", () =>
Effect.gen(function* () {
const error = yield* runWithPolicy({ mode: "off" });
assert.equal(error.message, "Example Corp manages T3 Code updates.");
}),
);
it.effect("refuses nightly releases when the policy disallows them", () =>
Effect.gen(function* () {
const byChannel = yield* runWithPolicy(
{ mode: "auto", allowNightly: false },
{ channel: "nightly" },
);
const byVersion = yield* runWithPolicy(
{ mode: "auto", allowNightly: false },
{ channel: "stable", requestedVersion: "1.2.0-nightly.20261028.1" },
);
for (const error of [byChannel, byVersion]) {
assert.equal(
error.message,
"Example Corp manages T3 Code updates. Only stable releases can be installed.",
);
}
}),
);
it.effect("looks for updates on the policy's mirror, never the public releases", () =>
Effect.gen(function* () {
const requested: string[] = [];
const error = yield* runWithPolicy(
{ mode: "auto", feedUrl: "https://updates.example.com/t3code" },
{ channel: "stable" },
HttpClient.make((request) => {
requested.push(new URL(request.url).origin);
return Effect.succeed(
HttpClientResponse.fromWeb(request, new Response("", { status: 404 })),
);
}),
);
assert.include(error.message, "from Example Corp's update mirror");
assert.deepStrictEqual(requested, ["https://updates.example.com"]);
}),
);
});
it.layer(NodeServices.layer)("t3 update launcher", (it) => {
it.effect("repoints a symlink that lives in a runtime versions tree", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
const newExe = path.join(root, "runtime/versions/2.0.0/t3");
const launcher = path.join(root, "bin/t3");
for (const file of [oldExe, newExe]) {
yield* fs.makeDirectory(path.dirname(file), { recursive: true });
yield* fs.writeFileString(file, "");
}
yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
yield* fs.symlink(oldExe, launcher);
const repointed = yield* repointLauncher({
launchedAs: launcher,
baseDir: root,
targetEntryPath: newExe,
});
assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
assert.equal(yield* fs.readLink(launcher), newExe);
}).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
);
it.effect.each([
{ name: "no launcher records", recorded: undefined },
{ name: "an empty launcher record", recorded: "" },
{ name: "whole launcher records", recorded: "/opt/t3\n" },
{ name: "Windows launcher records", recorded: "C:\\t3.cmd\r\n" },
// An interrupted append cut this record short.
{ name: "an unterminated launcher record", recorded: "/opt/t" },
// Another process's append is cut short after t3 update reads the records.
{ name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
])("keeps the runtime a repointed launcher off PATH points at with $name", ({ recorded, cut }) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
yield* TestClock.setTime(Duration.toMillis(Duration.days(1)));
for (const version of ["1.0.0", "2.0.0"]) {
const directory = path.join(root, "runtime/versions", version);
yield* fs.makeDirectory(directory, { recursive: true });
yield* fs.writeFileString(path.join(directory, "t3"), "");
yield* fs.writeFileString(path.join(directory, ".install-complete"), `${version}\n`);
yield* fs.utimes(path.join(directory, ".install-complete"), 0, 0);
}
if (recorded !== undefined) {
yield* fs.writeFileString(path.join(root, "runtime/launchers"), recorded);
}
// A launcher in the T3 home itself, which neither PATH nor the default bin dir reaches.
const launcher = path.join(root, "t3");
yield* fs.symlink(path.join(root, "runtime/versions/1.0.0/t3"), launcher);
const launchersFile = path.join(root, "runtime/launchers");
yield* repointLauncher({
launchedAs: launcher,
baseDir: root,
targetEntryPath: path.join(root, "runtime/versions/2.0.0/t3"),
}).pipe(
Effect.provideService(FileSystem.FileSystem, {
...fs,
readFileString: (file, encoding) =>
fs
.readFileString(file, encoding)
.pipe(
Effect.tap(() =>
cut === undefined || file !== launchersFile
? Effect.void
: fs.writeFileString(file, cut, { flag: "a" }),
),
),
}),
);
// A later server start prunes with no idea how this machine launches t3.
const removed = yield* prunePinnedRuntimes({ baseDir: root, keep: [] }).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, unrelatedLsof),
Effect.provideService(HostProcess.Platform, "darwin"),
Effect.provideService(HostProcess.Environment, { PATH: "" }),
Effect.provideService(HostProcess.HomeDirectory, root),
);
assert.deepStrictEqual(removed, ["1.0.0"]);
// macOS temp dirs sit behind the /var -> /private/var symlink, so compare canonical paths.
assert.equal(
yield* fs.realPath(launcher),
yield* fs.realPath(path.join(root, "runtime/versions/2.0.0/t3")),
);
}).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
);
const launcherFixture = Effect.fnUntraced(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
const newExe = path.join(root, "runtime/versions/2.0.0/t3");
const launcher = path.join(root, "t3");
for (const file of [oldExe, newExe]) {
yield* fs.makeDirectory(path.dirname(file), { recursive: true });
yield* fs.writeFileString(file, "");
}
yield* fs.symlink(oldExe, launcher);
return { root, oldExe, newExe, launcher, launchersFile: path.join(root, "runtime/launchers") };
});
it.effect("records a relative launcher path as absolute", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
yield* repointLauncher({
launchedAs: path.relative(path.resolve("."), launcher),
baseDir: root,
targetEntryPath: newExe,
});
assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`);
}).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
);
it.effect("fails instead of repointing a launcher it cannot record", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { root, oldExe, newExe, launcher, launchersFile } = yield* launcherFixture();
// Appending to a directory fails the way a read-only or full disk would.
yield* fs.makeDirectory(launchersFile);
const result = yield* repointLauncher({
launchedAs: launcher,
baseDir: root,
targetEntryPath: newExe,
}).pipe(Effect.exit);
assert.isTrue(Exit.isFailure(result));
assert.equal(yield* fs.readLink(launcher), oldExe);
}).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
);
it.effect.each(["recording", "repointing"] as const)(
"never leaves a repointed launcher unrecorded when t3 update dies while %s",
(step) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
yield* repointLauncher({
launchedAs: launcher,
baseDir: root,
targetEntryPath: newExe,
}).pipe(
Effect.provideService(FileSystem.FileSystem, {
...fs,
writeFileString: (path, data, options) =>
step === "recording" && path === launchersFile
? Effect.die("t3 update was killed")
: fs.writeFileString(path, data, options),
rename: (from, to) =>
step === "repointing" && to === launcher
? Effect.die("t3 update was killed")
: fs.rename(from, to),
}),
Effect.exit,
);
const repointed = (yield* fs.readLink(launcher)) === newExe;
const recorded = (yield* fs
.readFileString(launchersFile)
.pipe(Effect.orElseSucceed(() => "")))
.split("\n")
.includes(launcher);
assert.isFalse(repointed && !recorded);
}).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
);
it.effect("leaves a plain copy or a foreign symlink alone", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
const newExe = path.join(root, "runtime/versions/2.0.0/t3");
const copy = path.join(root, "copy/t3");
const foreign = path.join(root, "foreign/t3");
const elsewhere = path.join(root, "elsewhere/t3");
const otherHome = path.join(root, "other/runtime/versions/1.0.0/t3");
const otherLauncher = path.join(root, "other/bin/t3");
for (const file of [newExe, copy, elsewhere, otherHome]) {
yield* fs.makeDirectory(path.dirname(file), { recursive: true });
yield* fs.writeFileString(file, "");
}
yield* fs.makeDirectory(path.dirname(foreign), { recursive: true });
yield* fs.symlink(elsewhere, foreign);
yield* fs.makeDirectory(path.dirname(otherLauncher), { recursive: true });
yield* fs.symlink(otherHome, otherLauncher);
for (const launchedAs of [copy, foreign, otherLauncher, undefined]) {
const repointed = yield* repointLauncher({
launchedAs,
baseDir: root,
targetEntryPath: newExe,
});
assert.equal(repointed._tag, "None", launchedAs ?? "undefined");
}
assert.equal(yield* fs.readLink(foreign), elsewhere);
assert.equal(yield* fs.readLink(otherLauncher), otherHome);
}).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
);
it.effect("finds the launcher a bare command name resolved to on PATH", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const delimiter = (yield* HostProcess.Platform) === "win32" ? ";" : ":";
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
const launcher = path.join(root, "bin/t3");
yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
yield* fs.writeFileString(launcher, "");
const bare = yield* resolveLauncherPath.pipe(
Effect.provideService(HostProcess.InvokedAs, "t3"),
Effect.provideService(HostProcess.Environment, {
PATH: [path.join(root, "missing"), path.join(root, "bin")].join(delimiter),
}),
Effect.provideService(HostProcess.WorkingDirectory, root),
);
const relative = yield* resolveLauncherPath.pipe(
Effect.provideService(HostProcess.InvokedAs, "./bin/t3"),
Effect.provideService(HostProcess.Environment, { PATH: "" }),
Effect.provideService(HostProcess.WorkingDirectory, root),
);
const absent = yield* resolveLauncherPath.pipe(
Effect.provideService(HostProcess.InvokedAs, "t3"),
Effect.provideService(HostProcess.Environment, { PATH: path.join(root, "missing") }),
Effect.provideService(HostProcess.WorkingDirectory, root),
);
assert.equal(bare, launcher);
assert.equal(relative, launcher);
assert.equal(absent, undefined);
}).pipe(Effect.scoped),
);
});
// Without terminals, update skips its restart prompt whatever runs the test.
const withoutTerminals = Effect.acquireRelease(
Effect.sync(() =>
[process.stdin, process.stdout].map((stream) => {
const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
Object.defineProperty(stream, "isTTY", { configurable: true, value: false });
return { stream, descriptor };
}),
),
(saved) =>
Effect.sync(() => {
for (const { stream, descriptor } of saved) {
if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
else Object.defineProperty(stream, "isTTY", descriptor);
}
}),
);
it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
it.effect("names the version a service with a pending restart still runs", () =>
Effect.gen(function* () {
yield* withoutTerminals;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
const version = packageJson.version;
const runtime = pinnedRuntimePaths(path, baseDir, version, "linux");
yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
yield* fs.writeFileString(runtime.entryPath, "");
yield* fs.writeFileString(runtime.sentinelPath, `${version}\n`);
const unitPath = path.join(baseDir, "t3code.service");
const logPath = path.join(baseDir, "boot-service.log");
// An earlier `t3 update` pointed the service at this version without restarting it.
const service = Layer.mock(BootService.BootService, {
status: Effect.succeed<BootService.BootServiceStatus>({
supported: true,
installed: true,
current: false,
installedVersion: version,
installedBaseDir: baseDir,
problems: ["restart-pending"],
unitPath,
logPath,
}),
install: () => Effect.succeed({ program: [runtime.entryPath], baseDir, unitPath, logPath }),
});
vi.spyOn(BootService, "layer").mockReturnValue(service);
const runner = ProcessRunner.ProcessRunner.of({
run: (input) =>
input.args?.includes("--version") === true
? unrelatedLsof
.run(input)
.pipe(Effect.map((result) => ({ ...result, stdout: `t3 v${version}\n` })))
: unrelatedLsof.run(input),
});
const output = yield* runUpdate({
baseDir,
logsDir: baseDir,
serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
channel: undefined,
requestedVersion: version,
allowDowngrade: false,
assumeYes: false,
}).pipe(
Effect.andThen(TestConsole.logLines),
Effect.map((lines) => lines.join("\n")),
Effect.provide(
Layer.mergeAll(
service,
Layer.succeed(ProcessRunner.ProcessRunner, runner),
ManagedPolicy.layerTest(),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected release lookup")),
),
Layer.fresh(TestConsole.layer),
),
),
);
assert.include(
output,
`Background service still running the version before ${version}. Run \`t3 service restart\` when you are ready to switch it to ${version}.`,
);
}).pipe(
Effect.scoped,
Effect.provideService(HostProcess.Platform, "linux"),
Effect.provideService(HostProcess.Environment, { PATH: "" }),
),
);
});