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

ProjectService.ts

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