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

ProjectCommands.ts

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