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

discovery.ts

430 lines14.6 KB

1import * as NodeUtil from "node:util";
2import {
3 VcsProcessSpawnError,
4 type SourceControlProviderAuth,
5 type SourceControlProviderDiscoveryItem,
6 type SourceControlProviderInfo,
7 type SourceControlProviderKind,
8} from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { SpawnExecutableResolution } from "@t3tools/shared/shell";
11import type * as Cause from "effect/Cause";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as PlatformError from "effect/PlatformError";
15import * as Result from "effect/Result";
16import * as Schema from "effect/Schema";
17​
18import type * as SourceControlProvider from "./SourceControlProvider.ts";
19import type * as SourceControlHost from "./SourceControlHost.ts";
20​
21export interface SourceControlAuthProbeInput {
22 readonly stdout: string;
23 readonly stderr: string;
24 readonly exitCode: SourceControlHost.SourceControlProcessOutput["exitCode"];
26​
27export interface SourceControlUnknownRemoteRefinementInput {
28 readonly cwd: string;
29 readonly context: SourceControlProvider.SourceControlProviderContext;
30 readonly auth: SourceControlAuthProbeInput;
32​
33interface SourceControlDiscoverySpecBase {
34 readonly kind: SourceControlProviderKind;
35 readonly label: string;
36 readonly installHint: string;
38​
39export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {
40 readonly type: "cli";
41 readonly executable: string;
42 readonly versionArgs: ReadonlyArray<string>;
43 readonly authArgs: ReadonlyArray<string>;
44 /** Asked once when `authArgs` reports signed out; its answer counts only when it finds a sign-in. */
45 readonly authRetryArgs?: ReadonlyArray<string>;
46 readonly remoteRefinementArgs?: (
47 context: SourceControlProvider.SourceControlProviderContext,
48 ) => ReadonlyArray<string>;
49 readonly probeTimeoutMs?: number;
50 readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;
51 /** `null` when the CLI holds nothing for the remote; `undefined` when its output cannot say. */
52 readonly refineUnknownRemote?: (
53 input: SourceControlUnknownRemoteRefinementInput,
54 ) => SourceControlProviderInfo | null | undefined;
55};
56​
57export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
58 readonly type: "api";
59 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
60};
61​
62export type SourceControlManagedCliDiscoverySpec = SourceControlDiscoverySpecBase & {
63 readonly type: "managed-cli";
64 readonly probe: (cwd: string) => Effect.Effect<SourceControlProviderDiscoveryItem>;
65 /** Null includes missing CLIs. Failure means unknown and must not be cached by the registry. */
66 readonly refineUnknownRemote: (input: {
67 readonly cwd: string;
68 readonly context: SourceControlProvider.SourceControlProviderContext;
69 }) => Effect.Effect<SourceControlProviderInfo | null, Cause.YieldableError>;
70};
71​
72export type SourceControlProviderDiscoverySpec =
73 | SourceControlCliDiscoverySpec
74 | SourceControlManagedCliDiscoverySpec
75 | SourceControlApiDiscoverySpec;
76​
77type SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & {
78 readonly refineUnknownRemote: NonNullable<SourceControlCliDiscoverySpec["refineUnknownRemote"]>;
79};
80​
81const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
82/** An API host that stalls must not hold the whole discovery answer behind it. */
83const API_PROBE_TIMEOUT = "3 seconds";
84​
85function probeTimeoutMs(spec: SourceControlCliDiscoverySpec): number {
86 return spec.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
88​
89interface DiscoveryProbeResult {
90 readonly kind: SourceControlProviderKind;
91 readonly label: string;
92 readonly executable: string;
93 readonly status: "available" | "missing";
94 readonly version: Option.Option<string>;
95 readonly installHint: string;
96 readonly detail: Option.Option<string>;
98​
99export function firstNonEmptyLine(text: string): Option.Option<string> {
100 const line = NodeUtil.stripVTControlCharacters(text)
101 .split(/\r?\n/)
102 .map((entry) => entry.trim())
103 .find((entry) => entry.length > 0);
104 return line === undefined ? Option.none() : Option.some(line);
106​
107export function detailFromCause(cause: unknown): Option.Option<string> {
108 if (cause instanceof Error && cause.message.trim().length > 0) {
109 return Option.some(cause.message.trim());
110 }
111 return Option.none();
113​
114function authAccount(account: string | undefined): Option.Option<string> {
115 const trimmed = account?.trim();
116 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
118​
119function authHost(host: string | undefined): Option.Option<string> {
120 const trimmed = host?.trim();
121 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
123​
124function authDetail(detail: string | undefined): Option.Option<string> {
125 const trimmed = detail?.trim();
126 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
128​
129export function providerAuth(input: {
130 readonly status: SourceControlProviderAuth["status"];
131 readonly account?: string | undefined;
132 readonly host?: string | undefined;
133 readonly detail?: string | undefined;
134}): SourceControlProviderAuth {
135 return {
136 status: input.status,
137 account: authAccount(input.account),
138 host: authHost(input.host),
139 detail: authDetail(input.detail),
140 };
142​
143function unknownAuth(detail?: string): SourceControlProviderAuth {
144 return providerAuth({ status: "unknown", detail });
146​
147export function combinedAuthOutput(input: SourceControlAuthProbeInput): string {
148 const parts: string[] = [];
149 for (const entry of [input.stdout, input.stderr]) {
150 if (entry.trim().length > 0) {
151 parts.push(entry);
152 }
153 }
154 return parts.join("\n");
156​
157function sanitizedAuthLines(text: string): ReadonlyArray<string> {
158 const lines: string[] = [];
159 for (const entry of text.split(/\r?\n/)) {
160 const line = entry.trim();
161 if (line.length === 0) continue;
162 if (/^[-\s]*token(?:\s+scopes?)?:/iu.test(line)) continue;
163 lines.push(line);
164 }
165 return lines;
167​
168export function firstSafeAuthLine(text: string): string | undefined {
169 return sanitizedAuthLines(text)[0];
171​
172export function parseCliHost(text: string): string | undefined {
173 return sanitizedAuthLines(text)
174 .map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
175 .find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
177​
178export function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
179 for (const pattern of patterns) {
180 const match = pattern.exec(text);
181 const value = match?.[1]?.trim();
182 if (value && value.length > 0) return value;
183 }
184 return undefined;
186​
187function isCliRemoteRefinementSpec(
188 spec: SourceControlProviderDiscoverySpec,
189): spec is SourceControlCliRemoteRefinementSpec {
190 return spec.type === "cli" && spec.refineUnknownRemote !== undefined;
192​
193function probeCli(input: {
194 readonly spec: SourceControlCliDiscoverySpec;
195 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
196 readonly cwd: string;
197}): Effect.Effect<DiscoveryProbeResult> {
198 return input.process
199 .run({
200 operation: "source-control.discovery.probe",
201 command: input.spec.executable,
202 args: input.spec.versionArgs,
203 cwd: input.cwd,
204 timeoutMs: probeTimeoutMs(input.spec),
205 maxOutputBytes: 8_000,
206 appendTruncationMarker: true,
207 })
208 .pipe(
209 Effect.map(
210 (result) =>
211 ({
212 kind: input.spec.kind,
213 label: input.spec.label,
214 executable: input.spec.executable,
215 status: "available" as const,
216 version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
217 firstNonEmptyLine(result.stderr),
218 ),
219 installHint: input.spec.installHint,
220 detail: Option.none<string>(),
221 }) satisfies DiscoveryProbeResult,
222 ),
223 Effect.catch((cause) =>
224 Effect.gen(function* () {
225 const installHint = yield* unavailableInstallHint(
226 input.spec.executable,
227 input.spec.installHint,
228 cause,
229 );
230 return {
231 kind: input.spec.kind,
232 label: input.spec.label,
233 executable: input.spec.executable,
234 status: "missing" as const,
235 version: Option.none<string>(),
236 installHint,
237 detail: detailFromCause(cause),
238 } satisfies DiscoveryProbeResult;
239 }),
240 ),
241 );
243​
244export function probeSourceControlProvider(input: {
245 readonly spec: SourceControlProviderDiscoverySpec;
246 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
247 readonly cwd: string;
248}): Effect.Effect<SourceControlProviderDiscoveryItem> {
249 if (input.spec.type === "managed-cli") return input.spec.probe(input.cwd);
250 if (input.spec.type === "api") {
251 return input.spec.probeAuth.pipe(
252 Effect.timeoutOption(API_PROBE_TIMEOUT),
253 Effect.map(
254 Option.getOrElse(() =>
255 unknownAuth("The hosting service did not answer in time. Refresh to try again."),
256 ),
257 ),
258 Effect.map(
259 (auth) =>
260 ({
261 kind: input.spec.kind,
262 label: input.spec.label,
263 status: "available" as const,
264 version: Option.none<string>(),
265 installHint: input.spec.installHint,
266 detail: Option.none<string>(),
267 auth,
268 }) satisfies SourceControlProviderDiscoveryItem,
269 ),
270 );
271 }
272​
273 const spec = input.spec;
274 const runAuth = (args: ReadonlyArray<string>) =>
275 input.process
276 .run({
277 operation: "source-control.discovery.auth",
278 command: spec.executable,
279 args,
280 cwd: input.cwd,
281 allowNonZeroExit: true,
282 timeoutMs: probeTimeoutMs(spec),
283 maxOutputBytes: 8_000,
284 appendTruncationMarker: true,
285 })
286 .pipe(
287 Effect.map(spec.parseAuth),
288 Effect.catch((cause) =>
289 Effect.succeed(unknownAuth(Option.getOrUndefined(detailFromCause(cause)))),
290 ),
291 );
292 const retryArgs = spec.authRetryArgs;
293 const auth =
294 retryArgs === undefined
295 ? runAuth(spec.authArgs)
296 : runAuth(spec.authArgs).pipe(
297 Effect.filterOrElse(
298 (result) => result.status !== "unauthenticated",
299 (signedOut) =>
300 runAuth(retryArgs).pipe(
301 Effect.map((retry) => (retry.status === "authenticated" ? retry : signedOut)),
302 ),
303 ),
304 );
305​
306 // The auth check does not depend on the version output, so both spawn at once.
307 return Effect.all(
308 [
309 probeCli({
310 spec,
311 process: input.process,
312 cwd: input.cwd,
313 }),
314 auth,
315 ],
316 { concurrency: "unbounded" },
317 ).pipe(
318 Effect.map(
319 ([item, auth]) =>
320 ({
321 ...item,
322 auth:
323 item.status === "available"
324 ? auth
325 : unknownAuth("Hosting integration command was not found on the server PATH."),
326 }) satisfies SourceControlProviderDiscoveryItem,
327 ),
328 );
330​
331const isVcsProcessSpawnError = Schema.is(VcsProcessSpawnError);
332​
333/** The spawner checks cwd first, so ChildProcess NotFound identifies the executable. */
334export function isMissingExecutable(error: unknown): boolean {
335 return (
336 isVcsProcessSpawnError(error) &&
337 PlatformError.isPlatformError(error.cause) &&
338 error.cause.reason._tag === "NotFound" &&
339 error.cause.reason.module === "ChildProcess"
340 );
342​
343// macOS's EBADARCH, which Node has no name for: the binary is built for another CPU, such as an
344// Intel-only `gh` on Apple Silicon without Rosetta.
345const BAD_CPU_TYPE_ERRNO = -86;
346​
347export const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(function* (
348 executable: string,
349 installHint: string,
350 cause: unknown,
351) {
352 const platform = yield* HostProcess.Platform;
353 if (
354 platform !== "darwin" ||
355 !isVcsProcessSpawnError(cause) ||
356 !(cause.cause instanceof Error) ||
357 !("errno" in cause.cause) ||
358 cause.cause.errno !== BAD_CPU_TYPE_ERRNO
359 ) {
360 return installHint;
361 }
362 const resolveExecutable = yield* SpawnExecutableResolution;
363 const path = resolveExecutable(executable, platform, yield* HostProcess.Environment);
364 const architecture = yield* HostProcess.Architecture;
365 return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`;
366});
367​
368class UnknownRemoteUnanswered extends Schema.TaggedError<UnknownRemoteUnanswered>()(
369 "UnknownRemoteUnanswered",
370 {},
371) {}
372​
373export interface UnknownRemoteVerdict {
374 readonly provider: SourceControlProviderInfo | null;
375 readonly settled: boolean;
377​
378function refineWithSpec(input: {
379 readonly spec: SourceControlProviderDiscoverySpec;
380 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
381 readonly cwd: string;
382 readonly context: SourceControlProvider.SourceControlProviderContext;
383}): Effect.Effect<SourceControlProviderInfo | null, Cause.YieldableError> {
384 const { spec, context } = input;
385 if (spec.type === "managed-cli") {
386 return spec.refineUnknownRemote({ cwd: input.cwd, context });
387 }
388 if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null);
389 return input.process
390 .run({
391 operation: "source-control.discovery.refine-unknown-remote",
392 command: spec.executable,
393 args: spec.remoteRefinementArgs?.(context) ?? spec.authArgs,
394 cwd: input.cwd,
395 allowNonZeroExit: true,
396 timeoutMs: probeTimeoutMs(spec),
397 maxOutputBytes: 8_000,
398 appendTruncationMarker: true,
399 })
400 .pipe(
401 Effect.catchIf(isMissingExecutable, () => Effect.void),
402 Effect.flatMap((auth) => {
403 const provider =
404 auth === undefined ? null : spec.refineUnknownRemote({ cwd: input.cwd, context, auth });
405 return provider === undefined
406 ? Effect.fail(new UnknownRemoteUnanswered())
407 : Effect.succeed(provider);
408 }),
409 );
411​
412export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvider")(
413 function* (input: {
414 readonly specs: ReadonlyArray<SourceControlProviderDiscoverySpec>;
415 readonly process: SourceControlHost.SourceControlHost["Service"]["process"];
416 readonly cwd: string;
417 readonly context: SourceControlProvider.SourceControlProviderContext;
418 }): Effect.fn.Return<UnknownRemoteVerdict> {
419 const results = yield* Effect.forEach(input.specs, (spec) =>
420 refineWithSpec({ ...input, spec }).pipe(Effect.result),
421 );
422 // An earlier integration that could not answer might have claimed this host.
423 let settled = true;
424 for (const result of results) {
425 if (Result.isFailure(result)) settled = false;
426 else if (result.success !== null) return { provider: result.success, settled };
427 }
428 return { provider: null, settled };
429 },
430);