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

ProjectService.ts

574 lines20.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 * 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 // Retries re-plan against their own effects; the first receipt determines the outcome.
270 if (receipt.status === "accepted") return;
271 const rejection = Option.getOrUndefined(decodeProjectCommandRejection(receipt.error));
272 switch (rejection?._tag) {
273 case "ProjectWorkspaceConflictError":
274 return yield* new ProjectConflictError({
275 projectId,
276 workspaceRoot: rejection.workspaceRoot,
277 conflictingProjectId: rejection.conflictingProjectId,
278 });
279 case "ProjectCommandMissingProjectError":
280 return yield* new ProjectNotFoundError({ projectId });
281 default:
282 return yield* dispatchError(
283 rejection ?? receipt.error ?? "The command was previously rejected.",
284 );
285 }
286 });
287​
288 const readCommitted = Effect.fn("ProjectService.readCommitted")(function* (projectId: ProjectId) {
289 const row = yield* readRow(projectId, { includeDeleted: true });
290 if (Option.isNone(row)) {
291 return yield* new ProjectOperationError({
292 operation: "read-project",
293 projectId,
294 cause: "The accepted project command did not produce a project row.",
295 });
296 }
297 return yield* hydrate(row.value);
298 });
299​
300 const getById: ProjectService["Service"]["getById"] = Effect.fn("ProjectService.getById")(
301 function* (projectId, options) {
302 const row = yield* readRow(projectId, options);
303 return Option.isNone(row) ? Option.none() : Option.some(yield* hydrate(row.value));
304 },
305 );
306​
307 const getByWorkspaceRoot: ProjectService["Service"]["getByWorkspaceRoot"] = Effect.fn(
308 "ProjectService.getByWorkspaceRoot",
309 )(function* (workspaceRoot, options) {
310 const normalized = yield* normalizeWorkspaceRoot({ workspaceRoot });
311 const row = yield* (
312 options?.includeDeleted === true
313 ? projects
314 .list({ includeDeleted: true })
315 .pipe(
316 Effect.map((rows) =>
317 Option.fromUndefinedOr(rows.find((row) => row.workspaceRoot === normalized)),
318 ),
319 )
320 : projects.findActiveByWorkspaceRoot(normalized)
321 ).pipe(
322 Effect.mapError((cause) => new ProjectOperationError({ operation: "list-projects", cause })),
323 );
324 return Option.isNone(row) ? Option.none() : Option.some(yield* hydrate(row.value));
325 });
326​
327 const create: ProjectService["Service"]["create"] = Effect.fn("ProjectService.create")(
328 function* (input) {
329 const workspaceRoot = yield* normalizeWorkspaceRoot({
330 projectId: input.projectId,
331 workspaceRoot: input.workspaceRoot,
332 createIfMissing: input.createWorkspaceRootIfMissing ?? false,
333 });
334 yield* commit({
335 type: "project.create",
336 commandId: input.commandId,
337 projectId: input.projectId,
338 title: input.title,
339 workspaceRoot,
340 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
341 });
342 yield* projectEnrichment.invalidate([workspaceRoot]);
343 return yield* readCommitted(input.projectId);
344 },
345 );
346​
347 const update: ProjectService["Service"]["update"] = Effect.fn("ProjectService.update")(
348 function* (input) {
349 const existing = yield* readRow(input.projectId);
350 if (Option.isNone(existing)) {
351 return yield* new ProjectNotFoundError({ projectId: input.projectId });
352 }
353 const previousRoot = existing.value.workspaceRoot;
354 const workspaceRoot =
355 input.workspaceRoot === undefined
356 ? previousRoot
357 : yield* normalizeWorkspaceRoot({
358 projectId: input.projectId,
359 workspaceRoot: input.workspaceRoot,
360 });
361 yield* commit({
362 type: "project.meta.update",
363 commandId: input.commandId,
364 projectId: input.projectId,
365 ...(input.title === undefined ? {} : { title: input.title }),
366 ...(workspaceRoot === previousRoot ? {} : { workspaceRoot }),
367 ...(input.defaultModelSelection === undefined
368 ? {}
369 : { defaultModelSelection: input.defaultModelSelection }),
370 ...(input.autoPull === undefined ? {} : { autoPull: input.autoPull }),
371 ...(input.projectIcon === undefined ? {} : { projectIcon: input.projectIcon }),
372 ...(input.faviconPath === undefined ? {} : { faviconPath: input.faviconPath }),
373 ...(input.defaultThreadEnvMode === undefined
374 ? {}
375 : { defaultThreadEnvMode: input.defaultThreadEnvMode }),
376 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
377 });
378 if (workspaceRoot !== previousRoot) {
379 yield* projectEnrichment.invalidate([previousRoot, workspaceRoot]);
380 }
381 return yield* readCommitted(input.projectId);
382 },
383 );
384​
385 const bootstrap: ProjectService["Service"]["bootstrap"] = Effect.fn("ProjectService.bootstrap")(
386 function* (input) {
387 const existing = yield* getByWorkspaceRoot(input.workspaceRoot);
388 if (Option.isSome(existing)) return { project: existing.value, created: false };
389 return { project: yield* create(input), created: true };
390 },
391 );
392​
393 const deleteChildThread = Effect.fn("ProjectService.deleteChildThread")(function* (
394 input: ProjectDeleteInput,
395 threadId: ThreadId,
396 ) {
397 yield* legacyImporter.ensureTranscript(threadId);
398 const projection = yield* threadProjections.getThreadRecords(threadId, [
399 "runs",
400 "attempts",
401 "nodes",
402 "runtimeRequests",
403 "subagents",
404 "providerSessions",
405 ]);
406 if (projection.thread.deletedAt !== null || projection.thread.projectId !== input.projectId) {
407 return;
408 }
409 const command = {
410 type: "thread.delete" as const,
411 commandId: CommandId.make(`${input.commandId}:delete-thread:${threadId}`),
412 threadId,
413 };
414 const now = yield* DateTime.now;
415 const plan = yield* planThreadDeletion({
416 command,
417 projection,
418 attachmentIds: yield* threadProjections.getThreadAttachmentIds(threadId),
419 now,
420 idAllocator,
421 });
422 const committed = yield* eventSink.commitCommand({
423 commandId: command.commandId,
424 commandType: command.type,
425 threadId,
426 acceptedAt: now,
427 events: plan.events,
428 effects: plan.effects,
429 });
430 if (
431 committed.receipt.threadId !== command.threadId ||
432 committed.receipt.commandType !== command.type
433 ) {
434 return yield* Effect.fail("The thread deletion command ID belongs to a different command.");
435 }
436 if (committed.receipt.status === "rejected") {
437 return yield* Effect.fail(
438 committed.receipt.error ?? "Thread deletion was previously rejected.",
439 );
440 }
441 });
442​
443 const deleteChildThreads = Effect.fn("ProjectService.deleteChildThreads")(function* (
444 input: ProjectDeleteInput,
445 ) {
446 const { projectId } = input;
447 const snapshot = yield* threadProjections
448 .getShellSnapshot()
449 .pipe(
450 Effect.mapError(
451 (cause) => new ProjectOperationError({ operation: "list-threads", projectId, cause }),
452 ),
453 );
454 const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter(
455 (thread) => thread.projectId === projectId,
456 );
457 if (projectThreads.length > 0 && input.force !== true) {
458 return yield* new ProjectNotEmptyError({ projectId });
459 }
460 // Delete children durably before the project so a failed cascade can be retried.
461 yield* Effect.forEach(
462 projectThreads,
463 (thread) =>
464 threadCommands
465 .withLock(thread.id, deleteChildThread(input, thread.id))
466 .pipe(
467 Effect.mapError(
468 (cause) =>
469 new ProjectOperationError({ operation: "delete-thread", projectId, cause }),
470 ),
471 ),
472 { concurrency: 1, discard: true },
473 );
474 });
475​
476 // Best-effort cleanup releases disabled instances kept alive by overrides; crashes have no replay to revisit deletion.
477 const clearProjectSettingsOverrides = (projectId: ProjectId) =>
478 serverSettings.updateSettings({ projectSettingsOverrides: { [projectId]: null } }).pipe(
479 Effect.asVoid,
480 Effect.catchCause((cause) =>
481 Effect.logWarning(
482 `Failed to clear settings overrides for deleted project ${projectId}.`,
483 cause,
484 ),
485 ),
486 );
487​
488 const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")(
489 function* (input) {
490 const { projectId } = input;
491 // Read deleted rows so retries replay receipts and other command ids fail as not found.
492 const existing = yield* readRow(projectId, { includeDeleted: true });
493 if (Option.isNone(existing)) {
494 return yield* new ProjectNotFoundError({ projectId });
495 }
496​
497 const isFirstDelete = existing.value.deletedAt === null;
498 if (isFirstDelete) {
499 yield* deleteChildThreads(input);
500 }
501 yield* commit({ type: "project.delete", commandId: input.commandId, projectId });
502 if (isFirstDelete) {
503 yield* clearProjectSettingsOverrides(projectId);
504 }
505 yield* projectEnrichment.invalidate([existing.value.workspaceRoot]);
506 return yield* readCommitted(projectId);
507 },
508 );
509​
510 const enrichShell = (shell: OrchestrationProjectShell) =>
511 projectEnrichment.getAvailable(shell.workspaceRoot).pipe(
512 Effect.map((enrichment) => ({
513 ...shell,
514 repositoryIdentity: enrichment.repositoryIdentity,
515 })),
516 );
517​
518 const getShell: ProjectService["Service"]["getShell"] = Effect.fn("ProjectService.getShell")(
519 function* (projectId) {
520 const shell = yield* projects
521 .getShell(projectId)
522 .pipe(
523 Effect.mapError(
524 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
525 ),
526 );
527 return Option.isNone(shell) ? shell : Option.some(yield* enrichShell(shell.value));
528 },
529 );
530​
531 const listShells: ProjectService["Service"]["listShells"] = Effect.fn(
532 "ProjectService.listShells",
533 )(function* (options) {
534 const shells = yield* projects
535 .listShells(options)
536 .pipe(
537 Effect.mapError(
538 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
539 ),
540 );
541 return yield* Effect.forEach(shells, enrichShell, { concurrency: 16 });
542 });
543​
544 const snapshot = Effect.gen(function* () {
545 const rows = yield* projects
546 .list()
547 .pipe(
548 Effect.mapError(
549 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
550 ),
551 );
552 const hydrated = yield* Effect.forEach(rows, hydrate, { concurrency: 8 });
553 return {
554 projects: hydrated,
555 updatedAt: DateTime.formatIso(yield* DateTime.now),
556 } satisfies ProjectSnapshot;
557 });
558​
559 return ProjectService.of({
560 create,
561 bootstrap,
562 update,
563 delete: deleteProject,
564 getById,
565 getByWorkspaceRoot,
566 snapshot,
567 getShell,
568 listShells,
569 });
570});
571​
572export const layer = Layer.effect(ProjectService, make).pipe(
573 Layer.provide(ThreadCommandExecutor.layer),
574);