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

ProjectService.ts

495 lines17.3 KB

1import {
2 CommandId,
3 ProjectId,
4 type Project,
5 type ProjectCreatePayload,
6 type ProjectUpdatePayload,
7 type ProjectSnapshot,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Schema from "effect/Schema";
15​
16import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
17import { EventSinkV2 } from "../orchestration-v2/EventSink.ts";
18import { IdAllocatorV2 } from "../orchestration-v2/IdAllocator.ts";
19import { LegacyV1ThreadImporter } from "../orchestration-v2/LegacyV1ThreadImporter.ts";
20import { ProjectionStoreV2 } from "../orchestration-v2/ProjectionStore.ts";
21import {
22 ThreadCommandExecutor,
23 layer as threadCommandExecutorLayer,
24} from "../orchestration-v2/ThreadCommandExecutor.ts";
25import { planThreadDeletion } from "../orchestration-v2/ThreadDeletion.ts";
26import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts";
27import { ProjectEnrichmentService, type ProjectEnrichment } from "./ProjectEnrichmentService.ts";
28import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
29​
30export interface ProjectCreateInput extends ProjectCreatePayload {
31 readonly commandId: CommandId;
32 readonly projectId: ProjectId;
34​
35export interface ProjectUpdateInput extends ProjectUpdatePayload {
36 readonly commandId: CommandId;
37 readonly projectId: ProjectId;
39​
40export interface ProjectBootstrapInput extends ProjectCreateInput {}
41​
42export interface ProjectDeleteInput {
43 readonly commandId: CommandId;
44 readonly projectId: ProjectId;
45 readonly force?: boolean;
47​
48export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
49 "ProjectNotFoundError",
50 { projectId: ProjectId },
51) {
52 override get message(): string {
53 return `Project ${this.projectId} was not found.`;
54 }
56​
57export class ProjectConflictError extends Schema.TaggedError<ProjectConflictError>()(
58 "ProjectConflictError",
59 {
60 projectId: ProjectId,
61 workspaceRoot: Schema.String,
62 conflictingProjectId: ProjectId,
63 },
64) {
65 override get message(): string {
66 return `Workspace ${this.workspaceRoot} already belongs to project ${this.conflictingProjectId}.`;
67 }
69​
70export class ProjectNotEmptyError extends Schema.TaggedError<ProjectNotEmptyError>()(
71 "ProjectNotEmptyError",
72 { projectId: ProjectId },
73) {
74 override get message(): string {
75 return `Project ${this.projectId} is not empty.`;
76 }
78​
79export class ProjectOperationError extends Schema.TaggedError<ProjectOperationError>()(
80 "ProjectOperationError",
81 {
82 operation: Schema.Literals([
83 "normalize-workspace",
84 "read-project",
85 "list-projects",
86 "list-threads",
87 "delete-thread",
88 "dispatch-project-command",
89 ]),
90 projectId: Schema.optional(ProjectId),
91 workspaceRoot: Schema.optional(Schema.String),
92 cause: Schema.Defect(),
93 },
94) {
95 override get message(): string {
96 return `Project operation '${this.operation}' failed${this.projectId === undefined ? "" : ` for ${this.projectId}`}.`;
97 }
99​
100export type ProjectServiceError =
101 | ProjectNotFoundError
102 | ProjectConflictError
103 | ProjectNotEmptyError
104 | ProjectOperationError;
105​
106export class ProjectService extends Context.Service<
107 ProjectService,
108 {
109 readonly create: (input: ProjectCreateInput) => Effect.Effect<Project, ProjectServiceError>;
110 readonly bootstrap: (
111 input: ProjectBootstrapInput,
112 ) => Effect.Effect<
113 { readonly project: Project; readonly created: boolean },
114 ProjectServiceError
115 >;
116 readonly update: (input: ProjectUpdateInput) => Effect.Effect<Project, ProjectServiceError>;
117 readonly delete: (input: ProjectDeleteInput) => Effect.Effect<Project, ProjectServiceError>;
118 readonly getById: (
119 projectId: ProjectId,
120 options?: { readonly includeDeleted?: boolean },
121 ) => Effect.Effect<Option.Option<Project>, ProjectOperationError>;
122 readonly getByWorkspaceRoot: (
123 workspaceRoot: string,
124 options?: { readonly includeDeleted?: boolean },
125 ) => Effect.Effect<Option.Option<Project>, ProjectOperationError>;
126 readonly snapshot: Effect.Effect<ProjectSnapshot, ProjectOperationError>;
127 }
128>()("t3/project/ProjectService") {}
129​
130export const make = Effect.gen(function* () {
131 const engine = yield* OrchestrationEngineService;
132 const projects = yield* ProjectionProjects.ProjectionProjectRepository;
133 const projectEnrichment = yield* ProjectEnrichmentService;
134 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
135 const threadProjections = yield* ProjectionStoreV2;
136 const threadEvents = yield* EventSinkV2;
137 const idAllocator = yield* IdAllocatorV2;
138 const legacyImporter = yield* LegacyV1ThreadImporter;
139 const threadCommands = yield* ThreadCommandExecutor;
140​
141 const toProject = (
142 row: ProjectionProjects.ProjectionProject,
143 enrichment: ProjectEnrichment | null,
144 ): Project => ({
145 id: row.projectId,
146 title: row.title,
147 workspaceRoot: row.workspaceRoot,
148 repositoryIdentity: enrichment?.repositoryIdentity ?? null,
149 faviconPath: row.faviconPath ?? enrichment?.faviconPath ?? null,
150 defaultModelSelection: row.defaultModelSelection,
151 defaultThreadEnvMode: row.defaultThreadEnvMode,
152 autoPull: row.autoPull,
153 projectIcon: row.projectIcon,
154 scripts: row.scripts,
155 createdAt: row.createdAt,
156 updatedAt: row.updatedAt,
157 deletedAt: row.deletedAt,
158 });
159​
160 const hydrateAvailable = Effect.fn("ProjectService.hydrateAvailable")(function* (
161 row: ProjectionProjects.ProjectionProject,
162 ) {
163 const enrichment =
164 row.deletedAt === null
165 ? yield* projectEnrichment.getAvailable(row.workspaceRoot)
166 : yield* projectEnrichment.peek(row.workspaceRoot);
167 return toProject(row, enrichment);
168 });
169​
170 const readRows = Effect.fn("ProjectService.readRows")(function* () {
171 return yield* projects
172 .listAll()
173 .pipe(
174 Effect.mapError(
175 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
176 ),
177 );
178 });
179​
180 const getById: ProjectService["Service"]["getById"] = Effect.fn("ProjectService.getById")(
181 function* (projectId, options) {
182 const row = yield* projects
183 .getById({ projectId })
184 .pipe(
185 Effect.mapError(
186 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
187 ),
188 );
189 if (Option.isNone(row) || (row.value.deletedAt !== null && !options?.includeDeleted)) {
190 return Option.none();
191 }
192 return Option.some(yield* hydrateAvailable(row.value));
193 },
194 );
195​
196 const getByWorkspaceRoot: ProjectService["Service"]["getByWorkspaceRoot"] = Effect.fn(
197 "ProjectService.getByWorkspaceRoot",
198 )(function* (workspaceRoot, options) {
199 const normalized = yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
200 Effect.mapError(
201 (cause) =>
202 new ProjectOperationError({
203 operation: "normalize-workspace",
204 workspaceRoot,
205 cause,
206 }),
207 ),
208 );
209 const row = (yield* readRows()).find(
210 (candidate) =>
211 candidate.workspaceRoot === normalized &&
212 (options?.includeDeleted === true || candidate.deletedAt === null),
213 );
214 return row === undefined ? Option.none() : Option.some(yield* hydrateAvailable(row));
215 });
216​
217 const readCommitted = Effect.fn("ProjectService.readCommitted")(function* (projectId: ProjectId) {
218 const row = yield* projects
219 .getById({ projectId })
220 .pipe(
221 Effect.mapError(
222 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
223 ),
224 );
225 if (Option.isNone(row)) {
226 return yield* new ProjectOperationError({
227 operation: "read-project",
228 projectId,
229 cause: "The accepted project command did not produce a project projection.",
230 });
231 }
232 return yield* hydrateAvailable(row.value);
233 });
234​
235 const invalidateEnrichment = (...workspaceRoots: ReadonlyArray<string>) =>
236 projectEnrichment.invalidate(workspaceRoots);
237​
238 const dispatch = <A>(
239 projectId: ProjectId,
240 command: Parameters<OrchestrationEngineService["Service"]["dispatch"]>[0],
241 onCommitted: Effect.Effect<A, ProjectOperationError>,
242 ) =>
243 engine.dispatch(command).pipe(
244 Effect.mapError(
245 (cause) =>
246 new ProjectOperationError({
247 operation: "dispatch-project-command",
248 projectId,
249 cause,
250 }),
251 ),
252 Effect.andThen(onCommitted),
253 );
254​
255 const assertWorkspaceAvailable = Effect.fn("ProjectService.assertWorkspaceAvailable")(function* (
256 projectId: ProjectId,
257 workspaceRoot: string,
258 ) {
259 const conflicting = (yield* readRows()).find(
260 (candidate) =>
261 candidate.deletedAt === null &&
262 candidate.projectId !== projectId &&
263 candidate.workspaceRoot === workspaceRoot,
264 );
265 if (conflicting !== undefined) {
266 return yield* new ProjectConflictError({
267 projectId,
268 workspaceRoot,
269 conflictingProjectId: conflicting.projectId,
270 });
271 }
272 });
273​
274 const create: ProjectService["Service"]["create"] = Effect.fn("ProjectService.create")(
275 function* (input) {
276 const workspaceRoot = yield* workspacePaths
277 .normalizeWorkspaceRoot(input.workspaceRoot, {
278 createIfMissing: input.createWorkspaceRootIfMissing ?? false,
279 })
280 .pipe(
281 Effect.mapError(
282 (cause) =>
283 new ProjectOperationError({
284 operation: "normalize-workspace",
285 projectId: input.projectId,
286 workspaceRoot: input.workspaceRoot,
287 cause,
288 }),
289 ),
290 );
291 yield* assertWorkspaceAvailable(input.projectId, workspaceRoot);
292 const now = DateTime.formatIso(yield* DateTime.now);
293 return yield* dispatch(
294 input.projectId,
295 {
296 type: "project.create",
297 commandId: input.commandId,
298 projectId: input.projectId,
299 title: input.title,
300 workspaceRoot,
301 defaultModelSelection: input.defaultModelSelection ?? null,
302 scripts: [...(input.scripts ?? [])],
303 createdAt: now,
304 },
305 invalidateEnrichment(workspaceRoot).pipe(Effect.andThen(readCommitted(input.projectId))),
306 );
307 },
308 );
309​
310 const update: ProjectService["Service"]["update"] = Effect.fn("ProjectService.update")(
311 function* (input) {
312 const existing = yield* projects.getById({ projectId: input.projectId }).pipe(
313 Effect.mapError(
314 (cause) =>
315 new ProjectOperationError({
316 operation: "read-project",
317 projectId: input.projectId,
318 cause,
319 }),
320 ),
321 );
322 if (Option.isNone(existing) || existing.value.deletedAt !== null) {
323 return yield* new ProjectNotFoundError({ projectId: input.projectId });
324 }
325 const workspaceRoot =
326 input.workspaceRoot === undefined
327 ? existing.value.workspaceRoot
328 : yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
329 Effect.mapError(
330 (cause) =>
331 new ProjectOperationError({
332 operation: "normalize-workspace",
333 projectId: input.projectId,
334 workspaceRoot: input.workspaceRoot,
335 cause,
336 }),
337 ),
338 );
339 yield* assertWorkspaceAvailable(input.projectId, workspaceRoot);
340 return yield* dispatch(
341 input.projectId,
342 {
343 type: "project.meta.update",
344 commandId: input.commandId,
345 projectId: input.projectId,
346 ...(input.title === undefined ? {} : { title: input.title }),
347 ...(workspaceRoot === existing.value.workspaceRoot ? {} : { workspaceRoot }),
348 ...(input.defaultModelSelection === undefined
349 ? {}
350 : { defaultModelSelection: input.defaultModelSelection }),
351 ...(input.autoPull === undefined ? {} : { autoPull: input.autoPull }),
352 ...(input.projectIcon === undefined ? {} : { projectIcon: input.projectIcon }),
353 ...(input.faviconPath === undefined ? {} : { faviconPath: input.faviconPath }),
354 ...(input.defaultThreadEnvMode === undefined
355 ? {}
356 : { defaultThreadEnvMode: input.defaultThreadEnvMode }),
357 ...(input.scripts === undefined ? {} : { scripts: [...input.scripts] }),
358 },
359 (workspaceRoot === existing.value.workspaceRoot
360 ? Effect.void
361 : invalidateEnrichment(existing.value.workspaceRoot, workspaceRoot)
362 ).pipe(Effect.andThen(readCommitted(input.projectId))),
363 );
364 },
365 );
366​
367 const bootstrap: ProjectService["Service"]["bootstrap"] = Effect.fn("ProjectService.bootstrap")(
368 function* (input) {
369 const existing = yield* getByWorkspaceRoot(input.workspaceRoot);
370 if (Option.isSome(existing)) return { project: existing.value, created: false };
371 return { project: yield* create(input), created: true };
372 },
373 );
374​
375 const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")(
376 function* (input) {
377 const { projectId } = input;
378 const existing = yield* projects
379 .getById({ projectId })
380 .pipe(
381 Effect.mapError(
382 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
383 ),
384 );
385 if (Option.isNone(existing) || existing.value.deletedAt !== null) {
386 return yield* new ProjectNotFoundError({ projectId });
387 }
388​
389 const snapshot = yield* threadProjections
390 .getShellSnapshot()
391 .pipe(
392 Effect.mapError(
393 (cause) => new ProjectOperationError({ operation: "list-threads", projectId, cause }),
394 ),
395 );
396 const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter(
397 (thread) => thread.projectId === projectId,
398 );
399 if (projectThreads.length > 0 && input.force !== true) {
400 return yield* new ProjectNotEmptyError({ projectId });
401 }
402​
403 // Delete children durably before the project. Stable command IDs let a retry
404 // finish a partially completed cascade without repeating cleanup effects.
405 yield* Effect.forEach(
406 projectThreads,
407 (thread) =>
408 threadCommands
409 .withLock(
410 thread.id,
411 Effect.gen(function* () {
412 yield* legacyImporter.ensureTranscript(thread.id);
413 const projection = yield* threadProjections.getThreadProjection(thread.id);
414 if (
415 projection.thread.deletedAt !== null ||
416 projection.thread.projectId !== projectId
417 ) {
418 return;
419 }
420 const command = {
421 type: "thread.delete" as const,
422 commandId: CommandId.make(`${input.commandId}:delete-thread:${thread.id}`),
423 threadId: thread.id,
424 };
425 const now = yield* DateTime.now;
426 const plan = yield* planThreadDeletion({ command, projection, now, idAllocator });
427 const committed = yield* threadEvents.commitCommand({
428 commandId: command.commandId,
429 commandType: command.type,
430 threadId: command.threadId,
431 acceptedAt: now,
432 events: plan.events,
433 effects: plan.effects,
434 });
435 if (
436 committed.receipt.threadId !== command.threadId ||
437 committed.receipt.commandType !== command.type
438 ) {
439 return yield* Effect.fail(
440 "The thread deletion command ID belongs to a different command.",
441 );
442 }
443 if (committed.receipt.status === "rejected") {
444 return yield* Effect.fail(
445 committed.receipt.error ?? "Thread deletion was previously rejected.",
446 );
447 }
448 }),
449 )
450 .pipe(
451 Effect.mapError(
452 (cause) =>
453 new ProjectOperationError({ operation: "delete-thread", projectId, cause }),
454 ),
455 ),
456 { concurrency: 1, discard: true },
457 );
458 return yield* dispatch(
459 projectId,
460 {
461 type: "project.delete",
462 commandId: input.commandId,
463 projectId,
464 ...(input.force === undefined ? {} : { force: input.force }),
465 },
466 invalidateEnrichment(existing.value.workspaceRoot).pipe(
467 Effect.andThen(readCommitted(projectId)),
468 ),
469 );
470 },
471 );
472​
473 const snapshot = Effect.gen(function* () {
474 const rows = (yield* readRows()).filter((row) => row.deletedAt === null);
475 const hydrated = yield* Effect.forEach(rows, hydrateAvailable, { concurrency: 8 });
476 return {
477 projects: hydrated,
478 updatedAt: DateTime.formatIso(yield* DateTime.now),
479 } satisfies ProjectSnapshot;
480 });
481​
482 return ProjectService.of({
483 create,
484 bootstrap,
485 update,
486 delete: deleteProject,
487 getById,
488 getByWorkspaceRoot,
489 snapshot,
490 });
491});
492​
493export const layer = Layer.effect(ProjectService, make).pipe(
494 Layer.provide(threadCommandExecutorLayer),
495);