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