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

environment.test.ts

143 lines6.5 KB

1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the filesystem boundary.
2import * as NodePath from "node:path";
3​
4import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5import { NodeHttpServer } from "@effect/platform-node";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import type { ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as NetService from "@t3tools/shared/Net";
10import { expect, it } from "@effect/vitest";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as TestConsole from "effect/testing/TestConsole";
15import { Command } from "effect/cli";
16​
17import { cli } from "../binCli.ts";
18import * as ServerConfig from "../config.ts";
19import { descriptorOf, servePeer } from "../peer/PeerLinks.testkit.ts";
20​
21const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer);
22​
23const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
24​
25/** The batch reports printed so far; the logger writes to the same console. */
26const reports = TestConsole.logLines.pipe(
27 Effect.map((lines) =>
28 lines.filter((line): line is string => typeof line === "string" && line.includes(" linked.")),
29 ),
30);
31​
32/** A machine of the fleet, on a socket of its own. */
33const serveMachine = (descriptor: ExecutionEnvironmentDescriptor) =>
34 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
35 Effect.flatMap((server) =>
36 servePeer(descriptor, Layer.empty).pipe(Effect.provideContext(server)),
37 ),
38 );
39​
40it.effect("links a file of environments, reports each line, and fails when one did not link", () =>
41 Effect.scoped(
42 Effect.gen(function* () {
43 const fs = yield* FileSystem.FileSystem;
44 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-environment-cli-" });
45 const { settingsPath } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
46 yield* fs.makeDirectory(NodePath.dirname(settingsPath), { recursive: true });
47 yield* fs.writeFileString(settingsPath, JSON.stringify({ linkedEnvironmentsEnabled: true }));
48​
49 const one = yield* serveMachine(descriptorOf("environment-vm-1", "VM 1"));
50 const two = yield* serveMachine(descriptorOf("environment-vm-2", "VM 2"));
51 const three = yield* serveMachine(descriptorOf("environment-vm-3", "VM 3"));
52 const codeFor = (machine: typeof one) =>
53 machine.auth
54 .issuePairingCredential({ access: "auto", purpose: "peer-link" })
55 .pipe(Effect.map((pairing) => pairing.credential));
56 const firstCode = yield* codeFor(one);
57 const thirdCode = yield* codeFor(three);
58​
59 const file = NodePath.join(baseDir, "fleet.txt");
60 yield* fs.writeFileString(
61 file,
62 `# fleet\n${one.url} ${firstCode}\n\n${two.url} not-a-code\n${three.url} ${thirdCode}\n`,
63 );
64 const link = (from: string) =>
65 runCli(["environment", "link", "--from", from, "--access", "auto", "--base-dir", baseDir]);
66​
67 const conflict = yield* runCli([
68 "environment",
69 "link",
70 "--from",
71 file,
72 "--url",
73 "http://ignored.invalid",
74 "--access",
75 "auto",
76 "--base-dir",
77 baseDir,
78 ]).pipe(Effect.flip);
79 expect(conflict).toMatchObject({
80 _tag: "EnvironmentLinkUsageError",
81 detail: "--from takes its addresses and pairing codes from the file.",
82 });
83​
84 const failed = yield* link(file).pipe(Effect.flip);
85 expect(failed).toMatchObject({ _tag: "EnvironmentLinkBatchError", failed: 1, total: 3 });
86 const report = (yield* reports).at(-1) ?? "";
87 expect(report).toContain(`${one.url}: linked VM 1 (environment-vm-1) with auto access`);
88 expect(report).toContain(`${two.url}: code refused: `);
89 expect(report).toContain(`${three.url}: linked VM 3 (environment-vm-3) with auto access`);
90 expect(report).toContain("2 of 3 linked.");
91 // A pairing code is never printed, whether it worked or not.
92 expect(report).not.toContain(firstCode);
93 expect(report).not.toContain("not-a-code");
94 expect((yield* one.linkedSessions).length).toBe(1);
95 expect(yield* two.linkedSessions).toEqual([]);
96 expect((yield* three.linkedSessions).length).toBe(1);
97​
98 // Retrying the whole file links the failure and leaves the linked ones alone,
99 // their codes unused: the first is spent and the third was never valid.
100 const retry = NodePath.join(baseDir, "retry.txt");
101 yield* fs.writeFileString(
102 retry,
103 `${one.url} ${firstCode}\n${two.url} ${yield* codeFor(two)}\n${three.url} never-valid\n`,
104 );
105 yield* link("~/retry.txt").pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir));
106 const retried = (yield* reports).at(-1) ?? "";
107 expect(retried).toContain(
108 `${one.url}: already linked as VM 1 (environment-vm-1), left as it is`,
109 );
110 expect(retried).toContain(`${two.url}: linked VM 2 (environment-vm-2) with auto access`);
111 expect(retried).toContain(
112 `${three.url}: already linked as VM 3 (environment-vm-3), left as it is`,
113 );
114 expect(retried).toContain("3 of 3 linked.");
115 expect((yield* one.linkedSessions).length).toBe(1);
116 expect((yield* two.linkedSessions).length).toBe(1);
117 expect((yield* three.linkedSessions).length).toBe(1);
118​
119 // An address may carry credentials; a result line names only its origin.
120 const withSecrets = (url: string) =>
121 Object.assign(new URL(url), {
122 username: "alice",
123 password: "hunter2",
124 search: "?token=s3cret",
125 }).href;
126 const secrets = NodePath.join(baseDir, "secrets.txt");
127 yield* fs.writeFileString(
128 secrets,
129 [
130 `${withSecrets(one.url)} ${firstCode}`,
131 `${withSecrets("http://192.168.1.20:3773")} some-code`,
132 `ftp://alice:hunter2@files.example/?token=s3cret some-code`,
133 ].join("\n"),
134 );
135 yield* link(secrets).pipe(Effect.flip);
136 const redacted = (yield* reports).at(-1) ?? "";
137 expect(redacted).toContain(`${new URL(one.url).origin}: already linked as VM 1`);
138 expect(redacted).toContain("http://192.168.1.20:3773: unreachable: ");
139 expect(redacted).toContain("line 3: unreachable: ");
140 expect(redacted).not.toMatch(/alice|hunter2|s3cret/);
141 }),
142 ).pipe(Effect.provide(Layer.mergeAll(layerCliRuntime, TestConsole.layer))),
143);