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

project.ts

495 lines16.7 KB

1import {
2 AuthStandardClientScopes,
3 CommandId,
4 EnvironmentHttpCommonError,
5 type ProjectMutation,
6 type ProjectSnapshot,
7 ProjectId,
8} from "@t3tools/contracts";
9import * as Console from "effect/Console";
10import * as SecureRandom from "effect/crypto/SecureRandom";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as References from "effect/References";
17import * as Schema from "effect/Schema";
18import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
19import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
20​
21import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
22import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
23​
24import * as ServerConfig from "../config.ts";
25import * as SqlitePersistence from "../persistence/Sqlite.ts";
26import type * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts";
27import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
28import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
29import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
30import * as ProjectService from "../project/ProjectService.ts";
31import { projectMutationOperation } from "../project/ProjectMutation.ts";
32import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
35import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
36import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
37import * as RunningServer from "./runningServer.ts";
38​
39type ProjectMutationTarget = {
40 readonly id: ProjectId;
41 readonly title: string;
42 readonly workspaceRoot: string;
43};
44​
45type ProjectCliDispatchCommand = ProjectMutation;
46​
47const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
48​
49export class ProjectCommandIdGenerationError extends Schema.TaggedError<ProjectCommandIdGenerationError>()(
50 "ProjectCommandIdGenerationError",
51 {
52 operation: Schema.Literal("generateProjectCommandId"),
53 cause: Schema.Defect(),
54 },
55) {
56 override get message(): string {
57 return "Failed to generate a project command identifier.";
58 }
60​
61export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedError<ProjectLiveServerDeclaredResponseError>()(
62 "ProjectLiveServerDeclaredResponseError",
63 {
64 operation: Schema.Literal("callLiveServer"),
65 code: Schema.String,
66 traceId: Schema.String,
67 cause: Schema.Defect(),
68 },
69) {
70 override get message(): string {
71 return `Server request failed (${this.code}, trace ${this.traceId}).`;
72 }
74​
75export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedError<ProjectLiveServerUndeclaredStatusError>()(
76 "ProjectLiveServerUndeclaredStatusError",
77 {
78 operation: Schema.Literal("callLiveServer"),
79 status: Schema.Int,
80 cause: Schema.Defect(),
81 },
82) {
83 override get message(): string {
84 return `Server request failed with undeclared status ${this.status}.`;
85 }
87​
88export class ProjectTitleEmptyError extends Schema.TaggedError<ProjectTitleEmptyError>()(
89 "ProjectTitleEmptyError",
90 {
91 operation: Schema.Literal("validateProjectTitle"),
92 title: Schema.String,
93 },
94) {
95 override get message(): string {
96 return "Project title cannot be empty.";
97 }
99​
100export class ProjectIdentifierEmptyError extends Schema.TaggedError<ProjectIdentifierEmptyError>()(
101 "ProjectIdentifierEmptyError",
102 {
103 operation: Schema.Literal("resolveProjectTarget"),
104 identifier: Schema.String,
105 },
106) {
107 override get message(): string {
108 return "Project identifier cannot be empty.";
109 }
111​
112export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
113 "ProjectNotFoundError",
114 {
115 operation: Schema.Literal("resolveProjectTarget"),
116 identifier: Schema.String,
117 normalizedWorkspaceRoot: Schema.optional(Schema.String),
118 activeProjectCount: Schema.Number,
119 cause: Schema.optional(Schema.Defect()),
120 },
121) {
122 override get message(): string {
123 return `No active project found for '${this.identifier}'.`;
124 }
126​
127export class ProjectAlreadyExistsError extends Schema.TaggedError<ProjectAlreadyExistsError>()(
128 "ProjectAlreadyExistsError",
129 {
130 operation: Schema.Literal("addProject"),
131 projectId: ProjectId,
132 workspaceRoot: Schema.String,
133 },
134) {
135 override get message(): string {
136 return `An active project already exists for '${this.workspaceRoot}'.`;
137 }
139​
140export const ProjectCommandError = Schema.Union([
141 ProjectCommandIdGenerationError,
142 ProjectLiveServerDeclaredResponseError,
143 ProjectLiveServerUndeclaredStatusError,
144 ProjectTitleEmptyError,
145 ProjectIdentifierEmptyError,
146 ProjectNotFoundError,
147 ProjectAlreadyExistsError,
148]);
149export type ProjectCommandError = typeof ProjectCommandError.Type;
150​
151/** Names a server's error answer; unanswered requests pass through for `changeState`. */
152function projectCommandErrorFromServerAnswer<E>(cause: E) {
153 if (isEnvironmentHttpCommonError(cause)) {
154 return new ProjectLiveServerDeclaredResponseError({
155 operation: "callLiveServer",
156 code: cause.code,
157 traceId: cause.traceId,
158 cause,
159 });
160 }
161 if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
162 return new ProjectLiveServerUndeclaredStatusError({
163 operation: "callLiveServer",
164 status: cause.response.status,
165 cause,
166 });
167 }
168 return cause;
170​
171const projectCommandUuid = SecureRandom.SecureRandom.pipe(
172 Effect.flatMap((random) => random.uuidV4()),
173 Effect.mapError(
174 (cause) =>
175 new ProjectCommandIdGenerationError({
176 operation: "generateProjectCommandId",
177 cause,
178 }),
179 ),
180);
181​
182const makeProjectCliRuntimeLayer = (layerProjectService: typeof RuntimeLayer.layerProjectService) =>
183 layerProjectService.pipe(
184 Layer.provideMerge(ProjectEnrichmentService.layer),
185 Layer.provideMerge(RepositoryIdentityResolver.layer),
186 Layer.provideMerge(
187 ProjectFaviconResolver.layer.pipe(
188 Layer.provide(WorkspacePaths.layer),
189 Layer.provide(T3ProjectFileLoader.layer),
190 ),
191 ),
192 Layer.provideMerge(WorkspacePaths.layer),
193 Layer.provideMerge(
194 ServerSettings.layer.pipe(
195 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)),
196 ),
197 ),
198 // Built after acquireServerOwnership; layerCliConfig would contend with this process's own lock.
199 Layer.provideMerge(SqlitePersistence.layerConfig),
200 );
201​
202const normalizeWorkspaceRootForProjectCommand = Effect.fn(
203 "normalizeWorkspaceRootForProjectCommand",
204)(function* (workspaceRoot: string) {
205 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
206 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
207});
208​
209const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
210 workspaceRoot: string,
211 explicitTitle?: string,
212) {
213 if (explicitTitle !== undefined) {
214 const trimmed = explicitTitle.trim();
215 if (trimmed.length > 0) {
216 return trimmed;
217 }
218 return yield* new ProjectTitleEmptyError({
219 operation: "validateProjectTitle",
220 title: explicitTitle,
221 });
222 }
223​
224 const path = yield* Path.Path;
225 const basename = path.basename(workspaceRoot).trim();
226 return basename.length > 0 ? basename : "project";
227});
228​
229const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
230 readonly snapshot: ProjectSnapshot;
231 readonly identifier: string;
232}) {
233 const trimmedIdentifier = input.identifier.trim();
234 if (trimmedIdentifier.length === 0) {
235 return yield* new ProjectIdentifierEmptyError({
236 operation: "resolveProjectTarget",
237 identifier: input.identifier,
238 });
239 }
240​
241 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
242 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
243 if (exactIdMatch) {
244 return {
245 id: exactIdMatch.id,
246 title: exactIdMatch.title,
247 workspaceRoot: exactIdMatch.workspaceRoot,
248 } satisfies ProjectMutationTarget;
249 }
250​
251 const normalizedWorkspaceRootResult = yield* Effect.result(
252 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
253 );
254 // A stored workspace path still identifies its project after the directory is gone, so a
255 // relative or trailing-slash path resolves the same way it would while the directory exists.
256 const normalizedWorkspaceRoot =
257 normalizedWorkspaceRootResult._tag === "Success"
258 ? normalizedWorkspaceRootResult.success
259 : normalizedWorkspaceRootResult.failure.normalizedWorkspaceRoot;
260​
261 const exactWorkspaceMatch = activeProjects.find(
262 (project) => project.workspaceRoot === normalizedWorkspaceRoot,
263 );
264​
265 const resolved = exactWorkspaceMatch;
266 if (!resolved) {
267 return yield* new ProjectNotFoundError({
268 operation: "resolveProjectTarget",
269 identifier: trimmedIdentifier,
270 activeProjectCount: activeProjects.length,
271 normalizedWorkspaceRoot,
272 ...(normalizedWorkspaceRootResult._tag === "Failure"
273 ? { cause: normalizedWorkspaceRootResult.failure }
274 : {}),
275 });
276 }
277​
278 return {
279 id: resolved.id,
280 title: resolved.title,
281 workspaceRoot: resolved.workspaceRoot,
282 } satisfies ProjectMutationTarget;
283});
284​
285const runProjectMutation = Effect.fn("runProjectMutation")(function* (
286 flags: CliAuthLocationFlags,
287 run: (input: {
288 readonly snapshot: ProjectSnapshot;
289 readonly dispatch: (
290 command: ProjectCliDispatchCommand,
291 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
292 }) => Effect.Effect<
293 string,
294 Error,
295 | SecureRandom.SecureRandom
296 | FileSystem.FileSystem
297 | HttpClient.HttpClient
298 | Path.Path
299 | WorkspacePaths.WorkspacePaths
300 >,
301) {
302 const logLevel = yield* GlobalFlag.LogLevel;
303 const config = yield* resolveCliAuthConfig(flags, logLevel);
304 const minimumLogLevel = config.logLevel;
305​
306 return yield* Effect.gen(function* () {
307 const output = yield* RunningServer.changeState({
308 scopes: AuthStandardClientScopes,
309 viaServer: Effect.fn("project.viaServer")(function* (client) {
310 return yield* run({
311 snapshot: yield* client.projects.snapshot({ headers: {} }),
312 dispatch: (command) =>
313 client.projects.mutate({ headers: {}, payload: command } as Parameters<
314 typeof client.projects.mutate
315 >[0]),
316 });
317 }, Effect.mapError(projectCommandErrorFromServerAnswer)),
318 locally: Effect.promise(() => import("../orchestration-v2/runtimeLayer.ts")).pipe(
319 Effect.flatMap(({ layerProjectService }) =>
320 Effect.gen(function* () {
321 const projects = yield* ProjectService.ProjectService;
322 return yield* run({
323 snapshot: yield* projects.snapshot,
324 dispatch: (command) =>
325 projectMutationOperation(projects, command).pipe(Effect.asVoid),
326 });
327 }).pipe(
328 Effect.provide(
329 makeProjectCliRuntimeLayer(layerProjectService).pipe(
330 Layer.provide(ServerConfig.layer(config)),
331 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
332 ),
333 ),
334 ),
335 ),
336 ),
337 });
338 yield* Console.log(output);
339 }).pipe(
340 Effect.scoped,
341 Effect.provide(
342 Layer.mergeAll(EnvironmentAuth.layerRuntime, WorkspacePaths.layer).pipe(
343 Layer.provideMerge(FetchHttpClient.layer),
344 Layer.provideMerge(ServerConfig.layer(config)),
345 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
346 ),
347 ),
348 );
349});
350​
351const projectAddCommand = Command.make("add", {
352 ...projectLocationFlags,
353 workspaceRoot: Argument.String("path").pipe(
354 Argument.withDescription("Workspace root to add as a project."),
355 ),
356 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
357}).pipe(
358 Command.withDescription("Add a project."),
359 Command.withHandler((flags) =>
360 runProjectMutation(
361 flags,
362 Effect.fn("projectAddMutation")(function* ({
363 snapshot,
364 dispatch,
365 }: {
366 readonly snapshot: ProjectSnapshot;
367 readonly dispatch: (
368 command: ProjectCliDispatchCommand,
369 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
370 }) {
371 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
372 const existingProject = snapshot.projects.find(
373 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
374 );
375 // Re-adding an archived project's folder restores it, matching the clients.
376 if (existingProject?.archivedAt != null) {
377 const title = Option.isSome(flags.title)
378 ? yield* resolveProjectTitle(workspaceRoot, flags.title.value)
379 : undefined;
380 yield* dispatch({
381 type: "project.update",
382 commandId: CommandId.make(yield* projectCommandUuid),
383 projectId: existingProject.id,
384 archived: false,
385 ...(title === undefined ? {} : { title }),
386 });
387 return `Unarchived project ${existingProject.id} (${title ?? existingProject.title}) at ${workspaceRoot}.`;
388 }
389 if (existingProject) {
390 return yield* new ProjectAlreadyExistsError({
391 operation: "addProject",
392 projectId: existingProject.id,
393 workspaceRoot,
394 });
395 }
396​
397 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
398 const projectId = ProjectId.make(yield* projectCommandUuid);
399 yield* dispatch({
400 type: "project.create",
401 commandId: CommandId.make(yield* projectCommandUuid),
402 projectId,
403 title,
404 workspaceRoot,
405 });
406 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
407 }),
408 ),
409 ),
410);
411​
412const projectRemoveCommand = Command.make("remove", {
413 ...projectLocationFlags,
414 project: Argument.String("project").pipe(
415 Argument.withDescription("Project id or workspace root to remove."),
416 ),
417 force: Flag.Boolean("force").pipe(
418 Flag.withDescription("Delete the project and all of its threads."),
419 Flag.withDefault(false),
420 ),
421}).pipe(
422 Command.withDescription("Remove a project."),
423 Command.withHandler((flags) =>
424 runProjectMutation(
425 flags,
426 Effect.fn("projectRemoveMutation")(function* ({
427 snapshot,
428 dispatch,
429 }: {
430 readonly snapshot: ProjectSnapshot;
431 readonly dispatch: (
432 command: ProjectCliDispatchCommand,
433 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
434 }) {
435 const project = yield* findActiveProjectTarget({
436 snapshot,
437 identifier: flags.project,
438 });
439 yield* dispatch({
440 type: "project.delete",
441 commandId: CommandId.make(yield* projectCommandUuid),
442 projectId: project.id,
443 force: flags.force,
444 });
445 return `Removed project ${project.id} (${project.title}).`;
446 }),
447 ),
448 ),
449);
450​
451const projectRenameCommand = Command.make("rename", {
452 ...projectLocationFlags,
453 project: Argument.String("project").pipe(
454 Argument.withDescription("Project id or workspace root to rename."),
455 ),
456 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
457}).pipe(
458 Command.withDescription("Rename a project."),
459 Command.withHandler((flags) =>
460 runProjectMutation(
461 flags,
462 Effect.fn("projectRenameMutation")(function* ({
463 snapshot,
464 dispatch,
465 }: {
466 readonly snapshot: ProjectSnapshot;
467 readonly dispatch: (
468 command: ProjectCliDispatchCommand,
469 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
470 }) {
471 const project = yield* findActiveProjectTarget({
472 snapshot,
473 identifier: flags.project,
474 });
475 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
476 if (nextTitle === project.title) {
477 return `Project ${project.id} is already named ${nextTitle}.`;
478 }
479​
480 yield* dispatch({
481 type: "project.update",
482 commandId: CommandId.make(yield* projectCommandUuid),
483 projectId: project.id,
484 title: nextTitle,
485 });
486 return `Renamed project ${project.id} to ${nextTitle}.`;
487 }),
488 ),
489 ),
490);
491​
492export const projectCommand = Command.make("project").pipe(
493 Command.withDescription("Manage projects."),
494 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
495);