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

ProjectService.ts

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