Open History to see the last commit
1import { ProjectId, TaskFolder, TaskFolderError, TaskFolderRepository } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as SqlClient from "effect/sql/SqlClient";
10import * as SqlSchema from "effect/sql/SqlSchema";
11
12/**
13 * The record of each task folder. Reads live here so the services that only need to know where a
14 * thread works do not depend on Git; `TaskFolders` owns every change.
15 */
16export class TaskFolderStore extends Context.Service<
17 TaskFolderStore,
18 {
19 /** The task folder that is, or contains, `target`. */
20 readonly findContaining: (target: string) => Effect.Effect<TaskFolder | null, TaskFolderError>;
21 readonly list: Effect.Effect<ReadonlyArray<TaskFolder>, TaskFolderError>;
22 readonly put: (taskFolder: TaskFolder) => Effect.Effect<void, TaskFolderError>;
23 readonly remove: (root: string) => Effect.Effect<void, TaskFolderError>;
24 }
25>()("t3/workspace/TaskFolderStore") {}
26
27const TaskFolderRow = Schema.Struct({
28 root: Schema.String,
29 projectId: ProjectId,
30 projectRoot: Schema.String,
31 anchor: Schema.String,
32 projectPath: Schema.String,
33 projectIsWorktree: Schema.BooleanFromBit,
34 repositories: Schema.fromJsonString(Schema.Array(TaskFolderRepository)),
35});
36
37const make = Effect.gen(function* () {
38 const sql = yield* SqlClient.SqlClient;
39 const fileSystem = yield* FileSystem.FileSystem;
40 const path = yield* Path.Path;
41
42 const failed = (cause: unknown) =>
43 new TaskFolderError({ operation: "read", detail: "Could not read task folders.", cause });
44
45 // What Git and sandboxes resolve a path to: the nearest real ancestor plus what is missing.
46 const realLocation = (target: string): Effect.Effect<string> =>
47 fileSystem.realPath(target).pipe(
48 Effect.catch(() => {
49 const parent = path.dirname(target);
50 return parent === target
51 ? Effect.succeed(target)
52 : Effect.map(realLocation(parent), (real) => path.join(real, path.basename(target)));
53 }),
54 );
55
56 const ancestors = (target: string) => {
57 const result = [target];
58 for (let parent = path.dirname(target); parent !== result.at(-1); parent = path.dirname(parent))
59 result.push(parent);
60 return result;
61 };
62
63 const selectColumns = sql`
64 root,
65 project_id AS "projectId",
66 project_root AS "projectRoot",
67 anchor,
68 project_path AS "projectPath",
69 project_is_worktree AS "projectIsWorktree",
70 repositories_json AS "repositories"
71 `;
72
73 // Both spellings on both sides: a worktrees directory reached through a symlink is stored as
74 // named and as resolved, and a caller may hold either.
75 const findRows = SqlSchema.findAll({
76 Request: Schema.Array(Schema.String),
77 Result: TaskFolderRow,
78 execute: (candidates) => sql`
79 SELECT ${selectColumns} FROM task_folders
80 WHERE ${sql.in("root", candidates)} OR ${sql.in("real_root", candidates)}
81 ORDER BY length(root) DESC
82 LIMIT 1
83 `,
84 });
85
86 const listRows = SqlSchema.findAll({
87 Request: Schema.Void,
88 Result: TaskFolderRow,
89 execute: () => sql`SELECT ${selectColumns} FROM task_folders ORDER BY root`,
90 });
91
92 const encodeRepositories = Schema.encodeEffect(
93 Schema.fromJsonString(Schema.Array(TaskFolderRepository)),
94 );
95
96 const findContaining: TaskFolderStore["Service"]["findContaining"] = Effect.fn(
97 "TaskFolderStore.findContaining",
98 )(function* (target) {
99 if (!path.isAbsolute(target)) return null;
100 const named = path.resolve(target);
101 const candidates = [
102 ...new Set([...ancestors(named), ...ancestors(yield* realLocation(named))]),
103 ];
104 const rows = yield* findRows(candidates).pipe(Effect.mapError(failed));
105 return rows[0] ?? null;
106 });
107
108 const put: TaskFolderStore["Service"]["put"] = Effect.fn("TaskFolderStore.put")(function* (
109 taskFolder,
110 ) {
111 const repositories = yield* encodeRepositories(taskFolder.repositories);
112 const realRoot = yield* realLocation(taskFolder.root);
113 const createdAt = DateTime.formatIso(yield* DateTime.now);
114 yield* sql`
115 INSERT INTO task_folders (
116 root, real_root, project_id, project_root, anchor, project_path,
117 project_is_worktree, repositories_json, created_at
118 ) VALUES (
119 ${taskFolder.root}, ${realRoot}, ${taskFolder.projectId}, ${taskFolder.projectRoot},
120 ${taskFolder.anchor}, ${taskFolder.projectPath},
121 ${taskFolder.projectIsWorktree ? 1 : 0}, ${repositories}, ${createdAt}
122 )
123 ON CONFLICT (root) DO UPDATE SET
124 real_root = excluded.real_root,
125 project_path = excluded.project_path,
126 project_is_worktree = excluded.project_is_worktree,
127 repositories_json = excluded.repositories_json
128 `;
129 }, Effect.mapError(failed));
130
131 return TaskFolderStore.of({
132 findContaining,
133 list: listRows(undefined).pipe(Effect.mapError(failed)),
134 put,
135 remove: Effect.fn("TaskFolderStore.remove")(function* (root) {
136 yield* sql`DELETE FROM task_folders WHERE root = ${root}`.pipe(Effect.mapError(failed));
137 }),
138 });
139});
140
141export const layer = Layer.effect(TaskFolderStore, make);