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