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

ProjectService.ts

580 lines20.7 KB

1import {
2 CommandId,
3 type OrchestrationProjectShell,
4 ProjectId,
5 type Project,
6 type ProjectCreatePayload,
7 type ProjectUpdatePayload,
8 type ProjectSnapshot,
9 type ThreadId,
10} from "@t3tools/contracts";
11import * as KeyedLock from "@t3tools/shared/KeyedLock";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Result from "effect/Result";
18import * as Schema from "effect/Schema";
19​
20import * as EventSink from "../orchestration-v2/EventSink.ts";
21import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
22import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
23import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
24import {
25 decodeProjectCommandRejection,
26 encodeProjectCommandRejection,
27 planProjectCommand,
28 type ProjectCommand,
29} from "../orchestration-v2/ProjectCommands.ts";
30import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
31import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
32import { planThreadDeletion } from "../orchestration-v2/ThreadDeletion.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts";
35import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
36​
37export interface ProjectCreateInput extends ProjectCreatePayload {
38 readonly commandId: CommandId;
39 readonly projectId: ProjectId;
41​
42export interface ProjectUpdateInput extends ProjectUpdatePayload {
43 readonly commandId: CommandId;
44 readonly projectId: ProjectId;
46​
47export interface ProjectBootstrapInput extends ProjectCreateInput {}
48​
49export interface ProjectDeleteInput {
50 readonly commandId: CommandId;
51 readonly projectId: ProjectId;
52 readonly force?: boolean;
54​
55export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
56 "ProjectNotFoundError",
57 { projectId: ProjectId },
58) {
59 override get message(): string {
60 return `Project ${this.projectId} was not found.`;
61 }
63​
64export class ProjectConflictError extends Schema.TaggedError<ProjectConflictError>()(
65 "ProjectConflictError",
66 {
67 projectId: ProjectId,
68 workspaceRoot: Schema.String,
69 conflictingProjectId: ProjectId,
70 },
71) {
72 override get message(): string {
73 return `Workspace ${this.workspaceRoot} already belongs to project ${this.conflictingProjectId}.`;
74 }
76​
77export class ProjectNotEmptyError extends Schema.TaggedError<ProjectNotEmptyError>()(
78 "ProjectNotEmptyError",
79 { projectId: ProjectId },
80) {
81 override get message(): string {
82 return `Project ${this.projectId} is not empty.`;
83 }
85​
86export class ProjectOperationError extends Schema.TaggedError<ProjectOperationError>()(
87 "ProjectOperationError",
88 {
89 operation: Schema.Literals([
90 "normalize-workspace",
91 "read-project",
92 "list-projects",
93 "list-threads",
94 "delete-thread",
95 "dispatch-project-command",
96 ]),
97 projectId: Schema.optional(ProjectId),
98 workspaceRoot: Schema.optional(Schema.String),
99 cause: Schema.Defect(),
100 },
101) {
102 override get message(): string {
103 return `Project operation '${this.operation}' failed${this.projectId === undefined ? "" : ` for ${this.projectId}`}.`;
104 }
106​
107export type ProjectServiceError =
108 | ProjectNotFoundError
109 | ProjectConflictError
110 | ProjectNotEmptyError
111 | ProjectOperationError;
112​
113export class ProjectService extends Context.Service<
114 ProjectService,
115 {
116 readonly create: (input: ProjectCreateInput) => Effect.Effect<Project, ProjectServiceError>;
117 readonly bootstrap: (
118 input: ProjectBootstrapInput,
119 ) => Effect.Effect<
120 { readonly project: Project; readonly created: boolean },
121 ProjectServiceError
122 >;
123 readonly update: (input: ProjectUpdateInput) => Effect.Effect<Project, ProjectServiceError>;
124 readonly delete: (input: ProjectDeleteInput) => Effect.Effect<Project, ProjectServiceError>;
125 readonly getById: (
126 projectId: ProjectId,
127 options?: { readonly includeDeleted?: boolean },
128 ) => Effect.Effect<Option.Option<Project>, ProjectOperationError>;
129 readonly getByWorkspaceRoot: (
130 workspaceRoot: string,
131 options?: { readonly includeDeleted?: boolean },
132 ) => Effect.Effect<Option.Option<Project>, ProjectOperationError>;
133 readonly snapshot: Effect.Effect<ProjectSnapshot, ProjectOperationError>;
134 readonly getShell: (
135 projectId: ProjectId,
136 ) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectOperationError>;
137 readonly listShells: (options?: {
138 readonly projectIds?: ReadonlyArray<ProjectId>;
139 }) => Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, ProjectOperationError>;
140 }
141>()("t3/project/ProjectService") {}
142​
143export const make = Effect.gen(function* () {
144 const projects = yield* ProjectStore.ProjectStoreV2;
145 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
146 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
147 const threadProjections = yield* ProjectionStore.ProjectionStoreV2;
148 const eventSink = yield* EventSink.EventSinkV2;
149 const idAllocator = yield* IdAllocator.IdAllocatorV2;
150 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
151 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
152 const serverSettings = yield* ServerSettings.ServerSettingsService;
153 const projectLocks = yield* KeyedLock.make<ProjectId>();
154 const workspaceLocks = yield* KeyedLock.make<string>();
155​
156 const toProject = (
157 row: ProjectStore.ProjectRow,
158 enrichment: ProjectEnrichmentService.ProjectEnrichment | null,
159 ): Project => ({
160 id: row.projectId,
161 title: row.title,
162 workspaceRoot: row.workspaceRoot,
163 repositoryIdentity: enrichment?.repositoryIdentity ?? null,
164 faviconPath: row.faviconPath ?? enrichment?.faviconPath ?? null,
165 defaultModelSelection: row.defaultModelSelection,
166 defaultThreadEnvMode: row.defaultThreadEnvMode,
167 autoPull: row.autoPull,
168 projectIcon: row.projectIcon,
169 scripts: row.scripts,
170 createdAt: row.createdAt,
171 updatedAt: row.updatedAt,
172 deletedAt: row.deletedAt,
173 });
174​
175 const hydrate = Effect.fn("ProjectService.hydrate")(function* (row: ProjectStore.ProjectRow) {
176 const enrichment =
177 row.deletedAt === null
178 ? yield* projectEnrichment.getAvailable(row.workspaceRoot)
179 : yield* projectEnrichment.peek(row.workspaceRoot);
180 return toProject(row, enrichment);
181 });
182​
183 const readRow = (projectId: ProjectId, options?: { readonly includeDeleted?: boolean }) =>
184 projects
185 .get(projectId, options)
186 .pipe(
187 Effect.mapError(
188 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
189 ),
190 );
191​
192 const normalizeWorkspaceRoot = (input: {
193 readonly projectId?: ProjectId;
194 readonly workspaceRoot: string;
195 readonly createIfMissing?: boolean;
196 }) =>
197 workspacePaths
198 .normalizeWorkspaceRoot(input.workspaceRoot, {
199 createIfMissing: input.createIfMissing ?? false,
200 })
201 .pipe(
202 Effect.mapError(
203 (cause) =>
204 new ProjectOperationError({
205 operation: "normalize-workspace",
206 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
207 workspaceRoot: input.workspaceRoot,
208 cause,
209 }),
210 ),
211 );
212​
213 const commit = Effect.fn("ProjectService.commit")(function* (command: ProjectCommand) {
214 const { projectId } = command;
215 const dispatchError = (cause: unknown) =>
216 new ProjectOperationError({ operation: "dispatch-project-command", projectId, cause });
217 const workspaceRoot = command.type === "project.delete" ? undefined : command.workspaceRoot;
218 const planAndCommit = Effect.gen(function* () {
219 const project = Option.getOrUndefined(yield* readRow(projectId, { includeDeleted: true }));
220 const workspaceOwner =
221 workspaceRoot === undefined
222 ? undefined
223 : Option.getOrUndefined(
224 yield* projects
225 .findActiveByWorkspaceRoot(workspaceRoot)
226 .pipe(Effect.mapError(dispatchError)),
227 );
228 const now = yield* DateTime.now;
229 const eventId = yield* idAllocator.allocate
230 .event({ commandId: command.commandId })
231 .pipe(Effect.mapError(dispatchError));
232 const planned = planProjectCommand({
233 command,
234 state: { project, workspaceOwner },
235 eventId,
236 now,
237 });
238 if (Result.isSuccess(planned)) {
239 const { receipt } = yield* eventSink.commitProjectCommand({
240 commandId: command.commandId,
241 projectId,
242 commandType: command.type,
243 acceptedAt: now,
244 event: planned.success,
245 });
246 return receipt;
247 }
248 return yield* eventSink.commitRejectedProjectCommand({
249 commandId: command.commandId,
250 projectId,
251 commandType: command.type,
252 rejectedAt: now,
253 error: encodeProjectCommandRejection(planned.failure),
254 });
255 });
256 const receipt = yield* projectLocks
257 .withLock(
258 projectId,
259 workspaceRoot === undefined
260 ? planAndCommit
261 : workspaceLocks.withLock(workspaceRoot, planAndCommit),
262 )
263 .pipe(Effect.mapError(dispatchError));
264 if (receipt.projectId !== projectId || receipt.commandType !== command.type) {
265 return yield* dispatchError(
266 `Command ${command.commandId} was already used by ${receipt.commandType} for ${receipt.projectId}.`,
267 );
268 }
269 // A retried command re-plans against the state it already produced, so its
270 // first receipt, not the new plan, decides the outcome.
271 if (receipt.status === "accepted") return;
272 const rejection = Option.getOrUndefined(decodeProjectCommandRejection(receipt.error));
273 switch (rejection?._tag) {
274 case "ProjectWorkspaceConflictError":
275 return yield* new ProjectConflictError({
276 projectId,
277 workspaceRoot: rejection.workspaceRoot,
278 conflictingProjectId: rejection.conflictingProjectId,
279 });
280 case "ProjectCommandMissingProjectError":
281 return yield* new ProjectNotFoundError({ projectId });
282 default:
283 return yield* dispatchError(
284 rejection ?? receipt.error ?? "The command was previously rejected.",
285 );
286 }
287 });
288​
289 const readCommitted = Effect.fn("ProjectService.readCommitted")(function* (projectId: ProjectId) {
290 const row = yield* readRow(projectId, { includeDeleted: true });
291 if (Option.isNone(row)) {
292 return yield* new ProjectOperationError({
293 operation: "read-project",
294 projectId,
295 cause: "The accepted project command did not produce a project row.",
296 });
297 }
298 return yield* hydrate(row.value);
299 });
300​
301 const getById: ProjectService["Service"]["getById"] = Effect.fn("ProjectService.getById")(
302 function* (projectId, options) {
303 const row = yield* readRow(projectId, options);
304 return Option.isNone(row) ? Option.none() : Option.some(yield* hydrate(row.value));
305 },
306 );
307​
308 const getByWorkspaceRoot: ProjectService["Service"]["getByWorkspaceRoot"] = Effect.fn(
309 "ProjectService.getByWorkspaceRoot",
310 )(function* (workspaceRoot, options) {
311 const normalized = yield* normalizeWorkspaceRoot({ workspaceRoot });
312 const row = yield* (
313 options?.includeDeleted === true
314 ? projects
315 .list({ includeDeleted: true })
316 .pipe(
317 Effect.map((rows) =>
318 Option.fromUndefinedOr(rows.find((row) => row.workspaceRoot === normalized)),
319 ),
320 )
321 : projects.findActiveByWorkspaceRoot(normalized)
322 ).pipe(
323 Effect.mapError((cause) => new ProjectOperationError({ operation: "list-projects", cause })),
324 );
325 return Option.isNone(row) ? Option.none() : Option.some(yield* hydrate(row.value));
326 });
327​
328 const create: ProjectService["Service"]["create"] = Effect.fn("ProjectService.create")(
329 function* (input) {
330 const workspaceRoot = yield* normalizeWorkspaceRoot({
331 projectId: input.projectId,
332 workspaceRoot: input.workspaceRoot,
333 createIfMissing: input.createWorkspaceRootIfMissing ?? false,
334 });
335 yield* commit({
336 type: "project.create",
337 commandId: input.commandId,
338 projectId: input.projectId,
339 title: input.title,
340 workspaceRoot,
341 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
342 });
343 yield* projectEnrichment.invalidate([workspaceRoot]);
344 return yield* readCommitted(input.projectId);
345 },
346 );
347​
348 const update: ProjectService["Service"]["update"] = Effect.fn("ProjectService.update")(
349 function* (input) {
350 const existing = yield* readRow(input.projectId);
351 if (Option.isNone(existing)) {
352 return yield* new ProjectNotFoundError({ projectId: input.projectId });
353 }
354 const previousRoot = existing.value.workspaceRoot;
355 const workspaceRoot =
356 input.workspaceRoot === undefined
357 ? previousRoot
358 : yield* normalizeWorkspaceRoot({
359 projectId: input.projectId,
360 workspaceRoot: input.workspaceRoot,
361 });
362 yield* commit({
363 type: "project.meta.update",
364 commandId: input.commandId,
365 projectId: input.projectId,
366 ...(input.title === undefined ? {} : { title: input.title }),
367 ...(workspaceRoot === previousRoot ? {} : { workspaceRoot }),
368 ...(input.defaultModelSelection === undefined
369 ? {}
370 : { defaultModelSelection: input.defaultModelSelection }),
371 ...(input.autoPull === undefined ? {} : { autoPull: input.autoPull }),
372 ...(input.projectIcon === undefined ? {} : { projectIcon: input.projectIcon }),
373 ...(input.faviconPath === undefined ? {} : { faviconPath: input.faviconPath }),
374 ...(input.defaultThreadEnvMode === undefined
375 ? {}
376 : { defaultThreadEnvMode: input.defaultThreadEnvMode }),
377 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
378 });
379 if (workspaceRoot !== previousRoot) {
380 yield* projectEnrichment.invalidate([previousRoot, workspaceRoot]);
381 }
382 return yield* readCommitted(input.projectId);
383 },
384 );
385​
386 const bootstrap: ProjectService["Service"]["bootstrap"] = Effect.fn("ProjectService.bootstrap")(
387 function* (input) {
388 const existing = yield* getByWorkspaceRoot(input.workspaceRoot);
389 if (Option.isSome(existing)) return { project: existing.value, created: false };
390 return { project: yield* create(input), created: true };
391 },
392 );
393​
394 const deleteChildThread = Effect.fn("ProjectService.deleteChildThread")(function* (
395 input: ProjectDeleteInput,
396 threadId: ThreadId,
397 ) {
398 yield* legacyImporter.ensureTranscript(threadId);
399 const projection = yield* threadProjections.getThreadRecords(threadId, [
400 "runs",
401 "attempts",
402 "nodes",
403 "runtimeRequests",
404 "subagents",
405 "providerSessions",
406 ]);
407 if (projection.thread.deletedAt !== null || projection.thread.projectId !== input.projectId) {
408 return;
409 }
410 const command = {
411 type: "thread.delete" as const,
412 commandId: CommandId.make(`${input.commandId}:delete-thread:${threadId}`),
413 threadId,
414 };
415 const now = yield* DateTime.now;
416 const plan = yield* planThreadDeletion({
417 command,
418 projection,
419 attachmentIds: yield* threadProjections.getThreadAttachmentIds(threadId),
420 now,
421 idAllocator,
422 });
423 const committed = yield* eventSink.commitCommand({
424 commandId: command.commandId,
425 commandType: command.type,
426 threadId,
427 acceptedAt: now,
428 events: plan.events,
429 effects: plan.effects,
430 });
431 if (
432 committed.receipt.threadId !== command.threadId ||
433 committed.receipt.commandType !== command.type
434 ) {
435 return yield* Effect.fail("The thread deletion command ID belongs to a different command.");
436 }
437 if (committed.receipt.status === "rejected") {
438 return yield* Effect.fail(
439 committed.receipt.error ?? "Thread deletion was previously rejected.",
440 );
441 }
442 });
443​
444 const deleteChildThreads = Effect.fn("ProjectService.deleteChildThreads")(function* (
445 input: ProjectDeleteInput,
446 ) {
447 const { projectId } = input;
448 const snapshot = yield* threadProjections
449 .getShellSnapshot()
450 .pipe(
451 Effect.mapError(
452 (cause) => new ProjectOperationError({ operation: "list-threads", projectId, cause }),
453 ),
454 );
455 const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter(
456 (thread) => thread.projectId === projectId,
457 );
458 if (projectThreads.length > 0 && input.force !== true) {
459 return yield* new ProjectNotEmptyError({ projectId });
460 }
461 // Delete children durably before the project so a failed cascade can be retried.
462 yield* Effect.forEach(
463 projectThreads,
464 (thread) =>
465 threadCommands
466 .withLock(thread.id, deleteChildThread(input, thread.id))
467 .pipe(
468 Effect.mapError(
469 (cause) =>
470 new ProjectOperationError({ operation: "delete-thread", projectId, cause }),
471 ),
472 ),
473 { concurrency: 1, discard: true },
474 );
475 });
476​
477 // A machine-disabled provider instance that a deleted project's override
478 // once turned on must not stay probed and alive forever. Nothing else
479 // removes the entry, so deletion is where it goes; best-effort because a
480 // settings write failure should not block the deletion it is cleaning up
481 // after, and a server crash before a replay never revisits this project.
482 const clearProjectSettingsOverrides = (projectId: ProjectId) =>
483 serverSettings.updateSettings({ projectSettingsOverrides: { [projectId]: null } }).pipe(
484 Effect.asVoid,
485 Effect.catchCause((cause) =>
486 Effect.logWarning(
487 `Failed to clear settings overrides for deleted project ${projectId}.`,
488 cause,
489 ),
490 ),
491 );
492​
493 const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")(
494 function* (input) {
495 const { projectId } = input;
496 // A deleted row still reaches commit, so a retried command id replays its
497 // receipt and any other command id is rejected as not found.
498 const existing = yield* readRow(projectId, { includeDeleted: true });
499 if (Option.isNone(existing)) {
500 return yield* new ProjectNotFoundError({ projectId });
501 }
502​
503 const isFirstDelete = existing.value.deletedAt === null;
504 if (isFirstDelete) {
505 yield* deleteChildThreads(input);
506 }
507 yield* commit({ type: "project.delete", commandId: input.commandId, projectId });
508 if (isFirstDelete) {
509 yield* clearProjectSettingsOverrides(projectId);
510 }
511 yield* projectEnrichment.invalidate([existing.value.workspaceRoot]);
512 return yield* readCommitted(projectId);
513 },
514 );
515​
516 const enrichShell = (shell: OrchestrationProjectShell) =>
517 projectEnrichment.getAvailable(shell.workspaceRoot).pipe(
518 Effect.map((enrichment) => ({
519 ...shell,
520 repositoryIdentity: enrichment.repositoryIdentity,
521 })),
522 );
523​
524 const getShell: ProjectService["Service"]["getShell"] = Effect.fn("ProjectService.getShell")(
525 function* (projectId) {
526 const shell = yield* projects
527 .getShell(projectId)
528 .pipe(
529 Effect.mapError(
530 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
531 ),
532 );
533 return Option.isNone(shell) ? shell : Option.some(yield* enrichShell(shell.value));
534 },
535 );
536​
537 const listShells: ProjectService["Service"]["listShells"] = Effect.fn(
538 "ProjectService.listShells",
539 )(function* (options) {
540 const shells = yield* projects
541 .listShells(options)
542 .pipe(
543 Effect.mapError(
544 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
545 ),
546 );
547 return yield* Effect.forEach(shells, enrichShell, { concurrency: 16 });
548 });
549​
550 const snapshot = Effect.gen(function* () {
551 const rows = yield* projects
552 .list()
553 .pipe(
554 Effect.mapError(
555 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
556 ),
557 );
558 const hydrated = yield* Effect.forEach(rows, hydrate, { concurrency: 8 });
559 return {
560 projects: hydrated,
561 updatedAt: DateTime.formatIso(yield* DateTime.now),
562 } satisfies ProjectSnapshot;
563 });
564​
565 return ProjectService.of({
566 create,
567 bootstrap,
568 update,
569 delete: deleteProject,
570 getById,
571 getByWorkspaceRoot,
572 snapshot,
573 getShell,
574 listShells,
575 });
576});
577​
578export const layer = Layer.effect(ProjectService, make).pipe(
579 Layer.provide(ThreadCommandExecutor.layer),
580);