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