Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as DateTime from "effect/DateTime";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as PlatformError from "effect/PlatformError";
11import * as PubSub from "effect/PubSub";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15import {
16 DEFAULT_SERVER_SETTINGS,
17 VcsProcessSpawnError,
18 VcsProcessTimeoutError,
19} from "@t3tools/contracts";
20import type {
21 SourceControlCliDiscoverySpec,
22 SourceControlManagedCliDiscoverySpec,
23 SourceControlProviderDiscoverySpec,
24} from "@t3tools/source-control-core/server/discovery";
25import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
26import { fakeSourceControlProvider } from "@t3tools/source-control-testing/fakeSourceControlDriver";
27import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
28import { SpawnExecutableResolution } from "@t3tools/shared/shell";
29
30import * as ServerSettings from "../serverSettings.ts";
31import * as ServerConfig from "../config.ts";
32import type * as VcsDriver from "../vcs/VcsDriver.ts";
33import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
34import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
35
36const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
37const kind = SourceControlProviderKind.make;
38
39class NotAnswered extends Schema.TaggedError<NotAnswered>()("NotAnswered", {}) {}
40
41const linkSubject = (host: string) => () =>
42 Effect.succeed({ title: `${host} subject`, body: null });
43
44/** Only GitHub and GitLab read linked subjects, as in production. */
45const PROVIDERS = [
46 fakeSourceControlProvider("github", { resolveLink: linkSubject("github") }),
47 fakeSourceControlProvider("gitlab", { resolveLink: linkSubject("gitlab") }),
48 fakeSourceControlProvider("forgejo"),
49 fakeSourceControlProvider("bitbucket"),
50 fakeSourceControlProvider("azure-devops"),
51];
52
53/** A host CLI that claims every server it is signed in to, as `glab` does. */
54const claimingCli = (claims: string): SourceControlCliDiscoverySpec => ({
55 type: "cli",
56 kind: kind(claims),
57 label: claims,
58 installHint: `Install ${claims}.`,
59 executable: `${claims}-cli`,
60 versionArgs: ["--version"],
61 authArgs: ["auth", "status"],
62 remoteRefinementArgs: ({ provider }) => ["auth", "status", "--hostname", provider.name],
63 parseAuth: () => ({
64 status: "unknown",
65 account: Option.none(),
66 host: Option.none(),
67 detail: Option.none(),
68 }),
69 refineUnknownRemote: ({ context, auth }) =>
70 auth.stdout.includes(`Logged in to ${context.provider.name}`)
71 ? { kind: kind(claims), name: `${claims} Self-Hosted`, baseUrl: context.provider.baseUrl }
72 : null,
73});
74
75const managedCli = (
76 claims: string,
77 refine: SourceControlManagedCliDiscoverySpec["refineUnknownRemote"],
78): SourceControlManagedCliDiscoverySpec => ({
79 type: "managed-cli",
80 kind: kind(claims),
81 label: claims,
82 installHint: `Install ${claims}.`,
83 probe: () => Effect.die("unused"),
84 refineUnknownRemote: refine,
85});
86
87const onPath = (command: string) => `/usr/bin/${command}`;
88
89function makeRegistry(input: {
90 readonly remotes: ReadonlyArray<{
91 readonly name: string;
92 readonly url: string;
93 }>;
94 readonly discovery?: ReadonlyArray<SourceControlProviderDiscoverySpec>;
95 readonly run?: SourceControlHost.SourceControlHost["Service"]["process"]["run"];
96 readonly settings?: Partial<ServerSettings.ServerSettingsService["Service"]>;
97}) {
98 const driver = {
99 listRemotes: () =>
100 Effect.succeed({
101 remotes: input.remotes.map((remote) => ({
102 ...remote,
103 pushUrl: Option.none(),
104 isPrimary: remote.name === "origin",
105 })),
106 freshness: {
107 source: "live-local" as const,
108 observedAt: TEST_EPOCH,
109 expiresAt: Option.none(),
110 },
111 }),
112 } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
113
114 const discovery = input.discovery ?? [claimingCli("gitlab")];
115 return SourceControlProviderRegistry.makeWithProviders(
116 PROVIDERS.map((provider) => ({
117 kind: provider.kind,
118 provider,
119 discovery: discovery.find((spec) => spec.kind === provider.kind) ?? {
120 type: "api",
121 kind: provider.kind,
122 label: provider.kind,
123 installHint: "unused",
124 probeAuth: Effect.succeed({
125 status: "unknown",
126 account: Option.none(),
127 host: Option.none(),
128 detail: Option.none(),
129 }),
130 },
131 })),
132 ).pipe(
133 Effect.provide(
134 Layer.mergeAll(
135 Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
136 resolve: () =>
137 Effect.succeed({
138 kind: "git",
139 repository: {
140 kind: "git",
141 rootPath: "/repo",
142 metadataPath: null,
143 freshness: {
144 source: "live-local" as const,
145 observedAt: TEST_EPOCH,
146 expiresAt: Option.none(),
147 },
148 },
149 driver: driver as unknown as VcsDriver.VcsDriver["Service"],
150 }),
151 }),
152 TestSourceControlHost.layer({
153 process: {
154 run: input.run ?? (() => Effect.succeed(TestSourceControlHost.processOutput(""))),
155 },
156 }),
157 input.settings
158 ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings)
159 : ServerSettings.ServerSettingsService.layerTest(),
160 ServerConfig.layerTest(process.cwd(), {
161 prefix: "t3-source-control-registry-test-",
162 }).pipe(Layer.provide(NodeServices.layer)),
163 ),
164 ),
165 );
166}
167
168const signedIn = (host: string) => () =>
169 Effect.succeed(TestSourceControlHost.processOutput(` ✓ Logged in to ${host} as user\n`));
170
171it.effect("routes an unknown remote to the integration that claims its server", () =>
172 Effect.gen(function* () {
173 const asked: Array<string> = [];
174 const registry = yield* makeRegistry({
175 remotes: [{ name: "origin", url: "git@self-hosted.example.test:group/project.git" }],
176 run: (input) => {
177 asked.push([input.command, ...input.args].join(" "));
178 return signedIn("self-hosted.example.test")();
179 },
180 });
181
182 const handle = yield* registry.resolveHandle({ cwd: "/repo" });
183
184 assert.strictEqual(handle.provider.kind, "gitlab");
185 assert.deepStrictEqual(handle.context?.provider, {
186 kind: kind("gitlab"),
187 name: "gitlab Self-Hosted",
188 baseUrl: "https://self-hosted.example.test",
189 });
190 assert.deepStrictEqual(asked, ["gitlab-cli auth status --hostname self-hosted.example.test"]);
191 }),
192);
193
194it.effect("leaves a remote no integration claims unknown, with its server's address", () =>
195 Effect.gen(function* () {
196 const registry = yield* makeRegistry({
197 remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }],
198 });
199 const handle = yield* registry.resolveHandle({ cwd: "/repo" });
200 assert.strictEqual(handle.provider.kind, kind("unknown"));
201 assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test");
202 }),
203);
204
205it.effect.each([
206 ["github.com:team/project.git", "github"],
207 ["gitlab.com:team/project.git", "gitlab"],
208 ["bitbucket.org:team/project.git", "bitbucket"],
209 ["code.example.test:team/project.git", "unknown"],
210] as const)(
211 "reads the host of an SSH remote that leaves its user to ssh config: %s",
212 ([url, expected]) =>
213 Effect.gen(function* () {
214 const registry = yield* makeRegistry({ remotes: [{ name: "origin", url }] });
215
216 const handle = yield* registry.resolveHandle({ cwd: "/repo" });
217
218 assert.strictEqual(handle.provider.kind, kind(expected));
219 assert.strictEqual(handle.context?.remoteUrl, url);
220 }),
221);
222
223it.effect("refines the caller-selected remote instead of choosing another configured remote", () =>
224 Effect.gen(function* () {
225 const registry = yield* makeRegistry({
226 remotes: [{ name: "origin", url: "git@github.com:fork/project.git" }],
227 run: signedIn("self-hosted.example.test"),
228 });
229
230 const handle = yield* registry.resolveHandle({
231 cwd: "/repo",
232 context: {
233 provider: {
234 kind: kind("unknown"),
235 name: "self-hosted.example.test",
236 baseUrl: "https://self-hosted.example.test",
237 },
238 remoteName: "upstream",
239 remoteUrl: "https://self-hosted.example.test/group/project.git",
240 },
241 });
242
243 assert.strictEqual(handle.context?.provider.kind, "gitlab");
244 assert.strictEqual(handle.context?.remoteName, "upstream");
245 }),
246);
247
248it.effect("falls back to a non-origin remote when origin is not configured", () =>
249 Effect.gen(function* () {
250 const registry = yield* makeRegistry({
251 remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
252 });
253
254 const provider = yield* registry.resolve({ cwd: "/repo" });
255
256 assert.strictEqual(provider.kind, "azure-devops");
257 }),
258);
259
260it.effect(
261 "routes linked subjects to the host that serves them, independently of the checkout",
262 () =>
263 Effect.gen(function* () {
264 const registry = yield* makeRegistry({
265 remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
266 });
267 for (const [url, host] of [
268 ["https://github.com/team/project/issues/1", "github"],
269 ["https://gitlab.com/team/sub/project/-/merge_requests/2", "gitlab"],
270 ] as const) {
271 const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
272 assert.ok(lookup);
273 assert.deepStrictEqual(yield* lookup, { title: `${host} subject`, body: null });
274 }
275 for (const url of [
276 "https://example.test/team/project/issues/1",
277 "https://codeberg.org/team/project/issues/1",
278 "https://bitbucket.org/team/project/pull-requests/1",
279 "https://dev.azure.com/org/project/_git/repo/pullrequest/1",
280 "http://github.com/team/project/issues/1",
281 "https://user:secret@github.com/team/project/issues/1",
282 ]) {
283 assert.strictEqual(
284 registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
285 undefined,
286 url,
287 );
288 }
289 }),
290);
291
292it.effect("does not refine a context whose server address is empty", () =>
293 Effect.gen(function* () {
294 let asked = 0;
295 const remoteUrl = "git@githubenterprise.dev.example.com:team/workspace.git";
296 const registry = yield* makeRegistry({
297 remotes: [{ name: "origin", url: remoteUrl }],
298 discovery: [
299 managedCli("github", ({ context }) => {
300 asked += 1;
301 return Effect.succeed(
302 context.provider.baseUrl === ""
303 ? null
304 : { kind: kind("github"), name: "GitHub", baseUrl: context.provider.baseUrl },
305 );
306 }),
307 ],
308 });
309 const context = {
310 provider: { kind: kind("unknown"), name: "Unknown", baseUrl: "" },
311 remoteName: "origin",
312 remoteUrl,
313 };
314 assert.deepStrictEqual(
315 (yield* registry.resolveHandle({ cwd: "/repo", context })).context,
316 context,
317 );
318
319 const resolved = yield* registry.resolveHandle({ cwd: "/repo" });
320 assert.strictEqual(resolved.provider.kind, "github");
321 assert.strictEqual(
322 resolved.context?.provider.baseUrl,
323 "https://githubenterprise.dev.example.com",
324 );
325 assert.strictEqual(asked, 2);
326 }),
327);
328
329const notFound = (command: string, cwd: string) =>
330 new VcsProcessSpawnError({
331 operation: "test",
332 command,
333 cwd,
334 cause: PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }),
335 });
336
337const resolveUnknown = (
338 registry: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"],
339 repository: string,
340) =>
341 registry.resolveHandle({
342 cwd: `/${repository}`,
343 context: {
344 provider: {
345 kind: kind("unknown"),
346 name: "git.example.internal",
347 baseUrl: "https://git.example.internal",
348 },
349 remoteName: "origin",
350 remoteUrl: `git@Git.Example.Internal:team/${repository}.git`,
351 },
352 });
353
354it.effect("asks once for every checkout of a server no integration claims", () =>
355 Effect.gen(function* () {
356 const asked: Array<string> = [];
357 const release = yield* Deferred.make<void>();
358 const registry = yield* makeRegistry({
359 remotes: [],
360 discovery: [
361 claimingCli("gitlab"),
362 managedCli("github", ({ context }) => {
363 asked.push(`managed ${context.provider.name}`);
364 return Effect.succeed(null);
365 }),
366 ],
367 run: ({ command, args, cwd }) => {
368 asked.push([command, ...args].join(" "));
369 return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd))));
370 },
371 });
372
373 const started = yield* Effect.forEach(["a", "b", "c"], () => Deferred.make<void>());
374 const callers = yield* Effect.forEach(
375 ["a", "b", "c"],
376 (repository, index) =>
377 Deferred.succeed(started[index]!, undefined).pipe(
378 Effect.andThen(resolveUnknown(registry, repository)),
379 ),
380 { concurrency: "unbounded" },
381 ).pipe(Effect.forkChild);
382 yield* Effect.forEach(started, Deferred.await);
383 yield* Deferred.succeed(release, undefined);
384 const handles = yield* Fiber.join(callers);
385 yield* resolveUnknown(registry, "d");
386 assert.deepStrictEqual(
387 handles.map((handle) => handle.provider.kind),
388 ["unknown", "unknown", "unknown"],
389 );
390 const once = asked.slice();
391 assert.sameMembers(once, [
392 "managed git.example.internal",
393 "gitlab-cli auth status --hostname git.example.internal",
394 ]);
395
396 yield* TestClock.adjust("59 minutes");
397 yield* resolveUnknown(registry, "a");
398 assert.deepStrictEqual(asked, once);
399
400 yield* TestClock.adjust("1 minute");
401 yield* resolveUnknown(registry, "a");
402 assert.deepStrictEqual(asked, [...once, ...once]);
403 }),
404);
405
406it.effect("asks again after a check that could not answer", () =>
407 Effect.gen(function* () {
408 let asks = 0;
409 let managedAsks = 0;
410 const registry = yield* makeRegistry({
411 remotes: [],
412 discovery: [
413 claimingCli("gitlab"),
414 managedCli("github", () => {
415 managedAsks += 1;
416 return Effect.fail(new NotAnswered());
417 }),
418 ],
419 run: ({ command, cwd }) => {
420 asks += 1;
421 return Effect.fail(
422 new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }),
423 );
424 },
425 });
426 yield* resolveUnknown(registry, "a");
427 yield* resolveUnknown(registry, "b");
428 assert.strictEqual(asks, 2);
429 assert.strictEqual(managedAsks, 2);
430 }),
431);
432
433it.effect("asks again once Settings change", () =>
434 Effect.gen(function* () {
435 const changes = yield* PubSub.unbounded<typeof DEFAULT_SERVER_SETTINGS>();
436 const handled = yield* Deferred.make<void>();
437 let claims = false;
438 const registry = yield* makeRegistry({
439 remotes: [],
440 settings: {
441 subscribeChanges: PubSub.subscribe(changes).pipe(
442 Effect.map((subscription) =>
443 Stream.fromSubscription(subscription).pipe(
444 Stream.flatMap((settings) =>
445 Stream.concat(
446 Stream.make(settings),
447 Stream.fromEffectDrain(Deferred.succeed(handled, undefined)),
448 ),
449 ),
450 ),
451 ),
452 ),
453 },
454 discovery: [
455 managedCli("github", ({ context }) =>
456 Effect.succeed(
457 claims
458 ? { kind: kind("github"), name: "GitHub", baseUrl: context.provider.baseUrl }
459 : null,
460 ),
461 ),
462 ],
463 });
464 assert.strictEqual((yield* resolveUnknown(registry, "a")).provider.kind, "unknown");
465 claims = true;
466 assert.strictEqual((yield* resolveUnknown(registry, "b")).provider.kind, "unknown");
467
468 yield* PubSub.publish(changes, DEFAULT_SERVER_SETTINGS);
469 yield* Deferred.await(handled);
470 assert.strictEqual((yield* resolveUnknown(registry, "c")).provider.kind, "github");
471 }),
472);
473
474it.effect("asks again once discovery finds a new sign-in, not on every discovery", () =>
475 Effect.gen(function* () {
476 let signedIn = false;
477 let refinements = 0;
478 const registry = yield* makeRegistry({
479 remotes: [],
480 discovery: [
481 {
482 ...claimingCli("gitlab"),
483 parseAuth: () => ({
484 status: signedIn ? "authenticated" : "unauthenticated",
485 account: Option.none(),
486 host: Option.none(),
487 detail: Option.none(),
488 }),
489 },
490 ],
491 run: ({ args }) => {
492 if (args.includes("--hostname")) refinements += 1;
493 return Effect.succeed(
494 TestSourceControlHost.processOutput(
495 signedIn ? " ✓ Logged in to git.example.internal as user\n" : "",
496 ),
497 );
498 },
499 });
500 yield* registry.discover;
501 assert.strictEqual((yield* resolveUnknown(registry, "a")).provider.kind, "unknown");
502 yield* registry.discover;
503 assert.strictEqual((yield* resolveUnknown(registry, "b")).provider.kind, "unknown");
504 assert.strictEqual(refinements, 1);
505
506 signedIn = true;
507 yield* registry.discover;
508 assert.strictEqual((yield* resolveUnknown(registry, "c")).provider.kind, "gitlab");
509 assert.strictEqual(refinements, 2);
510 }).pipe(Effect.provideService(SpawnExecutableResolution, onPath)),
511);
512
513it.effect("answers discovery without waiting on a hosting API that stalls", () =>
514 Effect.gen(function* () {
515 const registry = yield* makeRegistry({
516 remotes: [],
517 discovery: [
518 claimingCli("gitlab"),
519 {
520 type: "api",
521 kind: kind("bitbucket"),
522 label: "Bitbucket",
523 installHint: "unused",
524 probeAuth: Effect.never,
525 },
526 ],
527 });
528 const discovering = yield* registry.discover.pipe(Effect.forkChild);
529 yield* TestClock.adjust("3 seconds");
530 const items = yield* Fiber.join(discovering);
531 const bitbucket = items.find((item) => item.kind === "bitbucket");
532 assert.strictEqual(bitbucket?.status, "available");
533 assert.strictEqual(bitbucket?.auth.status, "unknown");
534 assert.strictEqual(items.find((item) => item.kind === "gitlab")?.status, "available");
535 }).pipe(Effect.provideService(SpawnExecutableResolution, onPath)),
536);