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

ProjectCommands.ts

246 lines9.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 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 occurredAt = DateTime.formatIso(input.now);
140 const base = {
141 eventId: input.eventId,
142 aggregateKind: "project" as const,
143 aggregateId: command.projectId,
144 occurredAt,
145 commandId: command.commandId,
146 causationEventId: null,
147 correlationId: command.commandId,
148 metadata: {},
149 };
150​
151 switch (command.type) {
152 case "project.create": {
153 if (state.project !== undefined) {
154 return invariant(
155 `Project '${command.projectId}' already exists and cannot be created twice.`,
156 );
157 }
158 const conflict = requireWorkspaceAvailable(command.workspaceRoot);
159 if (conflict !== undefined) return Result.fail(conflict);
160 return Result.succeed({
161 ...base,
162 type: "project.created",
163 payload: {
164 projectId: command.projectId,
165 title: command.title,
166 workspaceRoot: command.workspaceRoot,
167 defaultModelSelection: command.defaultModelSelection ?? null,
168 faviconPath: null,
169 projectIcon: null,
170 scripts: command.scripts ?? [],
171 ...(command.trackedFolders === undefined || command.trackedFolders.length === 0
172 ? {}
173 : { trackedFolders: command.trackedFolders }),
174 createdAt: occurredAt,
175 updatedAt: occurredAt,
176 },
177 });
178 }
179​
180 case "project.meta.update": {
181 const project = activeProject;
182 if (project === undefined) return missingProject();
183 if (
184 command.projectIcon?.kind === "monogram" &&
185 countProjectMonogramGraphemes(command.projectIcon.text, monogramSegmenter) > 2
186 ) {
187 return invariant("Project monograms must contain at most two characters.");
188 }
189 if (command.scripts !== undefined) {
190 // Allow editing or removing persisted invalid script ids, while rejecting new invalid ids.
191 const existingIds = new Set(project.scripts.map((script) => script.id));
192 for (const script of command.scripts) {
193 if (!existingIds.has(script.id) && !isScriptRunCommand(`script.${script.id}.run`)) {
194 return invariant(
195 `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).`,
196 );
197 }
198 }
199 }
200 if (command.workspaceRoot !== undefined) {
201 const conflict = requireWorkspaceAvailable(command.workspaceRoot);
202 if (conflict !== undefined) return Result.fail(conflict);
203 }
204 return Result.succeed({
205 ...base,
206 type: "project.meta-updated",
207 payload: {
208 projectId: command.projectId,
209 ...(command.title === undefined ? {} : { title: command.title }),
210 ...(command.workspaceRoot === undefined ? {} : { workspaceRoot: command.workspaceRoot }),
211 ...(command.defaultModelSelection === undefined
212 ? {}
213 : { defaultModelSelection: command.defaultModelSelection }),
214 ...(command.defaultThreadEnvMode === undefined
215 ? {}
216 : { defaultThreadEnvMode: command.defaultThreadEnvMode }),
217 ...(command.autoPull === undefined ? {} : { autoPull: command.autoPull }),
218 ...(command.faviconPath === undefined ? {} : { faviconPath: command.faviconPath }),
219 ...(command.projectIcon === undefined ? {} : { projectIcon: command.projectIcon }),
220 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
221 ...(command.trackedFolders === undefined
222 ? {}
223 : { trackedFolders: command.trackedFolders }),
224 // Repeating a pin or archive keeps the original time.
225 ...(command.pinned === undefined
226 ? {}
227 : { pinnedAt: command.pinned ? (project.pinnedAt ?? occurredAt) : null }),
228 ...(command.archived === undefined
229 ? {}
230 : { archivedAt: command.archived ? (project.archivedAt ?? occurredAt) : null }),
231 updatedAt: occurredAt,
232 },
233 });
234 }
235​
236 case "project.delete": {
237 if (activeProject === undefined) return missingProject();
238 // Thread children are deleted by ProjectService before this event commits.
239 return Result.succeed({
240 ...base,
241 type: "project.deleted",
242 payload: { projectId: command.projectId, deletedAt: occurredAt },
243 });
244 }
245 }