Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import type {
3 ProjectCloneSnapshot,
4 ProjectCloneStage,
5 ProjectCloneStartInput,
6 ProjectCloneStartResult,
7 ProjectId,
8 SourceControlCloneProtocol,
9 SourceControlRepositoryInfo,
10} from "@t3tools/contracts";
11import {
12 OrchestrationDispatchCommandError,
13 PROJECT_CLONE_DETAIL_MAX_LENGTH,
14 PROJECT_CLONE_ERROR_MAX_LENGTH,
15 SourceControlRepositoryError,
16} from "@t3tools/contracts";
17import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations";
18import * as Cause from "effect/Cause";
19import * as Context from "effect/Context";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as Fiber from "effect/Fiber";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as PubSub from "effect/PubSub";
27import * as Queue from "effect/Queue";
28import * as Ref from "effect/Ref";
29import * as Schema from "effect/Schema";
30import * as Semaphore from "effect/Semaphore";
31import * as Scope from "effect/Scope";
32import * as Stream from "effect/Stream";
33
34import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
35import type { ProjectConflictError } from "./ProjectService.ts";
36
37export class ProjectCloneTracker extends Context.Service<
38 ProjectCloneTracker,
39 {
40 readonly start: (
41 input: ProjectCloneStartInput,
42 hooks: ProjectCloneHooks,
43 ) => Effect.Effect<
44 ProjectCloneStartResult,
45 SourceControlRepositoryError | OrchestrationDispatchCommandError
46 >;
47 /** Interrupts a running clone and deletes the partial checkout. */
48 readonly cancel: (projectId: ProjectId) => Effect.Effect<boolean>;
49 readonly retry: (projectId: ProjectId) => Effect.Effect<boolean, SourceControlRepositoryError>;
50 /** Stops tracking, interrupts any running clone and removes unfinished checkouts. */
51 readonly discard: (projectId: ProjectId) => Effect.Effect<void>;
52 readonly get: (projectId: ProjectId) => Effect.Effect<ProjectCloneSnapshot | null>;
53 readonly stream: Stream.Stream<ReadonlyArray<ProjectCloneSnapshot>>;
54 }
55>()("t3/project/ProjectCloneTracker") {}
56
57export interface ProjectCloneHooks {
58 /** Fails with `ProjectConflictError` when another project already owns the destination. */
59 readonly createProject: (input: {
60 readonly projectId: ProjectId;
61 readonly title: string;
62 readonly workspaceRoot: string;
63 readonly createdAt: string;
64 }) => Effect.Effect<void, OrchestrationDispatchCommandError | ProjectConflictError>;
65 readonly onCloned: (input: {
66 readonly projectId: ProjectId;
67 readonly workspaceRoot: string;
68 }) => Effect.Effect<void>;
69}
70
71const DONE_RETENTION = "30 seconds";
72// Git prints nothing while a transfer waits on the network, and the kernel can
73// take 15+ minutes to give up on a dead connection. Without this the banner
74// keeps showing the last transfer speed as if data were still arriving.
75const STALL_AFTER = "20 seconds";
76
77function clampText(text: string, maxLength: number): string {
78 if (text.length <= maxLength) return text;
79 const end = splitsSurrogatePair(text, maxLength - 1) ? maxLength - 2 : maxLength - 1;
80 return `${text.slice(0, end)}…`;
81}
82
83const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
84
85interface TrackedClone {
86 readonly snapshot: ProjectCloneSnapshot;
87 readonly fiber: Fiber.Fiber<unknown, unknown> | null;
88 readonly hooks: ProjectCloneHooks;
89 readonly input: {
90 /** What git is given; may carry credentials and never leaves the server. */
91 readonly cloneUrl: string;
92 readonly destinationPath: string;
93 readonly repository: SourceControlRepositoryInfo | null;
94 readonly protocol: SourceControlCloneProtocol;
95 };
96}
97
98/** @public */
99export const make = Effect.gen(function* () {
100 const repositories = yield* SourceControlRepositoryService.SourceControlRepositoryService;
101 const clones = yield* Ref.make(new Map<ProjectId, TrackedClone>());
102 const changes = yield* PubSub.unbounded<ReadonlyArray<ProjectCloneSnapshot>>();
103 const retentionFibers = new Map<ProjectId, Fiber.Fiber<unknown, never>>();
104 let sequence = 0;
105 const cloneScope = yield* Scope.make("parallel");
106 yield* Effect.addFinalizer(() => Scope.close(cloneScope, Exit.void));
107 // Serialize actions on the shared entry and directory so retries cannot race clones.
108 const actionLock = yield* Semaphore.make(1);
109 const locked = <A, E, R>(effect: Effect.Effect<A, E, R>) => actionLock.withPermits(1)(effect);
110
111 const list = Ref.get(clones).pipe(
112 Effect.map((current) => Array.from(current.values(), (tracked) => tracked.snapshot)),
113 );
114 const publish = list.pipe(Effect.flatMap((snapshots) => PubSub.publish(changes, snapshots)));
115
116 const modify = (
117 projectId: ProjectId,
118 mutate: (tracked: TrackedClone) => TrackedClone,
119 ): Effect.Effect<ProjectCloneSnapshot | null> =>
120 Ref.modify(clones, (current) => {
121 const existing = current.get(projectId);
122 if (!existing) return [null, current] as const;
123 const nextTracked = mutate(existing);
124 const nextSnapshot = { ...nextTracked.snapshot, sequence: ++sequence };
125 const next = new Map(current);
126 next.set(projectId, { ...nextTracked, snapshot: nextSnapshot });
127 return [nextSnapshot, next] as const;
128 }).pipe(Effect.tap((snapshot) => (snapshot ? publish : Effect.void)));
129
130 const clearRetention = (projectId: ProjectId) => {
131 const fiber = retentionFibers.get(projectId);
132 retentionFibers.delete(projectId);
133 return fiber ? Fiber.interrupt(fiber).pipe(Effect.ignore) : Effect.void;
134 };
135
136 const remove = (projectId: ProjectId) =>
137 Ref.update(clones, (current) => {
138 if (!current.has(projectId)) return current;
139 const next = new Map(current);
140 next.delete(projectId);
141 return next;
142 }).pipe(Effect.andThen(publish));
143
144 const scheduleRemoval = Effect.fn("ProjectCloneTracker.scheduleRemoval")(function* (
145 projectId: ProjectId,
146 ) {
147 yield* clearRetention(projectId);
148 const fiber = yield* remove(projectId).pipe(
149 Effect.delay(DONE_RETENTION),
150 Effect.ensuring(
151 Effect.sync(() => {
152 if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId);
153 }),
154 ),
155 Effect.forkDetach,
156 );
157 retentionFibers.set(projectId, fiber);
158 });
159
160 const progress = (
161 projectId: ProjectId,
162 update: {
163 readonly stage: ProjectCloneStage;
164 readonly percent: number | null;
165 readonly detail: string | null;
166 },
167 ) =>
168 modify(projectId, (tracked) => ({
169 ...tracked,
170 snapshot: {
171 ...tracked.snapshot,
172 stage: update.stage,
173 percent: update.percent,
174 detail:
175 update.detail === null ? null : clampText(update.detail, PROJECT_CLONE_DETAIL_MAX_LENGTH),
176 stalled: false,
177 },
178 })).pipe(Effect.asVoid);
179
180 const markStalled = (projectId: ProjectId) =>
181 modify(projectId, (tracked) => ({
182 ...tracked,
183 snapshot: { ...tracked.snapshot, stalled: true },
184 })).pipe(Effect.asVoid);
185
186 /** Marks the clone stalled once, then waits for git to speak again. */
187 const watchForStall = (projectId: ProjectId, pulses: Queue.Dequeue<void>) =>
188 Queue.take(pulses).pipe(
189 Effect.timeoutOption(STALL_AFTER),
190 Effect.flatMap((pulse) =>
191 Option.isSome(pulse)
192 ? Effect.void
193 : markStalled(projectId).pipe(Effect.andThen(Queue.take(pulses))),
194 ),
195 Effect.forever,
196 );
197
198 const finish = Effect.fn("ProjectCloneTracker.finish")(function* (
199 projectId: ProjectId,
200 phase: "done" | "failed" | "cancelled",
201 error: string | null,
202 ) {
203 const endedAt = yield* nowIso;
204 yield* modify(projectId, (tracked) => ({
205 ...tracked,
206 fiber: null,
207 snapshot: {
208 ...tracked.snapshot,
209 phase,
210 endedAt,
211 percent: phase === "done" ? 100 : tracked.snapshot.percent,
212 stalled: false,
213 error: error === null ? null : clampText(error, PROJECT_CLONE_ERROR_MAX_LENGTH),
214 },
215 }));
216 if (phase === "done") yield* scheduleRemoval(projectId);
217 });
218
219 const cloneWatchingForStall = Effect.fn("ProjectCloneTracker.cloneWatchingForStall")(function* (
220 projectId: ProjectId,
221 tracked: TrackedClone,
222 ) {
223 const pulses = yield* Queue.sliding<void>(1);
224 yield* watchForStall(projectId, pulses).pipe(Effect.forkScoped);
225 return yield* repositories.cloneRepository(
226 {
227 remoteUrl: tracked.input.cloneUrl,
228 destinationPath: tracked.input.destinationPath,
229 protocol: tracked.input.protocol,
230 },
231 {
232 onProgress: (update) =>
233 Queue.offer(pulses, undefined).pipe(Effect.andThen(progress(projectId, update))),
234 timeoutMs: null,
235 },
236 );
237 }, Effect.scoped);
238
239 /**
240 * `onExit` records outcomes even on interruption; `matchCause` would be skipped.
241 * Mark the clone done before the post-clone hook so a late Cancel cannot remove it.
242 */
243 const runClone = (projectId: ProjectId, tracked: TrackedClone) =>
244 cloneWatchingForStall(projectId, tracked).pipe(
245 Effect.onExit((exit) =>
246 Exit.isSuccess(exit)
247 ? finish(projectId, "done", null)
248 : Cause.hasInterruptsOnly(exit.cause)
249 ? finish(projectId, "cancelled", null)
250 : finish(projectId, "failed", describeCloneFailure(exit.cause)),
251 ),
252 Effect.flatMap(() =>
253 tracked.hooks
254 .onCloned({ projectId, workspaceRoot: tracked.input.destinationPath })
255 .pipe(Effect.ignoreCause({ log: true })),
256 ),
257 Effect.ignoreCause(),
258 );
259
260 const launch = Effect.fn("ProjectCloneTracker.launch")(function* (projectId: ProjectId) {
261 const current = yield* Ref.get(clones);
262 const tracked = current.get(projectId);
263 if (!tracked) return;
264 const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope));
265 yield* Ref.update(clones, (map) => {
266 const existing = map.get(projectId);
267 if (!existing) return map;
268 const next = new Map(map);
269 next.set(projectId, { ...existing, fiber });
270 return next;
271 });
272 });
273
274 const moveClaim = (from: ProjectId, to: ProjectId) =>
275 Ref.modify(clones, (current) => {
276 const claim = current.get(from);
277 if (!claim || current.has(to)) return [false, current] as const;
278 const next = new Map(current);
279 next.delete(from);
280 next.set(to, { ...claim, snapshot: { ...claim.snapshot, projectId: to } });
281 return [true, next] as const;
282 });
283
284 const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")(
285 function* (input, hooks) {
286 const prepared = yield* repositories.prepareClone(input);
287 const startedAt = yield* nowIso;
288 const snapshot: ProjectCloneSnapshot = {
289 projectId: input.projectId,
290 remoteUrl: prepared.remoteUrl,
291 destinationPath: prepared.destinationPath,
292 repository: prepared.repository,
293 phase: "running",
294 stage: "connecting",
295 percent: null,
296 detail: null,
297 stalled: false,
298 error: null,
299 startedAt,
300 endedAt: null,
301 sequence: ++sequence,
302 };
303 const claim = yield* Ref.modify(clones, (current) => {
304 const overlapping = Array.from(current.values()).filter(
305 (tracked) =>
306 tracked.snapshot.projectId === input.projectId ||
307 tracked.input.destinationPath === prepared.destinationPath,
308 );
309 // Only a running clone owns its destination; a failed or cancelled one
310 // left nothing behind, so a fresh start supersedes it.
311 if (overlapping.some((tracked) => tracked.snapshot.phase === "running")) {
312 return [null, current] as const;
313 }
314 const next = new Map(current);
315 for (const stale of overlapping) next.delete(stale.snapshot.projectId);
316 next.set(input.projectId, {
317 snapshot,
318 fiber: null,
319 hooks,
320 input: {
321 cloneUrl: prepared.cloneUrl,
322 destinationPath: prepared.destinationPath,
323 repository: prepared.repository,
324 protocol: input.protocol ?? "auto",
325 },
326 });
327 return [overlapping.map((stale) => stale.snapshot.projectId), next] as const;
328 });
329 const alreadyInProgress = new SourceControlRepositoryError({
330 operation: "cloneRepository",
331 provider: input.provider ?? SourceControlProviderKind.make("unknown"),
332 detail: "A clone into this destination is already in progress.",
333 });
334 if (claim === null) return yield* alreadyInProgress;
335 // A superseded done entry's pending removal would otherwise delete the new claim.
336 yield* Effect.forEach(claim, clearRetention, { discard: true });
337 // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried.
338 const projectId = yield* Effect.uninterruptible(
339 Effect.gen(function* () {
340 yield* clearRetention(input.projectId);
341 // Register before creation so racing thread.create and project.delete see the clone.
342 const projectId = yield* hooks
343 .createProject({
344 projectId: input.projectId,
345 title: input.title,
346 workspaceRoot: prepared.destinationPath,
347 createdAt: input.createdAt,
348 })
349 .pipe(
350 Effect.as(input.projectId),
351 // A failed clone's project still owns its empty folder after a restart
352 // forgets the clone; clone for that project instead.
353 Effect.catchTags({
354 ProjectConflictError: (conflict) =>
355 moveClaim(input.projectId, conflict.conflictingProjectId).pipe(
356 Effect.flatMap((moved) =>
357 moved ? Effect.succeed(conflict.conflictingProjectId) : alreadyInProgress,
358 ),
359 ),
360 }),
361 );
362 yield* publish;
363 yield* launch(projectId);
364 return projectId;
365 }).pipe(Effect.tapError(() => remove(input.projectId))),
366 );
367 return {
368 projectId,
369 cwd: prepared.destinationPath,
370 remoteUrl: prepared.remoteUrl,
371 repository: prepared.repository,
372 };
373 },
374 );
375
376 const get: ProjectCloneTracker["Service"]["get"] = (projectId) =>
377 Ref.get(clones).pipe(Effect.map((current) => current.get(projectId)?.snapshot ?? null));
378
379 const cancel: ProjectCloneTracker["Service"]["cancel"] = Effect.fn("ProjectCloneTracker.cancel")(
380 function* (projectId) {
381 const current = yield* Ref.get(clones);
382 const tracked = current.get(projectId);
383 if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) return false;
384 // Finish cancellation despite disconnects to avoid dead fibers behind running snapshots.
385 yield* Effect.uninterruptible(
386 Effect.gen(function* () {
387 yield* Fiber.interrupt(tracked.fiber!);
388 const after = yield* get(projectId);
389 if (after?.phase === "done") return;
390 if (after?.phase === "running") yield* finish(projectId, "cancelled", null);
391 yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);
392 }),
393 );
394 return true;
395 },
396 );
397
398 const retry: ProjectCloneTracker["Service"]["retry"] = Effect.fn("ProjectCloneTracker.retry")(
399 function* (projectId) {
400 const current = yield* Ref.get(clones);
401 const tracked = current.get(projectId);
402 if (
403 !tracked ||
404 (tracked.snapshot.phase !== "failed" && tracked.snapshot.phase !== "cancelled")
405 ) {
406 return false;
407 }
408 yield* repositories.discardClone(tracked.input.destinationPath);
409 const startedAt = yield* nowIso;
410 yield* modify(projectId, (entry) => ({
411 ...entry,
412 snapshot: {
413 ...entry.snapshot,
414 phase: "running",
415 stage: "connecting",
416 percent: null,
417 detail: null,
418 stalled: false,
419 error: null,
420 startedAt,
421 endedAt: null,
422 },
423 }));
424 yield* launch(projectId);
425 return true;
426 },
427 );
428
429 const discard: ProjectCloneTracker["Service"]["discard"] = Effect.fn(
430 "ProjectCloneTracker.discard",
431 )(function* (projectId) {
432 const current = yield* Ref.get(clones);
433 const tracked = current.get(projectId);
434 if (!tracked) return;
435 if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber);
436 // Git may have finished while the interrupt was landing; the project
437 // is going away either way, but a complete checkout is the user's.
438 const after = yield* get(projectId);
439 if (after?.phase !== "done") {
440 yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);
441 }
442 yield* clearRetention(projectId);
443 yield* remove(projectId);
444 });
445
446 const stream: ProjectCloneTracker["Service"]["stream"] = Stream.callback<
447 ReadonlyArray<ProjectCloneSnapshot>
448 >(
449 (mailbox) =>
450 Effect.gen(function* () {
451 const subscription = yield* PubSub.subscribe(changes);
452 Queue.offerUnsafe(mailbox, yield* list);
453 yield* Stream.fromSubscription(subscription).pipe(
454 Stream.runForEach((snapshots) =>
455 Effect.sync(() => Queue.offerUnsafe(mailbox, snapshots)),
456 ),
457 Effect.forkScoped,
458 );
459 }),
460 { bufferSize: 1, strategy: "sliding" },
461 );
462
463 // Forwarders retain the underlying operation spans.
464 return ProjectCloneTracker.of({
465 start: Effect.fnUntraced(function* (input, hooks) {
466 return yield* locked(start(input, hooks));
467 }),
468 cancel: Effect.fnUntraced(function* (projectId) {
469 return yield* locked(cancel(projectId));
470 }),
471 retry: Effect.fnUntraced(function* (projectId) {
472 return yield* locked(retry(projectId));
473 }),
474 discard: Effect.fnUntraced(function* (projectId) {
475 return yield* locked(discard(projectId));
476 }),
477 get,
478 stream,
479 });
480});
481
482const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
483
484/**
485 * Every dispatch transport (WebSocket, HTTP) runs this before normalizing so no
486 * client can start a thread on an empty tree, and no attachment copies are made
487 * for a command that is about to be refused.
488 */
489export const rejectCommandsDuringClone = Effect.fn("ProjectCloneTracker.rejectCommandsDuringClone")(
490 function* (
491 tracker: ProjectCloneTracker["Service"],
492 command: {
493 readonly type: string;
494 readonly projectId?: ProjectId;
495 readonly bootstrap?: unknown;
496 },
497 ): Effect.fn.Return<void, OrchestrationDispatchCommandError> {
498 const projectId =
499 command.type === "thread.create"
500 ? (command.projectId ?? null)
501 : command.type === "thread.turn.start"
502 ? bootstrapProjectId(command.bootstrap)
503 : null;
504 if (projectId === null) return;
505 const clone = yield* tracker.get(projectId);
506 if (clone === null || clone.phase === "done") return;
507 return yield* new OrchestrationDispatchCommandError({
508 message:
509 clone.phase === "running"
510 ? "The repository is still being cloned."
511 : "The repository was not cloned. Retry the clone first.",
512 });
513 },
514);
515
516function bootstrapProjectId(bootstrap: unknown): ProjectId | null {
517 if (typeof bootstrap !== "object" || bootstrap === null) return null;
518 const createThread = (bootstrap as { createThread?: { projectId?: ProjectId } }).createThread;
519 return createThread?.projectId ?? null;
520}
521
522function describeCloneFailure(cause: Cause.Cause<unknown>): string {
523 const error = Cause.squash(cause);
524 if (isSourceControlRepositoryError(error)) return error.detail;
525 return error instanceof Error && error.message.trim().length > 0
526 ? error.message
527 : "The repository could not be cloned.";
528}
529
530export const layer = Layer.effect(ProjectCloneTracker, make);