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

ManagedProjectFolders.ts

488 lines16.6 KB

1import {
2 CommandId,
3 type GitManagerServiceError,
4 ProjectId,
5 type ThreadId,
6 VcsProcessSpawnError,
7} from "@t3tools/contracts";
8import { newProjectFolderName } from "@t3tools/shared/path";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as PlatformError from "effect/PlatformError";
21import * as Schema from "effect/Schema";
22​
23import * as ServerConfig from "../config.ts";
24import * as GitWorkflow from "../git/GitWorkflowService.ts";
25import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
26import * as ProjectService from "./ProjectService.ts";
27​
28export class ScratchUnavailableError extends Schema.TaggedError<ScratchUnavailableError>()(
29 "ScratchUnavailableError",
30 {},
31) {
32 override get message(): string {
33 return "Threads without a project are not available on this environment.";
34 }
36​
37export class ScratchFolderError extends Schema.TaggedError<ScratchFolderError>()(
38 "ScratchFolderError",
39 {
40 folder: Schema.String,
41 cause: Schema.Defect(),
42 },
43) {
44 override get message(): string {
45 return "Failed to create the folder for threads without a project.";
46 }
48​
49export class ScratchProjectError extends Schema.TaggedError<ScratchProjectError>()(
50 "ScratchProjectError",
51 {
52 workspaceRoot: Schema.String,
53 cause: Schema.Defect(),
54 },
55) {
56 override get message(): string {
57 return "Failed to create the project for threads without a project.";
58 }
60​
61export type ScratchError = ScratchUnavailableError | ScratchFolderError | ScratchProjectError;
62​
63export class NamedProjectFolderError extends Schema.TaggedError<NamedProjectFolderError>()(
64 "NamedProjectFolderError",
65 {
66 folder: Schema.String,
67 cause: Schema.Defect(),
68 },
69) {
70 override get message(): string {
71 return "Failed to create the project folder.";
72 }
74​
75export class NamedProjectCreateError extends Schema.TaggedError<NamedProjectCreateError>()(
76 "NamedProjectCreateError",
77 {
78 workspaceRoot: Schema.String,
79 cause: Schema.Defect(),
80 },
81) {
82 override get message(): string {
83 return "Failed to create the project.";
84 }
86​
87export type NamedProjectError = NamedProjectFolderError | NamedProjectCreateError;
88​
89export class ManagedProjectFolders extends Context.Service<
90 ManagedProjectFolders,
91 {
92 readonly scratchRoot: Effect.Effect<Option.Option<string>>;
93 readonly ensureScratchProject: Effect.Effect<{ readonly projectId: ProjectId }, ScratchError>;
94 readonly isScratchProject: (projectId: ProjectId) => Effect.Effect<boolean>;
95 readonly folderForThread: (input: {
96 readonly projectId: ProjectId;
97 readonly threadId: ThreadId;
98 readonly text: string;
99 }) => Effect.Effect<Option.Option<string>, ScratchFolderError>;
100 readonly namedProjectsRoot: string;
101 /**
102 * The folder is removed when the create fails or is cancelled before the
103 * project exists, never once another project owns it.
104 */
105 readonly createNamedProject: (input: { readonly name: string }) => Effect.Effect<
106 {
107 readonly projectId: ProjectId;
108 readonly workspaceRoot: string;
109 readonly commitError?: string;
110 },
111 NamedProjectError
112 >;
113 }
114>()("t3/project/ManagedProjectFolders") {}
115​
116const folderWords = (text: string) =>
117 text
118 .toLowerCase()
119 .split(/[^a-z0-9]+/)
120 .filter(Boolean)
121 .slice(0, 5)
122 .join("-")
123 .slice(0, 48)
124 .replace(/-+$/, "");
125​
126const ICON_BACKGROUNDS = [
127 "#dc2626",
128 "#ea580c",
129 "#d97706",
130 "#16a34a",
131 "#059669",
132 "#0d9488",
133 "#0891b2",
134 "#0284c7",
135 "#2563eb",
136 "#4f46e5",
137 "#7c3aed",
138 "#9333ea",
139 "#c026d3",
140 "#db2777",
141 "#e11d48",
142] as const;
143​
144const MAX_NAMED_FOLDER_ATTEMPTS = 100;
145​
146function escapeXml(value: string): string {
147 return value
148 .replaceAll("&", "&amp;")
149 .replaceAll("<", "&lt;")
150 .replaceAll(">", "&gt;")
151 .replaceAll('"', "&quot;");
153​
154/**
155 * It lives at `assets/icon.svg`, a path ProjectFaviconResolver already checks,
156 * so every machine that clones the project shows the same icon.
157 */
158function namedProjectIconSvg(name: string): string {
159 const words = name.split(/[^\p{L}\p{N}]+/u).filter(Boolean);
160 const initials =
161 words
162 .slice(0, 2)
163 .map((word) => Array.from(word)[0] ?? "")
164 .join("")
165 .toUpperCase() ||
166 Array.from(name.trim())[0] ||
167 "?";
168 let hash = 0;
169 for (const char of name) hash = (hash * 31 + (char.codePointAt(0) ?? 0)) >>> 0;
170 const background = ICON_BACKGROUNDS[hash % ICON_BACKGROUNDS.length];
171 return [
172 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">`,
173 ` <rect width="64" height="64" rx="14" fill="${background}"/>`,
174 ` <text x="32" y="32" dy="0.35em" text-anchor="middle" font-family="ui-sans-serif, system-ui, -apple-system, sans-serif" font-size="${initials.length > 1 ? 26 : 32}" font-weight="600" fill="#ffffff">${escapeXml(initials)}</text>`,
175 `</svg>`,
176 "",
177 ].join("\n");
179​
180function namedProjectReadme(name: string): string {
181 return [
182 `<img src="assets/icon.svg" width="64" height="64" alt="">`,
183 "",
184 `# ${name}`,
185 "",
186 "Created in [T3 Code](https://t3.codes).",
187 "",
188 ].join("\n");
190​
191function describeCommitFailure(stderr: string): string {
192 if (/identity unknown|tell me who you are|no (name|email) was given/i.test(stderr)) {
193 return "Git has no name or email on this machine. Set user.name and user.email, then commit.";
194 }
195 const lines = stderr
196 .split("\n")
197 .map((line) => line.trim())
198 .filter(Boolean);
199 return lines.at(-1) ?? "Git could not make the first commit.";
201​
202const isVcsProcessSpawnError = Schema.is(VcsProcessSpawnError);
203​
204// Spawning a `git` that is not on PATH fails with NotFound, on Windows too.
205const isGitMissing = (error: GitManagerServiceError) =>
206 error._tag === "GitManagerError" &&
207 isVcsProcessSpawnError(error.cause) &&
208 PlatformError.isPlatformError(error.cause.cause) &&
209 error.cause.cause.reason._tag === "NotFound";
210​
211const make = Effect.gen(function* () {
212 const config = yield* ServerConfig.ServerConfig;
213 const fileSystem = yield* FileSystem.FileSystem;
214 const path = yield* Path.Path;
215 const gitWorkflow = yield* GitWorkflow.GitWorkflowService;
216 const git = yield* GitVcsDriver.GitVcsDriver;
217 const projects = yield* ProjectService.ProjectService;
218 const crypto = yield* Crypto.Crypto;
219​
220 /**
221 * Each folder is created without `recursive`, so creating it is the claim: of
222 * two racers for one name, one gets AlreadyExists and moves on to the next.
223 */
224 const claimFreeFolder = Effect.fnUntraced(function* <E>(
225 folderFor: (attempt: number) => Effect.Effect<Option.Option<string>, E>,
226 onError: (folder: string, cause: PlatformError.PlatformError) => E,
227 ) {
228 for (let attempt = 1; ; attempt++) {
229 const folder = yield* folderFor(attempt);
230 if (Option.isNone(folder)) return folder;
231 const claimed = yield* fileSystem.makeDirectory(folder.value).pipe(
232 Effect.as(true),
233 Effect.catchIf(
234 (error) => error.reason._tag === "AlreadyExists",
235 () => Effect.succeed(false),
236 ),
237 Effect.mapError((cause) => onError(folder.value, cause)),
238 );
239 if (claimed) return folder;
240 }
241 });
242​
243 // Inside a checkout (a dev worktree's .t3, a dotfiles home) the folder would
244 // inherit the repo's git status and checkpoints, so Scratch is offered only
245 // when the data dir is outside any work tree.
246 const [probe, invalidate] = yield* Effect.cachedInvalidateWithTTL(
247 gitWorkflow.isRepository(config.baseDir).pipe(
248 Effect.catchIf(isGitMissing, () => Effect.succeed(false)),
249 Effect.map((isRepository) =>
250 isRepository ? Option.none<string>() : Option.some(path.resolve(config.baseDir, "scratch")),
251 ),
252 Effect.catchCause((cause) =>
253 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Option.none<string>()),
254 ),
255 ),
256 Duration.infinity,
257 );
258 const scratchRoot = probe.pipe(Effect.onInterrupt(() => invalidate));
259​
260 const makeScratchFolder = (folder: string) =>
261 fileSystem
262 .makeDirectory(folder, { recursive: true })
263 .pipe(Effect.mapError((cause) => new ScratchFolderError({ folder, cause })));
264​
265 const ensureScratchProject: ManagedProjectFolders["Service"]["ensureScratchProject"] = Effect.gen(
266 function* () {
267 const workspaceRoot = yield* scratchRoot.pipe(
268 Effect.flatMap(
269 Option.match({
270 onNone: () => Effect.fail(new ScratchUnavailableError()),
271 onSome: Effect.succeed,
272 }),
273 ),
274 );
275 yield* makeScratchFolder(workspaceRoot);
276 const id = yield* crypto
277 .randomUUIDv4()
278 .pipe(Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })));
279 const bootstrapped = yield* projects
280 .bootstrap({
281 commandId: CommandId.make(`scratch-project:${id}`),
282 projectId: ProjectId.make(id),
283 title: "No project",
284 workspaceRoot,
285 })
286 .pipe(
287 // bootstrap looks the root up before taking the workspace lock, so a
288 // racing create loses with a conflict that names the winner.
289 Effect.catchTags({
290 ProjectConflictError: (conflict) =>
291 Effect.succeed({
292 project: { id: conflict.conflictingProjectId },
293 created: false,
294 }),
295 }),
296 Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })),
297 );
298 if (bootstrapped.created) {
299 // Set once at create, so a user's own icon choice is never overwritten.
300 yield* projects
301 .update({
302 commandId: CommandId.make(`scratch-project-icon:${id}`),
303 projectId: bootstrapped.project.id,
304 projectIcon: { kind: "lucide", name: "message-square-dashed", color: "gray" },
305 })
306 .pipe(Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })));
307 }
308 return { projectId: bootstrapped.project.id };
309 },
310 );
311​
312 const isScratchRoot = (projectId: ProjectId, root: string) =>
313 projects.getById(projectId).pipe(
314 Effect.map(
315 Option.exists((project) => path.resolve(project.workspaceRoot) === path.resolve(root)),
316 ),
317 Effect.orElseSucceed(() => false),
318 );
319​
320 const isScratchProject: ManagedProjectFolders["Service"]["isScratchProject"] = (projectId) =>
321 scratchRoot.pipe(
322 Effect.flatMap(
323 Option.match({
324 onNone: () => Effect.succeed(false),
325 onSome: (root) => isScratchRoot(projectId, root),
326 }),
327 ),
328 );
329​
330 const folderForThread: ManagedProjectFolders["Service"]["folderForThread"] = Effect.fn(
331 "ManagedProjectFolders.folderForThread",
332 )(function* (input) {
333 const root = yield* scratchRoot;
334 if (Option.isNone(root)) return Option.none();
335 if (!(yield* isScratchRoot(input.projectId, root.value))) return Option.none();
336 const date = DateTime.formatIso(yield* DateTime.now).slice(0, 10);
337 const words = folderWords(input.text);
338 const id = input.threadId.toLowerCase().replace(/[^a-z0-9]/g, "");
339 const folderFor = (idPart: string) =>
340 path.join(root.value, [date, words, idPart].filter(Boolean).join("-"));
341 yield* makeScratchFolder(root.value);
342 const fullFolder = folderFor(id);
343 return yield* claimFreeFolder(
344 (attempt) =>
345 attempt === 1
346 ? Effect.succeed(Option.some(folderFor(id.slice(-8))))
347 : attempt === 2
348 ? Effect.succeed(Option.some(fullFolder))
349 : crypto.randomUUIDv4().pipe(
350 Effect.map((uuid) => Option.some(`${fullFolder}-${uuid.slice(0, 8)}`)),
351 Effect.mapError((cause) => new ScratchFolderError({ folder: fullFolder, cause })),
352 ),
353 (folder, cause) => new ScratchFolderError({ folder, cause }),
354 );
355 });
356​
357 const namedProjectsRoot = path.resolve(config.baseDir, "projects");
358​
359 const claimNamedFolder = Effect.fn("ManagedProjectFolders.claimNamedFolder")(function* (
360 name: string,
361 ) {
362 yield* fileSystem
363 .makeDirectory(namedProjectsRoot, { recursive: true })
364 .pipe(
365 Effect.mapError(
366 (cause) => new NamedProjectFolderError({ folder: namedProjectsRoot, cause }),
367 ),
368 );
369 const folderName = newProjectFolderName(name);
370 const claimed = yield* claimFreeFolder(
371 (attempt) =>
372 Effect.succeed(
373 attempt > MAX_NAMED_FOLDER_ATTEMPTS
374 ? Option.none()
375 : Option.some(
376 path.join(
377 namedProjectsRoot,
378 attempt === 1 ? folderName : `${folderName}-${attempt}`,
379 ),
380 ),
381 ),
382 (folder, cause) => new NamedProjectFolderError({ folder, cause }),
383 );
384 if (Option.isSome(claimed)) return claimed.value;
385 return yield* new NamedProjectFolderError({
386 folder: path.join(namedProjectsRoot, folderName),
387 cause: `Every folder name for "${folderName}" is taken.`,
388 });
389 });
390​
391 const scaffoldRepository = Effect.fn("ManagedProjectFolders.scaffoldRepository")(function* (
392 cwd: string,
393 name: string,
394 ) {
395 const branch =
396 (yield* git
397 .readConfigValue(cwd, "init.defaultBranch")
398 .pipe(Effect.orElseSucceed(() => null))) ?? "main";
399 yield* git.execute({
400 operation: "ManagedProjectFolders.init",
401 cwd,
402 args: ["init", `--initial-branch=${branch}`],
403 timeoutMs: 10_000,
404 });
405 yield* fileSystem.writeFileString(path.join(cwd, "README.md"), namedProjectReadme(name));
406 yield* fileSystem.makeDirectory(path.join(cwd, "assets"));
407 yield* fileSystem.writeFileString(
408 path.join(cwd, "assets", "icon.svg"),
409 namedProjectIconSvg(name),
410 );
411 // Named and forced so a global ignore rule (say `*.svg`) cannot drop one.
412 yield* git.execute({
413 operation: "ManagedProjectFolders.add",
414 cwd,
415 args: ["add", "--force", "--", "README.md", "assets/icon.svg"],
416 timeoutMs: 10_000,
417 });
418 return yield* git
419 .execute({
420 operation: "ManagedProjectFolders.commit",
421 cwd,
422 args: ["commit", "--message", "Initial commit"],
423 allowNonZeroExit: true,
424 timeoutMs: 30_000,
425 })
426 .pipe(
427 Effect.map((result) =>
428 result.exitCode === 0 ? undefined : describeCommitFailure(result.stderr),
429 ),
430 Effect.catch((error) => Effect.succeed(error.message)),
431 );
432 });
433​
434 const createNamedProject: ManagedProjectFolders["Service"]["createNamedProject"] = Effect.fn(
435 "ManagedProjectFolders.createNamedProject",
436 )(function* (input) {
437 const workspaceRoot = yield* claimNamedFolder(input.name);
438 const removeFolder = fileSystem.remove(workspaceRoot, { recursive: true }).pipe(Effect.ignore);
439 const prepared = yield* Effect.all([
440 scaffoldRepository(workspaceRoot, input.name).pipe(
441 Effect.mapError((cause) => new NamedProjectFolderError({ folder: workspaceRoot, cause })),
442 ),
443 crypto
444 .randomUUIDv4()
445 .pipe(Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause }))),
446 ]).pipe(Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : removeFolder)));
447 const [commitError, id] = prepared;
448 const project = yield* projects
449 .create({
450 commandId: CommandId.make(`named-project:${id}`),
451 projectId: ProjectId.make(id),
452 title: input.name,
453 workspaceRoot,
454 })
455 .pipe(
456 // A rejected create leaves the folder unused, so remove it. An
457 // interrupt can land after the create is committed, and a conflict
458 // means another project owns the folder, so it stays then; the owner
459 // is checked again first, since deleting another project's files is
460 // never acceptable.
461 Effect.tapError((error) =>
462 error._tag === "ProjectConflictError"
463 ? Effect.void
464 : projects.getByWorkspaceRoot(workspaceRoot).pipe(
465 Effect.flatMap((owner) => (Option.isNone(owner) ? removeFolder : Effect.void)),
466 Effect.ignore,
467 ),
468 ),
469 Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause })),
470 );
471 return {
472 projectId: project.id,
473 workspaceRoot,
474 ...(commitError === undefined ? {} : { commitError }),
475 };
476 });
477​
478 return ManagedProjectFolders.of({
479 scratchRoot,
480 ensureScratchProject,
481 isScratchProject,
482 folderForThread,
483 namedProjectsRoot,
484 createNamedProject,
485 });
486});
487​
488export const layer = Layer.effect(ManagedProjectFolders, make);