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

SourceControlDiscovery.test.ts

354 lines13.0 KB

1import {
2 SourceControlProviderKind,
3 type VcsError,
4 VcsProcessExitError,
5 VcsProcessSpawnError,
6 VcsProcessTimeoutError,
7} from "@t3tools/contracts";
8import { assert, it } from "@effect/vitest";
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as PlatformError from "effect/PlatformError";
18import * as TestClock from "effect/testing/TestClock";
19import {
20 providerAuth,
21 type SourceControlProviderDiscoverySpec,
22} from "@t3tools/source-control-core/server/discovery";
23import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
24import {
25 fakeDiscovery,
26 fakeSourceControlProvider,
27} from "@t3tools/source-control-testing/fakeSourceControlDriver";
28import * as HostProcess from "@t3tools/shared/HostProcess";
29import { SpawnExecutableResolution } from "@t3tools/shared/shell";
30import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
31​
32import * as ServerConfig from "../config.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
35import * as VcsProcess from "../vcs/VcsProcess.ts";
36import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
37import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
38​
39const kind = SourceControlProviderKind.make;
40​
41// Serves both the host's runs and the server's own VCS probes, whose inputs share these fields.
42const run = (
43 input: Pick<
44 SourceControlHost.SourceControlProcessInput,
45 "operation" | "command" | "args" | "cwd"
46 >,
47): Effect.Effect<SourceControlHost.SourceControlProcessOutput, VcsError> => {
48 const context = { operation: input.operation, command: input.command, cwd: input.cwd };
49 if (input.command === "slow-cli") {
50 return Effect.fail(new VcsProcessTimeoutError({ ...context, timeoutMs: 5_000 }));
51 }
52 if (input.command === "broken-cli") {
53 return Effect.fail(
54 new VcsProcessExitError({ ...context, exitCode: 1, detail: "broken-cli: bad install" }),
55 );
56 }
57 if (input.command === "absent-cli") {
58 return Effect.fail(
59 new VcsProcessSpawnError({
60 ...context,
61 cause: PlatformError.systemError({
62 _tag: "NotFound",
63 module: "ChildProcess",
64 method: "spawn",
65 pathOrDescriptor: input.command,
66 }),
67 }),
68 );
69 }
70 if (input.args[0] === "--version") {
71 return input.command === "missing-cli"
72 ? Effect.fail(
73 new VcsProcessSpawnError({
74 operation: input.operation,
75 command: input.command,
76 cwd: input.cwd,
77 cause: new Error(`${input.command} not found`),
78 }),
79 )
80 : Effect.succeed(TestSourceControlHost.processOutput(`${input.command} version test\n`));
81 }
82 return Effect.succeed(
83 TestSourceControlHost.processOutput(`signed in as ${input.command}-user\n`),
84 );
85};
86​
87const cliDiscovery = (
88 name: string,
89 executable = name === "beta" ? "missing-cli" : `${name}-cli`,
90) => ({
91 type: "cli" as const,
92 kind: kind(name),
93 label: name,
94 installHint: `Install ${name}.`,
95 executable,
96 versionArgs: ["--version"],
97 authArgs: ["auth", "status"],
98 parseAuth: ({ stdout }: { readonly stdout: string }) =>
99 providerAuth({ status: "authenticated", account: /as (\S+)/.exec(stdout)?.[1] }),
100});
101​
102const defaultDiscoveries = [
103 cliDiscovery("alpha"),
104 cliDiscovery("beta"),
105 fakeDiscovery("gamma", {
106 probeAuth: Effect.succeed(providerAuth({ status: "authenticated", account: "api-user" })),
107 }),
108];
109​
110const onPath = (command: string) => `/usr/local/bin/${command}`;
111​
112const layerDiscovery = (
113 runProcess = run,
114 discoveries: ReadonlyArray<SourceControlProviderDiscoverySpec> = defaultDiscoveries,
115) =>
116 Layer.effect(
117 SourceControlProviderRegistry.SourceControlProviderRegistry,
118 SourceControlProviderRegistry.makeWithProviders(
119 discoveries.map((discovery) => ({
120 kind: discovery.kind,
121 provider: fakeSourceControlProvider(discovery.kind),
122 discovery,
123 })),
124 ),
125 ).pipe(
126 Layer.provideMerge(TestSourceControlHost.layer({ process: { run: runProcess } })),
127 Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
128 Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
129 Layer.provideMerge(Layer.mock(VcsProcess.VcsProcess)({ run: runProcess })),
130 Layer.provideMerge(
131 ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }),
132 ),
133 Layer.provideMerge(NodeServices.layer),
134 );
135​
136it.effect("reports every hosting integration in registry order with its sign-in", () =>
137 Effect.gen(function* () {
138 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
139 const result = yield* discovery.discover;
140​
141 assert.deepStrictEqual(
142 result.sourceControlProviders.map((item) => ({
143 kind: item.kind,
144 status: item.status,
145 version: item.version,
146 auth: item.auth.status,
147 account: item.auth.account,
148 })),
149 [
150 {
151 kind: kind("alpha"),
152 status: "available",
153 version: Option.some("alpha-cli version test"),
154 auth: "authenticated",
155 account: Option.some("alpha-cli-user"),
156 },
157 {
158 kind: kind("beta"),
159 status: "missing",
160 version: Option.none(),
161 auth: "unknown",
162 account: Option.none(),
163 },
164 {
165 kind: kind("gamma"),
166 status: "available",
167 version: Option.none(),
168 auth: "authenticated",
169 account: Option.some("api-user"),
170 },
171 ],
172 );
173 assert.deepStrictEqual(
174 result.versionControlSystems.map((item) => [item.kind, item.status]),
175 [
176 ["git", "available"],
177 ["jj", "available"],
178 ],
179 );
180 }).pipe(
181 Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery()))),
182 Effect.provideService(SpawnExecutableResolution, onPath),
183 ),
184);
185​
186it.effect("explains a CLI whose version probe failed instead of advising an install", () =>
187 Effect.gen(function* () {
188 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
189 const result = yield* discovery.discover;
190 const item = (name: string) => {
191 const found = result.sourceControlProviders.find((entry) => entry.kind === kind(name));
192 assert.isDefined(found);
193 return found;
194 };
195 const authDetail = (name: string) => Option.getOrElse(item(name).auth.detail, () => "");
196​
197 assert.notInclude(item("slow").installHint, "Install slow.");
198 assert.include(item("slow").installHint, "timed out after 5000ms");
199 assert.strictEqual(authDetail("slow"), item("slow").installHint);
200​
201 assert.notInclude(item("broken").installHint, "Install broken.");
202 assert.include(item("broken").installHint, "exited with status 1");
203 assert.strictEqual(authDetail("broken"), item("broken").installHint);
204​
205 assert.strictEqual(item("absent").installHint, "Install absent.");
206​
207 const git = result.versionControlSystems.find((entry) => entry.kind === "git");
208 assert.isDefined(git);
209 assert.notInclude(git.installHint, "Install Git from");
210 assert.include(git.installHint, "`git --version` exited with status 1");
211 }).pipe(
212 Effect.provideService(SpawnExecutableResolution, onPath),
213 Effect.provide(
214 SourceControlDiscovery.layer.pipe(
215 Layer.provide(
216 layerDiscovery(
217 (input) => run(input.command === "git" ? { ...input, command: "broken-cli" } : input),
218 [
219 cliDiscovery("slow", "slow-cli"),
220 cliDiscovery("broken", "broken-cli"),
221 cliDiscovery("absent", "absent-cli"),
222 ],
223 ),
224 ),
225 ),
226 ),
227 ),
228);
229​
230it.effect("answers once the slowest probe does instead of after every probe in turn", () => {
231 const delays: Record<string, Duration.Input> = {
232 "git --version": "1 second",
233 "slow-version-cli --version": "3 seconds",
234 "slow-version-cli auth": "1 second",
235 };
236 const timedRun: typeof run = (input) =>
237 run(input).pipe(Effect.delay(delays[`${input.command} ${input.args[0]}`] ?? Duration.zero));
238 return Effect.gen(function* () {
239 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
240 const fiber = yield* Effect.forkChild(discovery.discover);
241 yield* TestClock.adjust("3 seconds");
242 assert.isDefined(fiber.pollUnsafe(), "discovery waited on probes in series");
243 const item = (yield* Fiber.join(fiber)).sourceControlProviders[0];
244 assert.deepStrictEqual([item?.status, item?.auth.status], ["available", "authenticated"]);
245 }).pipe(
246 Effect.provide(
247 SourceControlDiscovery.layer.pipe(
248 Layer.provide(layerDiscovery(timedRun, [cliDiscovery("slow", "slow-version-cli")])),
249 ),
250 ),
251 Effect.provideService(SpawnExecutableResolution, onPath),
252 // Skips the login-shell PATH refresh, which spawns a real shell on wall-clock time.
253 Effect.provideService(HostProcess.Platform, "win32"),
254 );
255});
256​
257it.effect.each(["darwin", "linux"] as const)(
258 "names incompatible executables only on macOS (%s)",
259 (platform) => {
260 const runProcess: typeof run = (input) =>
261 Effect.fail(
262 new VcsProcessSpawnError({
263 operation: input.operation,
264 command: input.command,
265 cwd: input.cwd,
266 cause:
267 input.command === "missing-cli"
268 ? new Error("not found")
269 : Object.assign(new Error("spawn Unknown system error -86"), { errno: -86 }),
270 }),
271 );
272 return Effect.gen(function* () {
273 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
274 const result = yield* discovery.discover;
275 for (const item of [...result.versionControlSystems, ...result.sourceControlProviders]) {
276 if (item.kind === kind("gamma")) continue;
277 assert.strictEqual(item.status, "missing");
278 if (platform === "darwin" && item.executable !== "missing-cli") {
279 assert.include(
280 item.installHint,
281 `\`/usr/local/bin/${item.executable}\` is built for another CPU architecture, so this arm64 machine cannot run it. Remove or replace it.`,
282 );
283 } else {
284 assert.notInclude(item.installHint, "CPU architecture");
285 }
286 }
287 }).pipe(
288 Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery(runProcess)))),
289 Effect.provideService(SpawnExecutableResolution, onPath),
290 Effect.provideService(HostProcess.Platform, platform),
291 Effect.provideService(HostProcess.Architecture, "arm64"),
292 );
293 },
294);
295​
296// Spawns a real login shell and `jj`, so it runs on wall-clock time; the fixture shell is POSIX sh.
297it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
298 "rescans with tools the login shell gained after the server started",
299 () =>
300 Effect.gen(function* () {
301 const fs = yield* FileSystem.FileSystem;
302 const path = yield* Path.Path;
303 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-discovery-login-shell-" });
304 const home = path.join(root, "home");
305 const fakebin = path.join(home, "fakebin");
306 const loginShell = path.join(root, "loginsh");
307 yield* fs.makeDirectory(fakebin, { recursive: true });
308 // Stands in for `$SHELL -ilc <capture>` and sources only the fixture
309 // profile, so the host's own shell init cannot change the result.
310 yield* fs.writeFileString(
311 loginShell,
312 `#!/bin/sh\nexport HOME=${home}\n. "$HOME/.profile"\nshift\nexec /bin/sh -c "$1"\n`,
313 { mode: 0o755 },
314 );
315 const env = yield* HostProcess.Environment;
316 yield* Effect.acquireRelease(
317 Effect.sync(() => {
318 const saved = { PATH: env.PATH, SHELL: env.SHELL };
319 env.SHELL = loginShell;
320 return saved;
321 }),
322 (saved) =>
323 Effect.sync(() => {
324 env.PATH = saved.PATH;
325 if (saved.SHELL === undefined) delete env.SHELL;
326 else env.SHELL = saved.SHELL;
327 }),
328 );
329​
330 // The user installs a tool after launch; their login shell now finds it.
331 yield* fs.writeFileString(path.join(fakebin, "jj"), "#!/bin/sh\necho 'jj 0.99.0-test'\n", {
332 mode: 0o755,
333 });
334 yield* fs.writeFileString(path.join(home, ".profile"), 'export PATH="$HOME/fakebin:$PATH"\n');
335​
336 const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
337 const jj = (yield* discovery.discover).versionControlSystems.find(
338 (item) => item.kind === "jj",
339 );
340​
341 assert.deepStrictEqual(
342 { status: jj?.status, version: jj?.version },
343 { status: "available", version: Option.some("jj 0.99.0-test") },
344 );
345 }).pipe(
346 Effect.scoped,
347 Effect.provide(
348 SourceControlDiscovery.layer.pipe(
349 Layer.provide(VcsProcess.layer),
350 Layer.provideMerge(layerDiscovery()),
351 ),
352 ),
353 ),
354);