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

ProjectService.ts

575 lines20.4 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 readonly getShell: (
136 projectId: ProjectId,
137 ) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectOperationError>;
138 readonly listShells: (options?: {
139 readonly projectIds?: ReadonlyArray<ProjectId>;
140 }) => Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, ProjectOperationError>;
141 }
142>()("t3/project/ProjectService") {}
143​
144export const make = Effect.gen(function* () {
145 const projects = yield* ProjectStore.ProjectStoreV2;
146 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
147 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
148 const threadProjections = yield* ProjectionStore.ProjectionStoreV2;
149 const eventSink = yield* EventSink.EventSinkV2;
150 const idAllocator = yield* IdAllocator.IdAllocatorV2;
151 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
152 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
153 const serverSettings = yield* ServerSettings.ServerSettingsService;
154 const projectLocks = yield* KeyedLock.make<ProjectId>();
155 const workspaceLocks = yield* KeyedLock.make<string>();
156​
157 const toProject = (
158 row: ProjectStore.ProjectRow,
159 enrichment: ProjectEnrichmentService.ProjectEnrichment | null,
160 ): Project => ({
161 id: row.projectId,
162 title: row.title,
163 workspaceRoot: row.workspaceRoot,
164 repositoryIdentity: enrichment?.repositoryIdentity ?? null,
165 faviconPath: row.faviconPath ?? enrichment?.faviconPath ?? null,
166 defaultModelSelection: row.defaultModelSelection,
167 defaultThreadEnvMode: row.defaultThreadEnvMode,
168 autoPull: row.autoPull,
169 projectIcon: row.projectIcon,
170 scripts: row.scripts,
171 createdAt: row.createdAt,
172 updatedAt: row.updatedAt,
173 deletedAt: row.deletedAt,
174 });
175​
176 const hydrate = Effect.fn("ProjectService.hydrate")(function* (row: ProjectStore.ProjectRow) {
177 const enrichment =
178 row.deletedAt === null
179 ? yield* projectEnrichment.getAvailable(row.workspaceRoot)
180 : yield* projectEnrichment.peek(row.workspaceRoot);
181 return toProject(row, enrichment);
182 });
183​
184 const readRow = (projectId: ProjectId, options?: { readonly includeDeleted?: boolean }) =>
185 projects
186 .get(projectId, options)
187 .pipe(
188 Effect.mapError(
189 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
190 ),
191 );
192​
193 const normalizeWorkspaceRoot = (input: {
194 readonly projectId?: ProjectId;
195 readonly workspaceRoot: string;
196 readonly createIfMissing?: boolean;
197 }) =>
198 workspacePaths
199 .normalizeWorkspaceRoot(input.workspaceRoot, {
200 createIfMissing: input.createIfMissing ?? false,
201 })
202 .pipe(
203 Effect.mapError(
204 (cause) =>
205 new ProjectOperationError({
206 operation: "normalize-workspace",
207 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
208 workspaceRoot: input.workspaceRoot,
209 cause,
210 }),
211 ),
212 );
213​
214 const commit = Effect.fn("ProjectService.commit")(function* (command: ProjectCommand) {
215 const { projectId } = command;
216 const dispatchError = (cause: unknown) =>
217 new ProjectOperationError({ operation: "dispatch-project-command", projectId, cause });
218 const workspaceRoot = command.type === "project.delete" ? undefined : command.workspaceRoot;
219 const planAndCommit = Effect.gen(function* () {
220 const project = Option.getOrUndefined(yield* readRow(projectId, { includeDeleted: true }));
221 const workspaceOwner =
222 workspaceRoot === undefined
223 ? undefined
224 : Option.getOrUndefined(
225 yield* projects
226 .findActiveByWorkspaceRoot(workspaceRoot)
227 .pipe(Effect.mapError(dispatchError)),
228 );
229 const now = yield* DateTime.now;
230 const eventId = yield* idAllocator.allocate
231 .event({ commandId: command.commandId })
232 .pipe(Effect.mapError(dispatchError));
233 const planned = planProjectCommand({
234 command,
235 state: { project, workspaceOwner },
236 eventId,
237 now,
238 });
239 if (Result.isSuccess(planned)) {
240 const { receipt } = yield* eventSink.commitProjectCommand({
241 commandId: command.commandId,
242 projectId,
243 commandType: command.type,
244 acceptedAt: now,
245 event: planned.success,
246 });
247 return receipt;
248 }
249 return yield* eventSink.commitRejectedProjectCommand({
250 commandId: command.commandId,
251 projectId,
252 commandType: command.type,
253 rejectedAt: now,
254 error: encodeProjectCommandRejection(planned.failure),
255 });
256 });
257 const receipt = yield* projectLocks
258 .withLock(
259 projectId,
260 workspaceRoot === undefined
261 ? planAndCommit
262 : workspaceLocks.withLock(workspaceRoot, planAndCommit),
263 )
264 .pipe(Effect.mapError(dispatchError));
265 if (receipt.projectId !== projectId || receipt.commandType !== command.type) {
266 return yield* dispatchError(
267 `Command ${command.commandId} was already used by ${receipt.commandType} for ${receipt.projectId}.`,
268 );
269 }
270 // Retries re-plan against their own effects; the first receipt determines 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 }, withCommandMetrics);
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 // Best-effort cleanup releases disabled instances kept alive by overrides; crashes have no replay to revisit deletion.
478 const clearProjectSettingsOverrides = (projectId: ProjectId) =>
479 serverSettings.updateSettings({ projectSettingsOverrides: { [projectId]: null } }).pipe(
480 Effect.asVoid,
481 Effect.catchCause((cause) =>
482 Effect.logWarning(
483 `Failed to clear settings overrides for deleted project ${projectId}.`,
484 cause,
485 ),
486 ),
487 );
488​
489 const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")(
490 function* (input) {
491 const { projectId } = input;
492 // Read deleted rows so retries replay receipts and other command ids fail as not found.
493 const existing = yield* readRow(projectId, { includeDeleted: true });
494 if (Option.isNone(existing)) {
495 return yield* new ProjectNotFoundError({ projectId });
496 }
497​
498 const isFirstDelete = existing.value.deletedAt === null;
499 if (isFirstDelete) {
500 yield* deleteChildThreads(input);
501 }
502 yield* commit({ type: "project.delete", commandId: input.commandId, projectId });
503 if (isFirstDelete) {
504 yield* clearProjectSettingsOverrides(projectId);
505 }
506 yield* projectEnrichment.invalidate([existing.value.workspaceRoot]);
507 return yield* readCommitted(projectId);
508 },
509 );
510​
511 const enrichShell = (shell: OrchestrationProjectShell) =>
512 projectEnrichment.getAvailable(shell.workspaceRoot).pipe(
513 Effect.map((enrichment) => ({
514 ...shell,
515 repositoryIdentity: enrichment.repositoryIdentity,
516 })),
517 );
518​
519 const getShell: ProjectService["Service"]["getShell"] = Effect.fn("ProjectService.getShell")(
520 function* (projectId) {
521 const shell = yield* projects
522 .getShell(projectId)
523 .pipe(
524 Effect.mapError(
525 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
526 ),
527 );
528 return Option.isNone(shell) ? shell : Option.some(yield* enrichShell(shell.value));
529 },
530 );
531​
532 const listShells: ProjectService["Service"]["listShells"] = Effect.fn(
533 "ProjectService.listShells",
534 )(function* (options) {
535 const shells = yield* projects
536 .listShells(options)
537 .pipe(
538 Effect.mapError(
539 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
540 ),
541 );
542 return yield* Effect.forEach(shells, enrichShell, { concurrency: 16 });
543 });
544​
545 const snapshot = Effect.gen(function* () {
546 const rows = yield* projects
547 .list()
548 .pipe(
549 Effect.mapError(
550 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
551 ),
552 );
553 const hydrated = yield* Effect.forEach(rows, hydrate, { concurrency: 8 });
554 return {
555 projects: hydrated,
556 updatedAt: DateTime.formatIso(yield* DateTime.now),
557 } satisfies ProjectSnapshot;
558 });
559​
560 return ProjectService.of({
561 create,
562 bootstrap,
563 update,
564 delete: deleteProject,
565 getById,
566 getByWorkspaceRoot,
567 snapshot,
568 getShell,
569 listShells,
570 });
571});
572​
573export const layer = Layer.effect(ProjectService, make).pipe(
574 Layer.provide(ThreadCommandExecutor.layer),
575);