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 Redacted from "effect/Redacted";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15import { HttpClient } from "effect/http";
16import { ChildProcessSpawner } from "effect/process";
17import {
18 DEFAULT_SERVER_SETTINGS,
19 VcsProcessSpawnError,
20 VcsProcessTimeoutError,
21 VcsRepositoryDetectionError,
22} from "@t3tools/contracts";
23
24import { withHostOverrideSettingsFailure } from "../testUtils/hostOverrideSettingsFailure.ts";
25import * as ServerSettings from "../serverSettings.ts";
26import * as ServerConfig from "../config.ts";
27import type * as VcsDriver from "../vcs/VcsDriver.ts";
28import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
29import * as VcsProcess from "../vcs/VcsProcess.ts";
30import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
31import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
32import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
33import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
34import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
35import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
36import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy";
37import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
38import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
39import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
40import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
41import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
42import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
43import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
44import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
45import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
46
47const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
48
49const processOutput = (
50 stdout: string,
51 options?: {
52 readonly stderr?: string;
53 readonly exitCode?: ChildProcessSpawner.ExitCode;
54 },
55): VcsProcess.VcsProcessOutput => ({
56 exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0),
57 stdout,
58 stderr: options?.stderr ?? "",
59 stdoutTruncated: false,
60 stderrTruncated: false,
61});
62
63function makeRegistry(input: {
64 readonly remotes: ReadonlyArray<{
65 readonly name: string;
66 readonly url: string;
67 }>;
68 readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
69 readonly githubApi?: Partial<GitHubRest.GitHubRest["Service"]>;
70 readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
71 readonly forgejo?: Partial<ForgejoCli.ForgejoCli["Service"]>;
72 readonly settings?: Partial<ServerSettings.ServerSettingsService["Service"]>;
73 readonly listRemotes?: VcsDriver.VcsDriver["Service"]["listRemotes"];
74 readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
75}) {
76 const driver = {
77 listRemotes:
78 input.listRemotes ??
79 (() =>
80 Effect.succeed({
81 remotes: input.remotes.map((remote) => ({
82 ...remote,
83 pushUrl: Option.none(),
84 isPrimary: remote.name === "origin",
85 })),
86 freshness: {
87 source: "live-local" as const,
88 observedAt: TEST_EPOCH,
89 expiresAt: Option.none(),
90 },
91 })),
92 } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
93
94 const layerRegistry = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
95 get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriver["Service"]),
96 resolve:
97 input.resolve ??
98 (() =>
99 Effect.succeed({
100 kind: "git",
101 repository: {
102 kind: "git",
103 rootPath: "/repo",
104 metadataPath: null,
105 freshness: {
106 source: "live-local" as const,
107 observedAt: TEST_EPOCH,
108 expiresAt: Option.none(),
109 },
110 },
111 driver: driver as unknown as VcsDriver.VcsDriver["Service"],
112 })),
113 });
114
115 const layerProcess = Layer.mock(VcsProcess.VcsProcess)({
116 run: () => Effect.succeed(processOutput("")),
117 ...input.process,
118 });
119
120 return SourceControlProviderRegistry.make.pipe(
121 Effect.provide(
122 Layer.mergeAll(
123 NodeServices.layer,
124 layerRegistry,
125 layerProcess,
126 ServerSourceControlHost.layer.pipe(
127 Layer.provide(
128 Layer.mergeAll(
129 layerProcess,
130 layerRegistry,
131 ServerSettings.ServerSettingsService.layerTest(),
132 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
133 ),
134 ),
135 ),
136 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
137 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
138 Layer.mock(BitbucketApi.BitbucketApi)({}),
139 Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
140 input.settings
141 ? Layer.mock(ServerSettings.ServerSettingsService)({
142 getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
143 subscribeChanges: Effect.succeed(Stream.empty),
144 ...input.settings,
145 })
146 : ServerSettings.ServerSettingsService.layerTest(),
147 Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
148 // The GitHub provider's GraphQL reads go through these; no test here makes one.
149 Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}),
150 Layer.succeed(
151 HttpClient.HttpClient,
152 HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))),
153 ),
154 Layer.mock(GitHubRest.GitHubRest)({
155 // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
156 credential: (host) => Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
157 ...input.githubApi,
158 }),
159 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
160 Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
161 Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
162 Layer.mock(ForgejoCli.ForgejoCli)({
163 listLogins: () => Effect.succeed([]),
164 ...input.forgejo,
165 }),
166 Layer.mock(GitCafeApi.GitCafeApi)({}),
167 Layer.mock(GitCafeCredentials.GitCafeCredentials)({
168 cliEnv: () => Effect.succeed({}),
169 }),
170 ServerConfig.layerTest(process.cwd(), {
171 prefix: "t3-source-control-registry-test-",
172 }).pipe(Layer.provide(NodeServices.layer)),
173 ),
174 ),
175 );
176}
177
178it.effect("uses hostname heuristics and warns when settings fail", () =>
179 withHostOverrideSettingsFailure((settings) =>
180 Effect.gen(function* () {
181 const registry = yield* makeRegistry({
182 remotes: [{ name: "origin", url: "git@github.com:team/repo.git" }],
183 settings,
184 });
185 const provider = yield* registry.resolve({ cwd: "/repo" });
186 assert.strictEqual(provider.kind, "github");
187 }),
188 ),
189);
190
191it.effect("routes GitHub remotes to the GitHub provider", () =>
192 Effect.gen(function* () {
193 const registry = yield* makeRegistry({
194 remotes: [{ name: "origin", url: "git@github.com:pingdotgg/t3code.git" }],
195 });
196
197 const provider = yield* registry.resolve({ cwd: "/repo" });
198
199 assert.strictEqual(provider.kind, "github");
200 }),
201);
202
203it.effect(
204 "uses configured hosts before heuristics and account probes, including supplied contexts",
205 () =>
206 Effect.gen(function* () {
207 const registry = yield* makeRegistry({
208 remotes: [{ name: "origin", url: "ssh://git@gitlab.example.test:2222/team/repo.git" }],
209 settings: {
210 getSettings: Effect.succeed({
211 ...DEFAULT_SERVER_SETTINGS,
212 sourceControlHostOverrides: {
213 "GITLAB.example.test:2222": {
214 kind: "forgejo",
215 baseUrl: "http://web.example.test:3000/forgejo",
216 },
217 },
218 }),
219 },
220 process: { run: () => Effect.die("explicit mapping must not probe other providers") },
221 });
222 for (const input of [
223 { cwd: "/repo" },
224 {
225 cwd: "/repo",
226 context: {
227 provider: {
228 kind: SourceControlProviderKind.make("gitlab"),
229 name: "GitLab",
230 baseUrl: "https://gitlab.example.test",
231 },
232 remoteName: "origin",
233 remoteUrl: "ssh://git@gitlab.example.test:2222/team/repo.git",
234 },
235 },
236 ]) {
237 const handle = yield* registry.resolveHandle(input);
238 assert.strictEqual(handle.provider.kind, "forgejo");
239 assert.strictEqual(
240 handle.context?.provider.baseUrl,
241 "http://web.example.test:3000/forgejo",
242 );
243 }
244 }),
245);
246
247it.effect("invalidates detected contexts when a host mapping is added, changed, or removed", () =>
248 Effect.gen(function* () {
249 const changes = yield* PubSub.unbounded<{
250 settings: typeof DEFAULT_SERVER_SETTINGS;
251 handled: Deferred.Deferred<void>;
252 }>();
253 const registry = yield* makeRegistry({
254 remotes: [{ name: "origin", url: "https://gitlab.example.test/team/repo.git" }],
255 settings: {
256 subscribeChanges: PubSub.subscribe(changes).pipe(
257 Effect.map((subscription) =>
258 Stream.fromSubscription(subscription).pipe(
259 Stream.flatMap(({ settings, handled }) =>
260 Stream.concat(
261 Stream.make(settings),
262 Stream.fromEffectDrain(Deferred.succeed(handled, undefined)),
263 ),
264 ),
265 ),
266 ),
267 ),
268 },
269 });
270 assert.strictEqual((yield* registry.resolveHandle({ cwd: "/repo" })).provider.kind, "gitlab");
271 for (const kind of ["forgejo", "github", null] as const) {
272 const handled = yield* Deferred.make<void>();
273 yield* PubSub.publish(changes, {
274 handled,
275 settings: {
276 ...DEFAULT_SERVER_SETTINGS,
277 sourceControlHostOverrides: kind === null ? {} : { "gitlab.example.test": { kind } },
278 },
279 });
280 yield* Deferred.await(handled);
281 assert.strictEqual(
282 (yield* registry.resolveHandle({ cwd: "/repo" })).provider.kind,
283 kind ?? "gitlab",
284 );
285 }
286 }),
287);
288
289it.effect("routes directly by provider kind for remote-first workflows", () =>
290 Effect.gen(function* () {
291 const registry = yield* makeRegistry({
292 remotes: [],
293 });
294
295 const provider = yield* registry.get(SourceControlProviderKind.make("github"));
296
297 assert.strictEqual(provider.kind, "github");
298 }),
299);
300
301it.effect("includes the request cwd when an unregistered provider is used", () =>
302 Effect.gen(function* () {
303 const registry = yield* makeRegistry({ remotes: [] });
304 const provider = yield* registry.get(SourceControlProviderKind.make("unknown"));
305
306 const error = yield* provider
307 .getChangeRequest({ cwd: "/repo", reference: "#42" })
308 .pipe(Effect.flip);
309
310 assert.strictEqual(error.provider, "unknown");
311 assert.strictEqual(error.operation, "getChangeRequest");
312 assert.strictEqual(error.cwd, "/repo");
313 assert.strictEqual(error.reference, "#42");
314 }),
315);
316
317it.effect("lists no change requests for a repository on an unrecognized host", () =>
318 Effect.gen(function* () {
319 const registry = yield* makeRegistry({
320 remotes: [{ name: "origin", url: "https://git.example.internal/team/repo.git" }],
321 });
322 const provider = yield* registry.resolve({ cwd: "/repo" });
323
324 assert.strictEqual(provider.kind, "unknown");
325 assert.deepStrictEqual(
326 yield* provider.listChangeRequests({ cwd: "/repo", headSelector: "master", state: "all" }),
327 [],
328 );
329 }),
330);
331
332it.effect("retains VCS detection failures with structured cwd context", () =>
333 Effect.gen(function* () {
334 const cause = new VcsRepositoryDetectionError({
335 operation: "resolve",
336 cwd: "/repo",
337 detail: "raw VCS detection failure",
338 cause: new Error("raw nested failure"),
339 });
340 const registry = yield* makeRegistry({
341 remotes: [],
342 resolve: () => Effect.fail(cause),
343 });
344
345 const error = yield* registry.resolve({ cwd: "/repo" }).pipe(Effect.flip);
346
347 assert.strictEqual(error.provider, "unknown");
348 assert.strictEqual(error.operation, "detectProvider");
349 assert.strictEqual(error.cwd, "/repo");
350 assert.strictEqual(error.detail, "Failed to detect source control provider.");
351 assert.strictEqual(error.cause, cause);
352 assert.equal(error.message.includes(cause.message), false);
353 }),
354);
355
356it.effect("routes GitLab remotes to the GitLab provider", () =>
357 Effect.gen(function* () {
358 const registry = yield* makeRegistry({
359 remotes: [{ name: "origin", url: "git@gitlab.com:group/project.git" }],
360 });
361
362 const provider = yield* registry.resolve({ cwd: "/repo" });
363
364 assert.strictEqual(provider.kind, "gitlab");
365 }),
366);
367
368it.effect("routes authenticated self-hosted GitLab remotes without relying on host naming", () =>
369 Effect.gen(function* () {
370 const registry = yield* makeRegistry({
371 remotes: [{ name: "origin", url: "https://self-hosted.example.test/group/project.git" }],
372 process: {
373 run: () =>
374 Effect.succeed(
375 processOutput(
376 `gitlab.com
377 x gitlab.com: API call failed: 401 Unauthorized
378 ! No token found
379self-hosted.example.test
380 ✓ Logged in to self-hosted.example.test as gitlab-user
381 ✓ Token found: ******
382`,
383 { exitCode: ChildProcessSpawner.ExitCode(1) },
384 ),
385 ),
386 },
387 });
388
389 const provider = yield* registry.resolve({ cwd: "/repo" });
390
391 assert.strictEqual(provider.kind, "gitlab");
392 }),
393);
394
395it.effect("refines the caller-selected remote instead of choosing another configured remote", () =>
396 Effect.gen(function* () {
397 const registry = yield* makeRegistry({
398 remotes: [{ name: "origin", url: "git@github.com:fork/project.git" }],
399 process: {
400 run: () =>
401 Effect.succeed(
402 processOutput(`self-hosted.example.test
403 ✓ Logged in to self-hosted.example.test as gitlab-user
404`),
405 ),
406 },
407 });
408
409 const handle = yield* registry.resolveHandle({
410 cwd: "/repo",
411 context: {
412 provider: {
413 kind: SourceControlProviderKind.make("unknown"),
414 name: "self-hosted.example.test",
415 baseUrl: "https://self-hosted.example.test",
416 },
417 remoteName: "upstream",
418 remoteUrl: "https://self-hosted.example.test/group/project.git",
419 },
420 });
421
422 assert.strictEqual(handle.context?.provider.kind, "gitlab");
423 assert.strictEqual(handle.context?.remoteName, "upstream");
424 }),
425);
426
427it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () =>
428 Effect.gen(function* () {
429 const registry = yield* makeRegistry({
430 remotes: [{ name: "origin", url: "https://self-hosted.example.test:8443/group/project.git" }],
431 process: {
432 run: () =>
433 Effect.succeed(
434 processOutput(
435 `self-hosted.example.test:8443
436 ✓ Logged in to self-hosted.example.test:8443 as gitlab-user
437 ✓ Token found: ******
438`,
439 ),
440 ),
441 },
442 });
443
444 const provider = yield* registry.resolve({ cwd: "/repo" });
445
446 assert.strictEqual(provider.kind, "gitlab");
447 }),
448);
449
450it.effect("routes Bitbucket remotes to the Bitbucket provider", () =>
451 Effect.gen(function* () {
452 const registry = yield* makeRegistry({
453 remotes: [{ name: "origin", url: "git@bitbucket.org:pingdotgg/t3code.git" }],
454 });
455
456 const provider = yield* registry.resolve({ cwd: "/repo" });
457
458 assert.strictEqual(provider.kind, "bitbucket");
459 }),
460);
461
462it.effect("routes Azure DevOps remotes to the Azure DevOps provider", () =>
463 Effect.gen(function* () {
464 const registry = yield* makeRegistry({
465 remotes: [{ name: "origin", url: "https://dev.azure.com/acme/project/_git/repo" }],
466 });
467
468 const provider = yield* registry.resolve({ cwd: "/repo" });
469
470 assert.strictEqual(provider.kind, "azure-devops");
471 }),
472);
473
474it.effect("falls back to a non-origin remote when origin is not configured", () =>
475 Effect.gen(function* () {
476 const registry = yield* makeRegistry({
477 remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
478 });
479
480 const provider = yield* registry.resolve({ cwd: "/repo" });
481
482 assert.strictEqual(provider.kind, "azure-devops");
483 }),
484);
485
486it.effect(
487 "routes linked subjects by URL independently of the checkout and skips unsupported links",
488 () =>
489 Effect.gen(function* () {
490 const registry = yield* makeRegistry({
491 remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
492 githubApi: {
493 rest: () =>
494 Effect.succeed({
495 status: 200,
496 headers: {},
497 body: JSON.stringify({ title: "GitHub issue", body: null }),
498 truncated: false,
499 invalidUtf8: false,
500 }),
501 },
502 gitlab: {
503 execute: () =>
504 Effect.succeed(
505 processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })),
506 ),
507 },
508 });
509 for (const [url, expected] of [
510 ["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }],
511 [
512 "https://gitlab.com/team/sub/project/-/merge_requests/2",
513 { title: "GitLab MR", body: "Nested project" },
514 ],
515 ] as const) {
516 const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) });
517 assert.ok(lookup);
518 assert.deepStrictEqual(yield* lookup, expected);
519 }
520 for (const url of [
521 "https://example.test/team/project/issues/1",
522 "https://github.attacker.test/team/project/issues/1",
523 "https://gitlab.attacker.test/team/project/-/issues/1",
524 "https://github.com/team/project",
525 "https://codeberg.org/team/project/issues/1",
526 "https://bitbucket.org/team/project/pull-requests/1",
527 "https://dev.azure.com/org/project/_git/repo/pullrequest/1",
528 "http://github.com/team/project/issues/1",
529 "https://user:secret@github.com/team/project/issues/1",
530 ]) {
531 assert.strictEqual(
532 registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }),
533 undefined,
534 );
535 }
536 }).pipe(Effect.scoped),
537);
538
539it.effect.each([
540 { name: "a credential", credential: "found", expected: "github" },
541 { name: "a host turned off in Settings", credential: "disabled", expected: "github" },
542 { name: "no credential", credential: "missing", expected: "unknown" },
543] as const)("resolves custom-host remotes with $name", (scenario) =>
544 Effect.gen(function* () {
545 const hosts: Array<string> = [];
546 const commands: Array<string> = [];
547 const registry = yield* makeRegistry({
548 remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }],
549 process: {
550 run: ({ command }) => {
551 commands.push(command);
552 return Effect.succeed(processOutput(""));
553 },
554 },
555 githubApi: {
556 credential: (host) => {
557 hosts.push(host);
558 return scenario.credential === "found"
559 ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
560 : scenario.credential === "disabled"
561 ? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host }))
562 : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
563 },
564 },
565 });
566 const handle = yield* registry.resolveHandle({ cwd: "/repo" });
567 assert.strictEqual(handle.provider.kind, SourceControlProviderKind.make(scenario.expected));
568 assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test");
569 assert.deepStrictEqual(hosts, ["code.example.test"]);
570 assert.notInclude(commands, "gh");
571 }),
572);
573
574it.effect("skips GitHub discovery for the identity resolver's empty base URL", () =>
575 Effect.gen(function* () {
576 const hosts: string[] = [];
577 const remoteUrl = "git@githubenterprise.dev.example.com:team/workspace.git";
578 const registry = yield* makeRegistry({
579 remotes: [{ name: "origin", url: remoteUrl }],
580 githubApi: {
581 credential: (host) => {
582 hosts.push(host);
583 return Effect.succeed({
584 token: Redacted.make("token"),
585 fingerprint: `${host}:fingerprint`,
586 });
587 },
588 },
589 });
590 const context = {
591 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" },
592 remoteName: "origin",
593 remoteUrl,
594 };
595 const unresolved = yield* registry.resolveHandle({ cwd: "/repo", context });
596 assert.deepStrictEqual(unresolved.context, context);
597 assert.deepStrictEqual(hosts, []);
598
599 const resolved = yield* registry.resolveHandle({ cwd: "/repo" });
600 assert.strictEqual(resolved.provider.kind, "github");
601 assert.strictEqual(
602 resolved.context?.provider.baseUrl,
603 "https://githubenterprise.dev.example.com",
604 );
605 assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]);
606 }),
607);
608
609const notFound = (command: string, cwd: string) =>
610 new VcsProcessSpawnError({
611 operation: "test",
612 command,
613 cwd,
614 cause: PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }),
615 });
616
617const resolveUnknown = (
618 registry: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"],
619 repository: string,
620) =>
621 registry.resolveHandle({
622 cwd: `/${repository}`,
623 context: {
624 provider: {
625 kind: SourceControlProviderKind.make("unknown"),
626 name: "git.example.internal",
627 baseUrl: "https://git.example.internal",
628 },
629 remoteName: "origin",
630 remoteUrl: `git@Git.Example.Internal:team/${repository}.git`,
631 },
632 });
633
634it.effect("asks once for every checkout of a server no integration claims", () =>
635 Effect.gen(function* () {
636 const asked: Array<string> = [];
637 const release = yield* Deferred.make<void>();
638 const registry = yield* makeRegistry({
639 remotes: [],
640 process: {
641 run: ({ command, args, cwd }) => {
642 asked.push([command, ...args].join(" "));
643 return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd))));
644 },
645 },
646 githubApi: {
647 credential: (host) => {
648 asked.push(`credential ${host}`);
649 return Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
650 },
651 },
652 forgejo: {
653 listLogins: ({ command = "tea", cwd }) => {
654 asked.push(command);
655 const cause = notFound(command, cwd);
656 return Effect.fail(new ForgejoCli.ForgejoCliError({ command, cwd, detail: "", cause }));
657 },
658 },
659 });
660
661 const started = yield* Effect.forEach(["a", "b", "c"], () => Deferred.make<void>());
662 const callers = yield* Effect.forEach(
663 ["a", "b", "c"],
664 (repository, index) =>
665 Deferred.succeed(started[index]!, undefined).pipe(
666 Effect.andThen(resolveUnknown(registry, repository)),
667 ),
668 { concurrency: "unbounded" },
669 ).pipe(Effect.forkChild);
670 yield* Effect.forEach(started, Deferred.await);
671 yield* Deferred.succeed(release, undefined);
672 const handles = yield* Fiber.join(callers);
673 yield* resolveUnknown(registry, "d");
674 assert.deepStrictEqual(
675 handles.map((handle) => handle.provider.kind),
676 ["unknown", "unknown", "unknown"],
677 );
678 const once = asked.slice();
679 assert.sameMembers(once, [
680 "credential git.example.internal",
681 "glab auth status --hostname Git.Example.Internal",
682 "fj",
683 "tea",
684 ]);
685
686 yield* TestClock.adjust("5 minutes");
687 yield* resolveUnknown(registry, "a");
688 assert.deepStrictEqual(asked, [...once, ...once]);
689 }),
690);
691
692it.effect("asks again after a check that could not answer", () =>
693 Effect.gen(function* () {
694 let asks = 0;
695 const registry = yield* makeRegistry({
696 remotes: [],
697 process: {
698 run: ({ command, cwd }) => {
699 asks += 1;
700 return Effect.fail(
701 new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }),
702 );
703 },
704 },
705 });
706 yield* resolveUnknown(registry, "a");
707 yield* resolveUnknown(registry, "b");
708 assert.strictEqual(asks, 2);
709 }),
710);
711
712it.effect("keeps both detection caches until normalized host mappings change", () =>
713 Effect.gen(function* () {
714 const changes = yield* PubSub.unbounded<{
715 settings: typeof DEFAULT_SERVER_SETTINGS;
716 handled: Deferred.Deferred<void>;
717 }>();
718 let listings = 0;
719 let probes = 0;
720 const registry = yield* makeRegistry({
721 remotes: [],
722 listRemotes: () =>
723 Effect.sync(() => {
724 listings += 1;
725 return {
726 remotes: [
727 {
728 name: "origin",
729 url: "https://code.example.test/team/repo.git",
730 pushUrl: Option.none(),
731 isPrimary: true,
732 },
733 ],
734 freshness: {
735 source: "live-local" as const,
736 observedAt: TEST_EPOCH,
737 expiresAt: Option.none(),
738 },
739 };
740 }),
741 settings: {
742 subscribeChanges: PubSub.subscribe(changes).pipe(
743 Effect.map((subscription) =>
744 Stream.fromSubscription(subscription).pipe(
745 Stream.flatMap(({ settings, handled }) =>
746 Stream.concat(
747 Stream.make(settings),
748 Stream.fromEffectDrain(Deferred.succeed(handled, undefined)),
749 ),
750 ),
751 ),
752 ),
753 ),
754 },
755 process: { run: ({ command, cwd }) => Effect.fail(notFound(command, cwd)) },
756 githubApi: {
757 credential: (host) => {
758 probes += 1;
759 return Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
760 },
761 },
762 });
763 const publish = Effect.fnUntraced(function* (settings: typeof DEFAULT_SERVER_SETTINGS) {
764 const handled = yield* Deferred.make<void>();
765 yield* PubSub.publish(changes, { settings, handled });
766 yield* Deferred.await(handled);
767 });
768 const resolve = (cwd = "/repo") => registry.resolveHandle({ cwd });
769 assert.strictEqual((yield* resolve()).provider.kind, "unknown");
770 assert.deepStrictEqual([listings, probes], [1, 1]);
771 for (const worktreesDirectory of ["/worktrees/a", "/worktrees/b"]) {
772 yield* publish({ ...DEFAULT_SERVER_SETTINGS, worktreesDirectory });
773 yield* resolve();
774 assert.deepStrictEqual([listings, probes], [1, 1]);
775 }
776 // A fresh checkout misses the context cache but must reuse settled host discovery.
777 yield* resolve("/other");
778 assert.deepStrictEqual([listings, probes], [2, 1]);
779 yield* publish({
780 ...DEFAULT_SERVER_SETTINGS,
781 sourceControlHostOverrides: {
782 "code.example.test": { kind: "gitlab", baseUrl: "https://code.example.test" },
783 },
784 });
785 assert.strictEqual((yield* resolve()).provider.kind, "gitlab");
786 assert.deepStrictEqual([listings, probes], [3, 1]);
787 yield* publish({
788 ...DEFAULT_SERVER_SETTINGS,
789 sourceControlHostOverrides: {
790 "CODE.EXAMPLE.TEST": { kind: "gitlab", baseUrl: "https://code.example.test/" },
791 },
792 });
793 assert.strictEqual((yield* resolve()).provider.kind, "gitlab");
794 assert.deepStrictEqual([listings, probes], [3, 1]);
795 yield* publish(DEFAULT_SERVER_SETTINGS);
796 assert.strictEqual((yield* resolve()).provider.kind, "unknown");
797 assert.deepStrictEqual([listings, probes], [4, 2]);
798 }),
799);