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