Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectCloneTracker.ts

451 lines16.4 KB

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>;
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)}…`;
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 };
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 = Effect.fn("ProjectCloneTracker.scheduleRemoval")(function* (
137 projectId: ProjectId,
138 ) {
139 yield* clearRetention(projectId);
140 const fiber = yield* remove(projectId).pipe(
141 Effect.delay(DONE_RETENTION),
142 Effect.ensuring(
143 Effect.sync(() => {
144 if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId);
145 }),
146 ),
147 Effect.forkDetach,
148 );
149 retentionFibers.set(projectId, fiber);
150 });
151​
152 const progress = (
153 projectId: ProjectId,
154 update: {
155 readonly stage: ProjectCloneStage;
156 readonly percent: number | null;
157 readonly detail: string | null;
158 },
159 ) =>
160 modify(projectId, (tracked) => ({
161 ...tracked,
162 snapshot: {
163 ...tracked.snapshot,
164 stage: update.stage,
165 percent: update.percent,
166 detail:
167 update.detail === null ? null : clampText(update.detail, PROJECT_CLONE_DETAIL_MAX_LENGTH),
168 },
169 })).pipe(Effect.asVoid);
170​
171 const finish = Effect.fn("ProjectCloneTracker.finish")(function* (
172 projectId: ProjectId,
173 phase: "done" | "failed" | "cancelled",
174 error: string | null,
175 ) {
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 = Effect.fn("ProjectCloneTracker.launch")(function* (projectId: ProjectId) {
221 const current = yield* Ref.get(clones);
222 const tracked = current.get(projectId);
223 if (!tracked) return;
224 const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope));
225 yield* Ref.update(clones, (map) => {
226 const existing = map.get(projectId);
227 if (!existing) return map;
228 const next = new Map(map);
229 next.set(projectId, { ...existing, fiber });
230 return next;
231 });
232 });
233​
234 const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")(
235 function* (input, hooks) {
236 const prepared = yield* repositories.prepareClone(input);
237 const startedAt = yield* nowIso;
238 const snapshot: ProjectCloneSnapshot = {
239 projectId: input.projectId,
240 remoteUrl: prepared.remoteUrl,
241 destinationPath: prepared.destinationPath,
242 repository: prepared.repository,
243 phase: "running",
244 stage: "connecting",
245 percent: null,
246 detail: null,
247 error: null,
248 startedAt,
249 endedAt: null,
250 sequence: ++sequence,
251 };
252 const claimed = yield* Ref.modify(clones, (current) => {
253 const conflict = Array.from(current.values()).some(
254 (tracked) =>
255 tracked.snapshot.projectId === input.projectId ||
256 tracked.input.destinationPath === prepared.destinationPath,
257 );
258 if (conflict) return [false, current] as const;
259 const next = new Map(current);
260 next.set(input.projectId, {
261 snapshot,
262 fiber: null,
263 hooks,
264 input: {
265 cloneUrl: prepared.cloneUrl,
266 destinationPath: prepared.destinationPath,
267 repository: prepared.repository,
268 },
269 });
270 return [true, next] as const;
271 });
272 if (!claimed) {
273 return yield* new SourceControlRepositoryError({
274 operation: "cloneRepository",
275 provider: input.provider ?? SourceControlProviderKind.make("unknown"),
276 detail: "A clone into this destination is already in progress.",
277 });
278 }
279 // Everything after the claim runs to completion even if the requesting
280 // connection drops: a claimed entry with no fiber could neither be
281 // cancelled nor retried. Any failure in here releases the claim.
282 yield* Effect.uninterruptible(
283 Effect.gen(function* () {
284 yield* clearRetention(input.projectId);
285 // The entry is registered before the project exists so a
286 // thread.create or project.delete racing this call already sees it.
287 yield* hooks.createProject({
288 projectId: input.projectId,
289 title: input.title,
290 workspaceRoot: prepared.destinationPath,
291 createdAt: input.createdAt,
292 });
293 yield* publish;
294 yield* launch(input.projectId);
295 }).pipe(Effect.tapError(() => remove(input.projectId))),
296 );
297 return {
298 projectId: input.projectId,
299 cwd: prepared.destinationPath,
300 remoteUrl: prepared.remoteUrl,
301 repository: prepared.repository,
302 };
303 },
304 );
305​
306 const get: ProjectCloneTracker["Service"]["get"] = (projectId) =>
307 Ref.get(clones).pipe(Effect.map((current) => current.get(projectId)?.snapshot ?? null));
308​
309 const cancel: ProjectCloneTracker["Service"]["cancel"] = Effect.fn("ProjectCloneTracker.cancel")(
310 function* (projectId) {
311 const current = yield* Ref.get(clones);
312 const tracked = current.get(projectId);
313 if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) return false;
314 // Uninterruptible past this point: a client that disconnects mid-cancel
315 // must not leave a dead fiber behind a "running" snapshot.
316 yield* Effect.uninterruptible(
317 Effect.gen(function* () {
318 yield* Fiber.interrupt(tracked.fiber!);
319 const after = yield* get(projectId);
320 if (after?.phase === "done") return;
321 if (after?.phase === "running") yield* finish(projectId, "cancelled", null);
322 yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);
323 }),
324 );
325 return true;
326 },
327 );
328​
329 const retry: ProjectCloneTracker["Service"]["retry"] = Effect.fn("ProjectCloneTracker.retry")(
330 function* (projectId) {
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​
359 const discard: ProjectCloneTracker["Service"]["discard"] = Effect.fn(
360 "ProjectCloneTracker.discard",
361 )(function* (projectId) {
362 const current = yield* Ref.get(clones);
363 const tracked = current.get(projectId);
364 if (!tracked) return;
365 if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber);
366 // Git may have finished while the interrupt was landing; the project
367 // is going away either way, but a complete checkout is the user's.
368 const after = yield* get(projectId);
369 if (after?.phase !== "done") {
370 yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);
371 }
372 yield* clearRetention(projectId);
373 yield* remove(projectId);
374 });
375​
376 const stream: ProjectCloneTracker["Service"]["stream"] = Stream.callback<
377 ReadonlyArray<ProjectCloneSnapshot>
378 >(
379 (mailbox) =>
380 Effect.gen(function* () {
381 const subscription = yield* PubSub.subscribe(changes);
382 Queue.offerUnsafe(mailbox, yield* list);
383 yield* Stream.fromSubscription(subscription).pipe(
384 Stream.runForEach((snapshots) =>
385 Effect.sync(() => Queue.offerUnsafe(mailbox, snapshots)),
386 ),
387 Effect.forkScoped,
388 );
389 }),
390 { bufferSize: 1, strategy: "sliding" },
391 );
392​
393 return ProjectCloneTracker.of({
394 start: (input, hooks) => locked(start(input, hooks)),
395 cancel: (projectId) => locked(cancel(projectId)),
396 retry: (projectId) => locked(retry(projectId)),
397 discard: (projectId) => locked(discard(projectId)),
398 get,
399 stream,
400 });
401});
402​
403const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
404​
405/**
406 * Every dispatch transport (WebSocket, HTTP) runs this before normalizing so no
407 * client can start a thread on an empty tree, and no attachment copies are made
408 * for a command that is about to be refused.
409 */
410export const rejectCommandsDuringClone = Effect.fn("ProjectCloneTracker.rejectCommandsDuringClone")(
411 function* (
412 tracker: ProjectCloneTracker["Service"],
413 command: {
414 readonly type: string;
415 readonly projectId?: ProjectId;
416 readonly bootstrap?: unknown;
417 },
418 ): Effect.fn.Return<void, OrchestrationDispatchCommandError> {
419 const projectId =
420 command.type === "thread.create"
421 ? (command.projectId ?? null)
422 : command.type === "thread.turn.start"
423 ? bootstrapProjectId(command.bootstrap)
424 : null;
425 if (projectId === null) return;
426 const clone = yield* tracker.get(projectId);
427 if (clone === null || clone.phase === "done") return;
428 return yield* new OrchestrationDispatchCommandError({
429 message:
430 clone.phase === "running"
431 ? "The repository is still being cloned."
432 : "The repository was not cloned. Retry the clone first.",
433 });
434 },
435);
436​
437function bootstrapProjectId(bootstrap: unknown): ProjectId | null {
438 if (typeof bootstrap !== "object" || bootstrap === null) return null;
439 const createThread = (bootstrap as { createThread?: { projectId?: ProjectId } }).createThread;
440 return createThread?.projectId ?? null;
442​
443function describeCloneFailure(cause: Cause.Cause<unknown>): string {
444 const error = Cause.squash(cause);
445 if (isSourceControlRepositoryError(error)) return error.detail;
446 return error instanceof Error && error.message.trim().length > 0
447 ? error.message
448 : "The repository could not be cloned.";
450​
451export const layer = Layer.effect(ProjectCloneTracker, make);