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

ManagedProjectFolders.ts

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