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

project.ts

575 lines18.9 KB

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