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

SourceControlRepositoryService.ts

578 lines21.8 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Path from "effect/Path";
6import * as Schedule from "effect/Schedule";
7import * as Schema from "effect/Schema";
8​
9import {
10 GitCommandError,
11 SourceControlProviderError,
12 SourceControlRepositoryError,
13 type GitCommandFailureReason,
14 type SourceControlCloneRepositoryInput,
15 type SourceControlCloneRepositoryResult,
16 type SourceControlCloneProtocol,
17 SourceControlProviderKind,
18 type SourceControlPublishRepositoryInput,
19 type SourceControlPublishRepositoryResult,
20 type SourceControlRepositoryCloneUrls,
21 type SourceControlRepositoryInfo,
22 type SourceControlRepositoryLookupInput,
23} from "@t3tools/contracts";
24​
25import * as ServerConfig from "../config.ts";
26import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
27import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
28import {
29 parseGitCloneProgressLine,
30 type GitCloneProgressLine,
31} from "../project/gitCloneProgress.ts";
32import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
33import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
34import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
35import * as HostProcess from "@t3tools/shared/HostProcess";
36import { cloneUrlForProtocol, cloneUrlProtocol } from "@t3tools/shared/cloneUrl";
37const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
38const isSourceControlProviderError = Schema.is(SourceControlProviderError);
39const isGitCommandError = Schema.is(GitCommandError);
40​
41export class SourceControlRepositoryService extends Context.Service<
42 SourceControlRepositoryService,
43 {
44 readonly lookupRepository: (
45 input: SourceControlRepositoryLookupInput,
46 ) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
47 readonly prepareClone: (
48 input: SourceControlCloneRepositoryInput,
49 ) => Effect.Effect<SourceControlPreparedClone, SourceControlRepositoryError>;
50 readonly cloneRepository: (
51 input: SourceControlCloneRepositoryInput,
52 options?: SourceControlCloneOptions,
53 ) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
54 readonly discardClone: (
55 destinationPath: string,
56 ) => Effect.Effect<void, SourceControlRepositoryError>;
57 readonly publishRepository: (
58 input: SourceControlPublishRepositoryInput,
59 ) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
60 }
61>()("t3/sourceControl/SourceControlRepositoryService") {}
62​
63export interface SourceControlPreparedClone {
64 readonly destinationPath: string;
65 readonly remoteUrl: string;
66 readonly cloneUrl: string;
67 readonly repository: SourceControlRepositoryInfo | null;
69​
70export interface SourceControlCloneOptions {
71 readonly onProgress?: (line: GitCloneProgressLine) => Effect.Effect<void>;
72 /** Overrides the default clone budget; `null` disables the deadline. */
73 readonly timeoutMs?: number | null;
75​
76// The synchronous RPC (older clients, mobile) keeps a deadline: nothing else
77// tells the user a clone stalled. The tracked path passes null and relies on
78// progress and Cancel instead.
79const CLONE_TIMEOUT_MS = 120_000;
80const CLONE_ENV = {
81 // `--progress` forces the transfer counters through the pipe; the delay env
82 // makes the checkout counter start immediately. No tty means a credential
83 // prompt would hang forever, so tell git to fail instead.
84 GIT_PROGRESS_DELAY: "0",
85 GIT_TERMINAL_PROMPT: "0",
86 LC_ALL: "C",
87} satisfies NodeJS.ProcessEnv;
88​
89function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
90 return Effect.mapError((cause: unknown) =>
91 isSourceControlRepositoryError(cause)
92 ? cause
93 : new SourceControlRepositoryError({
94 operation,
95 provider,
96 detail:
97 (isSourceControlProviderError(cause)
98 ? SourceControlProvider.userFacingSourceControlDetail(cause.cause)
99 : undefined) ?? "The source control operation could not be completed.",
100 cause,
101 }),
102 );
104​
105function toRepositoryInfo(
106 provider: SourceControlProviderKind,
107 urls: SourceControlRepositoryCloneUrls,
108): SourceControlRepositoryInfo {
109 return {
110 provider,
111 nameWithOwner: urls.nameWithOwner,
112 url: urls.url,
113 sshUrl: urls.sshUrl,
114 };
116​
117/**
118 * The URL clients see. A pasted `https://user:token@host/…` must not travel
119 * back over `subscribeProjectClones` to every reader; git still gets the
120 * original.
121 */
122function redactRemoteUrl(remoteUrl: string): string {
123 try {
124 const url = new URL(remoteUrl);
125 // Clone URLs have no legitimate query; when one is present it is a token.
126 if (url.username.length === 0 && url.password.length === 0 && url.search.length === 0) {
127 return remoteUrl;
128 }
129 url.username = "";
130 url.password = "";
131 url.search = "";
132 return url.toString();
133 } catch {
134 return remoteUrl;
135 }
137​
138// Userinfo may itself contain `@`; everything up to the last one before the
139// host boundary goes.
140const URL_WITH_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/]+@/gi;
141​
142function redactUrlCredentials(text: string): string {
143 return text.replace(URL_WITH_USERINFO, "$1");
145​
146/**
147 * Explains a failed first push of a published repository. The repository
148 * already exists by then, so publishing again cannot help; the user has to
149 * fix access and push. Built from fixed text and the provider's URLs only,
150 * since git's stderr can carry credentials.
151 */
152function publishPushFailureDetail(input: {
153 readonly urls: SourceControlRepositoryCloneUrls;
154 readonly remoteName: string;
155 readonly remoteUrl: string;
156 readonly reason: GitCommandFailureReason | undefined;
157}): string {
158 const created = `Created ${input.urls.nameWithOwner} and added it as remote "${input.remoteName}", but the push failed`;
159 const switchToHttps = `git remote set-url ${input.remoteName} ${input.urls.url}`;
160 const usesSsh = input.remoteUrl === input.urls.sshUrl;
161 switch (input.reason) {
162 case "authentication_failed":
163 return usesSsh
164 ? `${created} because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "${switchToHttps}", then push again.`
165 : `${created} because Git could not authenticate. Check your Git credentials, then push again.`;
166 case "host_key_unverified":
167 return `${created} because the host's SSH key is not trusted yet. Verify it by connecting once with ssh, or switch the remote to HTTPS with "${switchToHttps}", then push again.`;
168 default:
169 return `${created}. Fix the problem, then push again.`;
170 }
172​
173/**
174 * Adding a project clones over SSH for most hosts, and a machine with no SSH
175 * key there would fail every time, while the host's HTTPS credential helper
176 * may be set up. A clone whose SSH login was refused is retried once over
177 * HTTPS, unless the caller asked for SSH. A looked-up repository has the
178 * provider's own HTTPS URL; any other URL is rewritten, which is refused
179 * where it would have to guess.
180 */
181function httpsFallbackUrl(
182 input: SourceControlCloneRepositoryInput,
183 prepared: SourceControlPreparedClone,
184): string | null {
185 if (input.protocol === "ssh" || cloneUrlProtocol(prepared.cloneUrl) !== "ssh") return null;
186 if (prepared.repository?.sshUrl === prepared.cloneUrl) return prepared.repository.url;
187 return cloneUrlForProtocol(prepared.cloneUrl, "https");
189​
190const isSshRejection = (error: SourceControlRepositoryError) =>
191 isGitCommandError(error.cause) &&
192 (error.cause.reason === "authentication_failed" || error.cause.reason === "host_key_unverified");
193​
194function selectRemoteUrl(
195 urls: SourceControlRepositoryCloneUrls,
196 protocol: SourceControlCloneProtocol | undefined,
197): string {
198 switch (protocol ?? "auto") {
199 case "https":
200 return urls.url;
201 case "ssh":
202 case "auto":
203 return urls.sshUrl;
204 }
206​
207/** @public Service construction is part of the canonical Effect module API. */
208export const make = Effect.gen(function* () {
209 const config = yield* ServerConfig.ServerConfig;
210 const fileSystem = yield* FileSystem.FileSystem;
211 const git = yield* GitVcsDriver.GitVcsDriver;
212 const path = yield* Path.Path;
213 const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
214​
215 const ensureConcreteProvider = (input: {
216 readonly operation: string;
217 readonly provider: SourceControlProviderKind;
218 }) => {
219 if (input.provider !== "unknown") {
220 return Effect.succeed(input.provider);
221 }
222​
223 return Effect.fail(
224 new SourceControlRepositoryError({
225 operation: input.operation,
226 provider: input.provider,
227 detail: "Choose a source control provider before continuing.",
228 }),
229 );
230 };
231​
232 const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(
233 function* (input: SourceControlRepositoryLookupInput) {
234 const providerKind = yield* ensureConcreteProvider({
235 operation: "lookupRepository",
236 provider: input.provider,
237 });
238 const provider = yield* providers.get(providerKind);
239 const urls = yield* provider.getRepositoryCloneUrls({
240 cwd: input.cwd ?? config.cwd,
241 repository: input.repository.trim(),
242 });
243 return toRepositoryInfo(providerKind, urls);
244 },
245 // Someone adding or cloning a repository is waiting, so a background rate-limit pause must not
246 // refuse the lookup.
247 Effect.provideService(SourceControlRateLimit.Interactive, true),
248 );
249​
250 const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
251 function* (destinationPath: string) {
252 const trimmed = destinationPath.trim();
253 if (trimmed.length === 0) {
254 return yield* new SourceControlRepositoryError({
255 operation: "cloneRepository",
256 provider: SourceControlProviderKind.make("unknown"),
257 detail: "Choose a destination path before cloning.",
258 });
259 }
260​
261 return path.resolve(expandHomePath(trimmed, yield* HostProcess.HomeDirectory));
262 },
263 );
264​
265 const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
266 function* (destinationPath: string) {
267 const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
268 if (yield* fileSystem.exists(normalizedDestination)) {
269 const entries = yield* fileSystem
270 .readDirectory(normalizedDestination, { recursive: false })
271 .pipe(
272 Effect.mapError(
273 (cause) =>
274 new SourceControlRepositoryError({
275 operation: "cloneRepository",
276 provider: SourceControlProviderKind.make("unknown"),
277 detail: "Destination path already exists and is not a directory.",
278 cause,
279 }),
280 ),
281 );
282 if (entries.length > 0) {
283 return yield* new SourceControlRepositoryError({
284 operation: "cloneRepository",
285 provider: SourceControlProviderKind.make("unknown"),
286 detail: "Destination path already exists and is not empty.",
287 });
288 }
289 } else {
290 // Skip existing parents: recursive mkdir on a Windows drive root fails with EPERM.
291 const parentPath = path.dirname(normalizedDestination);
292 if (!(yield* fileSystem.exists(parentPath))) {
293 yield* fileSystem.makeDirectory(parentPath, { recursive: true });
294 }
295 }
296​
297 return {
298 destinationPath: normalizedDestination,
299 parentPath: path.dirname(normalizedDestination),
300 directoryName: path.basename(normalizedDestination),
301 };
302 },
303 );
304​
305 const prepareClone = Effect.fn("SourceControlRepositoryService.prepareClone")(function* (
306 input: SourceControlCloneRepositoryInput,
307 ) {
308 const preparedDestination = yield* prepareDestination(input.destinationPath);
309 let repository: SourceControlRepositoryInfo | null = null;
310 let remoteUrl = input.remoteUrl?.trim() ?? null;
311 let provider: SourceControlProviderKind =
312 input.provider ?? SourceControlProviderKind.make("unknown");
313​
314 if (input.provider && input.repository) {
315 repository = yield* lookupRepository({
316 provider: input.provider,
317 repository: input.repository,
318 cwd: preparedDestination.parentPath,
319 });
320 remoteUrl = selectRemoteUrl(repository, input.protocol);
321 provider = input.provider;
322 }
323​
324 if (!remoteUrl) {
325 return yield* new SourceControlRepositoryError({
326 operation: "cloneRepository",
327 provider,
328 detail: "Enter a repository path or clone URL before cloning.",
329 });
330 }
331​
332 return {
333 destinationPath: preparedDestination.destinationPath,
334 remoteUrl: redactRemoteUrl(remoteUrl),
335 cloneUrl: remoteUrl,
336 repository,
337 } satisfies SourceControlPreparedClone;
338 });
339​
340 const runClone = Effect.fn("SourceControlRepositoryService.runClone")(function* (
341 input: SourceControlCloneRepositoryInput,
342 destinationPath: string,
343 cloneUrl: string,
344 options?: SourceControlCloneOptions,
345 ) {
346 const onProgress = options?.onProgress;
347 // Git interleaves progress redraws with its real messages on stderr. The
348 // last non-progress lines are what explain a failure ("Repository not
349 // found", "Permission denied"), so keep them for the error detail.
350 const stderrTail: Array<string> = [];
351 const onStderrLine = (line: string) => {
352 const parsed = parseGitCloneProgressLine(line);
353 if (parsed) return onProgress ? onProgress(parsed) : Effect.void;
354 return Effect.sync(() => {
355 const trimmed = line.trim();
356 if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return;
357 // Git echoes the remote in some failures; the tail becomes user-facing text.
358 stderrTail.push(redactUrlCredentials(trimmed));
359 if (stderrTail.length > 4) stderrTail.shift();
360 });
361 };
362 yield* git
363 .execute({
364 operation: "SourceControlRepositoryService.cloneRepository",
365 cwd: path.dirname(destinationPath),
366 args: ["clone", "--progress", "--", cloneUrl, path.basename(destinationPath)],
367 timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs,
368 // Progress redraws add up on a slow multi-GB clone. The buffered copy
369 // is never read (the tail is kept by hand above), so keep it small
370 // and let the line callbacks keep flowing past the cap.
371 maxOutputBytes: 256 * 1024,
372 appendTruncationMarker: true,
373 keepLineCallbacksAfterTruncation: true,
374 env: CLONE_ENV,
375 progress: { onStderrLine },
376 })
377 .pipe(
378 Effect.mapError(
379 (cause) =>
380 new SourceControlRepositoryError({
381 operation: "cloneRepository",
382 provider: input.provider ?? SourceControlProviderKind.make("unknown"),
383 detail:
384 stderrTail.length > 0
385 ? stderrTail.join(" ")
386 : "The repository could not be cloned.",
387 cause,
388 }),
389 ),
390 );
391 });
392​
393 const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
394 input: SourceControlCloneRepositoryInput,
395 options?: SourceControlCloneOptions,
396 ) {
397 const prepared = yield* prepareClone(input);
398 const httpsUrl = httpsFallbackUrl(input, prepared);
399 const remoteUrl = yield* runClone(
400 input,
401 prepared.destinationPath,
402 prepared.cloneUrl,
403 options,
404 ).pipe(
405 Effect.as(prepared.remoteUrl),
406 Effect.catch((sshError) =>
407 httpsUrl === null || !isSshRejection(sshError)
408 ? Effect.fail(sshError)
409 : runClone(input, prepared.destinationPath, httpsUrl, options).pipe(
410 Effect.as(redactRemoteUrl(httpsUrl)),
411 Effect.mapError(
412 (httpsError) =>
413 new SourceControlRepositoryError({
414 operation: "cloneRepository",
415 provider: sshError.provider,
416 detail: `${sshError.detail} Cloning over HTTPS instead also failed: ${httpsError.detail}`,
417 cause: httpsError.cause,
418 }),
419 ),
420 ),
421 ),
422 );
423​
424 return {
425 cwd: prepared.destinationPath,
426 remoteUrl,
427 repository: prepared.repository,
428 };
429 });
430​
431 const discardClone = Effect.fn("SourceControlRepositoryService.discardClone")(function* (
432 destinationPath: string,
433 ) {
434 const normalized = yield* normalizeDestinationPath(destinationPath);
435 // Only what git left behind may go. The destination was empty when the
436 // clone started, so anything without a `.git` inside was put there by
437 // someone else since; refuse rather than delete their files.
438 // A missing destination is already discarded; any other read failure
439 // (a file in its place, permissions) is not something to remove through.
440 const entries = yield* fileSystem.readDirectory(normalized).pipe(
441 Effect.catchIf(
442 (cause) => cause.reason._tag === "NotFound",
443 () => Effect.succeed<ReadonlyArray<string>>([]),
444 ),
445 Effect.mapError(
446 (cause) =>
447 new SourceControlRepositoryError({
448 operation: "discardClone",
449 provider: SourceControlProviderKind.make("unknown"),
450 detail: "The clone destination could not be inspected.",
451 cause,
452 }),
453 ),
454 );
455 if (entries.length > 0 && !entries.includes(".git")) {
456 return yield* new SourceControlRepositoryError({
457 operation: "discardClone",
458 provider: SourceControlProviderKind.make("unknown"),
459 detail: "Destination path contains files that are not from the clone.",
460 });
461 }
462 // The directory itself is the project's workspace root and must stay;
463 // only git's partial contents go. An interrupted git may still be closing
464 // files, so removal retries briefly.
465 yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe(
466 Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })),
467 Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }),
468 Effect.mapError(
469 (cause) =>
470 new SourceControlRepositoryError({
471 operation: "discardClone",
472 provider: SourceControlProviderKind.make("unknown"),
473 detail: "The partial clone could not be removed.",
474 cause,
475 }),
476 ),
477 );
478 });
479​
480 const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
481 function* (input: SourceControlPublishRepositoryInput) {
482 const providerKind = yield* ensureConcreteProvider({
483 operation: "publishRepository",
484 provider: input.provider,
485 });
486 const provider = yield* providers.get(providerKind);
487 const urls = yield* provider.createRepository({
488 cwd: input.cwd,
489 repository: input.repository.trim(),
490 visibility: input.visibility,
491 });
492 const remoteUrl = selectRemoteUrl(urls, input.protocol);
493 const remoteName = yield* git.ensureRemote({
494 cwd: input.cwd,
495 preferredName: input.remoteName?.trim() || "origin",
496 url: remoteUrl,
497 });
498​
499 // An empty local repo (no commits) would make `git push HEAD:...` fail
500 // with an opaque "src refspec HEAD does not match any". Treat this as a
501 // partial success: the remote was created and wired up, but there is
502 // nothing to push yet.
503 const hasCommits = yield* git
504 .execute({
505 operation: "SourceControlRepositoryService.publishRepository.headCheck",
506 cwd: input.cwd,
507 args: ["rev-parse", "--verify", "HEAD"],
508 })
509 .pipe(
510 Effect.map(() => true),
511 Effect.orElseSucceed(() => false),
512 );
513 if (!hasCommits) {
514 const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));
515 return {
516 repository: toRepositoryInfo(providerKind, urls),
517 remoteName,
518 remoteUrl,
519 branch: details?.branch ?? "main",
520 status: "remote_added" as const,
521 };
522 }
523​
524 const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName }).pipe(
525 Effect.mapError(
526 (cause) =>
527 new SourceControlRepositoryError({
528 operation: "publishRepository",
529 provider: providerKind,
530 detail: publishPushFailureDetail({
531 urls,
532 remoteName,
533 remoteUrl,
534 reason: cause.reason,
535 }),
536 cause,
537 }),
538 ),
539 );
540​
541 return {
542 repository: toRepositoryInfo(providerKind, urls),
543 remoteName,
544 remoteUrl,
545 branch: pushResult.branch,
546 ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
547 status: "pushed" as const,
548 };
549 },
550 );
551​
552 return SourceControlRepositoryService.of({
553 lookupRepository: (input) =>
554 lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
555 prepareClone: (input) =>
556 prepareClone(input).pipe(
557 mapRepositoryError(
558 "cloneRepository",
559 input.provider ?? SourceControlProviderKind.make("unknown"),
560 ),
561 ),
562 cloneRepository: (input, options) =>
563 cloneRepository(input, options).pipe(
564 mapRepositoryError(
565 "cloneRepository",
566 input.provider ?? SourceControlProviderKind.make("unknown"),
567 ),
568 ),
569 discardClone: (destinationPath) =>
570 discardClone(destinationPath).pipe(
571 mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")),
572 ),
573 publishRepository: (input) =>
574 publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
575 });
576});
577​
578export const layer = Layer.effect(SourceControlRepositoryService, make);