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

ProjectCommands.ts

226 lines8.0 KB

1import {
2 type CommandId,
3 type EventId,
4 MAX_SCRIPT_ID_LENGTH,
5 type ModelSelection,
6 type ProjectIconOverride,
7 ProjectId,
8 type ProjectScript,
9 SCRIPT_RUN_COMMAND_PATTERN,
10 type ThreadEnvMode,
11} from "@t3tools/contracts";
12import * as DateTime from "effect/DateTime";
13import * as Result from "effect/Result";
14import * as Schema from "effect/Schema";
15​
16import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";
17import type { ProjectRow } from "./ProjectStore.ts";
18​
19export interface ProjectCreateCommand {
20 readonly type: "project.create";
21 readonly commandId: CommandId;
22 readonly projectId: ProjectId;
23 readonly title: string;
24 readonly workspaceRoot: string;
25 readonly scripts?: ReadonlyArray<ProjectScript>;
27​
28export interface ProjectMetaUpdateCommand {
29 readonly type: "project.meta.update";
30 readonly commandId: CommandId;
31 readonly projectId: ProjectId;
32 readonly title?: string;
33 readonly workspaceRoot?: string;
34 readonly defaultModelSelection?: ModelSelection | null;
35 readonly defaultThreadEnvMode?: ThreadEnvMode | null;
36 readonly autoPull?: boolean;
37 readonly faviconPath?: string | null;
38 readonly projectIcon?: ProjectIconOverride | null;
39 readonly scripts?: ReadonlyArray<ProjectScript>;
41​
42export interface ProjectDeleteCommand {
43 readonly type: "project.delete";
44 readonly commandId: CommandId;
45 readonly projectId: ProjectId;
47​
48export type ProjectCommand = ProjectCreateCommand | ProjectMetaUpdateCommand | ProjectDeleteCommand;
49​
50export class ProjectCommandInvariantError extends Schema.TaggedError<ProjectCommandInvariantError>()(
51 "ProjectCommandInvariantError",
52 {
53 commandType: Schema.String,
54 detail: Schema.String,
55 },
56) {
57 override get message(): string {
58 return `Project command invariant failed (${this.commandType}): ${this.detail}`;
59 }
61​
62export class ProjectCommandMissingProjectError extends Schema.TaggedError<ProjectCommandMissingProjectError>()(
63 "ProjectCommandMissingProjectError",
64 {
65 commandType: Schema.String,
66 projectId: ProjectId,
67 },
68) {
69 override get message(): string {
70 return `Project '${this.projectId}' does not exist for command '${this.commandType}'.`;
71 }
73​
74export class ProjectWorkspaceConflictError extends Schema.TaggedError<ProjectWorkspaceConflictError>()(
75 "ProjectWorkspaceConflictError",
76 {
77 workspaceRoot: Schema.String,
78 conflictingProjectId: ProjectId,
79 },
80) {
81 override get message(): string {
82 return `Active project '${this.conflictingProjectId}' already exists for workspace root '${this.workspaceRoot}'.`;
83 }
85​
86export const ProjectCommandRejection = Schema.Union([
87 ProjectCommandInvariantError,
88 ProjectCommandMissingProjectError,
89 ProjectWorkspaceConflictError,
90]);
91export type ProjectCommandRejection = typeof ProjectCommandRejection.Type;
92​
93const ProjectCommandRejectionJson = Schema.fromJsonString(ProjectCommandRejection);
94export const encodeProjectCommandRejection = Schema.encodeSync(ProjectCommandRejectionJson);
95export const decodeProjectCommandRejection = Schema.decodeUnknownOption(
96 ProjectCommandRejectionJson,
97);
98​
99export interface ProjectCommandState {
100 readonly project: ProjectRow | undefined;
101 readonly workspaceOwner: ProjectRow | undefined;
103​
104const monogramSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
105const isScriptRunCommand = Schema.is(SCRIPT_RUN_COMMAND_PATTERN);
106​
107/** Read state and commit the planned event under the project lock. */
108export function planProjectCommand(input: {
109 readonly command: ProjectCommand;
110 readonly state: ProjectCommandState;
111 readonly eventId: EventId;
112 readonly now: DateTime.Utc;
113}): Result.Result<UnsequencedProjectEvent, ProjectCommandRejection> {
114 const { command, state } = input;
115 const invariant = (detail: string) =>
116 Result.fail(new ProjectCommandInvariantError({ commandType: command.type, detail }));
117 const missingProject = () =>
118 Result.fail(
119 new ProjectCommandMissingProjectError({
120 commandType: command.type,
121 projectId: command.projectId,
122 }),
123 );
124 const activeProject = state.project?.deletedAt === null ? state.project : undefined;
125 const requireWorkspaceAvailable = (workspaceRoot: string) =>
126 state.workspaceOwner === undefined || state.workspaceOwner.projectId === command.projectId
127 ? undefined
128 : new ProjectWorkspaceConflictError({
129 workspaceRoot,
130 conflictingProjectId: state.workspaceOwner.projectId,
131 });
132 const occurredAt = DateTime.formatIso(input.now);
133 const base = {
134 eventId: input.eventId,
135 aggregateKind: "project" as const,
136 aggregateId: command.projectId,
137 occurredAt,
138 commandId: command.commandId,
139 causationEventId: null,
140 correlationId: command.commandId,
141 metadata: {},
142 };
143​
144 switch (command.type) {
145 case "project.create": {
146 if (state.project !== undefined) {
147 return invariant(
148 `Project '${command.projectId}' already exists and cannot be created twice.`,
149 );
150 }
151 const conflict = requireWorkspaceAvailable(command.workspaceRoot);
152 if (conflict !== undefined) return Result.fail(conflict);
153 return Result.succeed({
154 ...base,
155 type: "project.created",
156 payload: {
157 projectId: command.projectId,
158 title: command.title,
159 workspaceRoot: command.workspaceRoot,
160 defaultModelSelection: null,
161 faviconPath: null,
162 projectIcon: null,
163 scripts: command.scripts ?? [],
164 createdAt: occurredAt,
165 updatedAt: occurredAt,
166 },
167 });
168 }
169​
170 case "project.meta.update": {
171 const project = activeProject;
172 if (project === undefined) return missingProject();
173 if (
174 command.projectIcon?.kind === "monogram" &&
175 Array.from(monogramSegmenter.segment(command.projectIcon.text)).length > 2
176 ) {
177 return invariant("Project monograms must contain at most two characters.");
178 }
179 if (command.scripts !== undefined) {
180 // Allow editing or removing persisted invalid script ids, while rejecting new invalid ids.
181 const existingIds = new Set(project.scripts.map((script) => script.id));
182 for (const script of command.scripts) {
183 if (!existingIds.has(script.id) && !isScriptRunCommand(`script.${script.id}.run`)) {
184 return invariant(
185 `Script IDs must be 1-${MAX_SCRIPT_ID_LENGTH} lowercase letters, digits or hyphens, starting with a letter or digit (got ${script.id.length} characters).`,
186 );
187 }
188 }
189 }
190 if (command.workspaceRoot !== undefined) {
191 const conflict = requireWorkspaceAvailable(command.workspaceRoot);
192 if (conflict !== undefined) return Result.fail(conflict);
193 }
194 return Result.succeed({
195 ...base,
196 type: "project.meta-updated",
197 payload: {
198 projectId: command.projectId,
199 ...(command.title === undefined ? {} : { title: command.title }),
200 ...(command.workspaceRoot === undefined ? {} : { workspaceRoot: command.workspaceRoot }),
201 ...(command.defaultModelSelection === undefined
202 ? {}
203 : { defaultModelSelection: command.defaultModelSelection }),
204 ...(command.defaultThreadEnvMode === undefined
205 ? {}
206 : { defaultThreadEnvMode: command.defaultThreadEnvMode }),
207 ...(command.autoPull === undefined ? {} : { autoPull: command.autoPull }),
208 ...(command.faviconPath === undefined ? {} : { faviconPath: command.faviconPath }),
209 ...(command.projectIcon === undefined ? {} : { projectIcon: command.projectIcon }),
210 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
211 updatedAt: occurredAt,
212 },
213 });
214 }
215​
216 case "project.delete": {
217 if (activeProject === undefined) return missingProject();
218 // Thread children are deleted by ProjectService before this event commits.
219 return Result.succeed({
220 ...base,
221 type: "project.deleted",
222 payload: { projectId: command.projectId, deletedAt: occurredAt },
223 });
224 }
225 }