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

project.ts

567 lines20.0 KB

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