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