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

project.ts

607 lines20.4 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/unstable/cli";
21import { FetchHttpClient, HttpClient, HttpClientError } from "effect/unstable/http";
22import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
23​
24import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
25​
26import * as ServerConfig from "../config.ts";
27import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
28import { ProjectServiceLayerLive } 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 * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
34import * as ServerRuntimeStartup from "../serverRuntimeStartup.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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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 ProjectCliRuntimeLive = ProjectServiceLayerLive.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(SqlitePersistenceLayerLive),
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 const exactWorkspaceMatch =
290 normalizedWorkspaceRoot === null
291 ? undefined
292 : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
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 offlineRuntimeLayer = ProjectCliRuntimeLive.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) =>
430 command.type === "project.create"
431 ? projects
432 .create({
433 commandId: command.commandId,
434 projectId: command.projectId,
435 title: command.title,
436 workspaceRoot: command.workspaceRoot,
437 ...(command.defaultModelSelection === undefined
438 ? {}
439 : { defaultModelSelection: command.defaultModelSelection }),
440 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
441 })
442 .pipe(Effect.asVoid)
443 : command.type === "project.update"
444 ? projects
445 .update({
446 commandId: command.commandId,
447 projectId: command.projectId,
448 ...(command.title === undefined ? {} : { title: command.title }),
449 ...(command.workspaceRoot === undefined
450 ? {}
451 : { workspaceRoot: command.workspaceRoot }),
452 ...(command.defaultModelSelection === undefined
453 ? {}
454 : { defaultModelSelection: command.defaultModelSelection }),
455 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
456 })
457 .pipe(Effect.asVoid)
458 : projects
459 .delete({ commandId: command.commandId, projectId: command.projectId })
460 .pipe(Effect.asVoid),
461 mode: "offline",
462 });
463 yield* Console.log(output);
464 }).pipe(Effect.provide(offlineRuntimeLayer));
465 }).pipe(
466 Effect.provide(
467 Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePaths.layer).pipe(
468 Layer.provideMerge(FetchHttpClient.layer),
469 Layer.provide(ServerConfig.layer(config)),
470 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
471 ),
472 ),
473 );
474});
475​
476const projectAddCommand = Command.make("add", {
477 ...projectLocationFlags,
478 workspaceRoot: Argument.string("path").pipe(
479 Argument.withDescription("Workspace root to add as a project."),
480 ),
481 title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
482}).pipe(
483 Command.withDescription("Add a project."),
484 Command.withHandler((flags) =>
485 runProjectMutation(
486 flags,
487 Effect.fn("projectAddMutation")(function* ({
488 snapshot,
489 dispatch,
490 }: {
491 readonly snapshot: ProjectSnapshot;
492 readonly dispatch: (
493 command: ProjectCliDispatchCommand,
494 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
495 }) {
496 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
497 const existingProject = snapshot.projects.find(
498 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
499 );
500 if (existingProject) {
501 return yield* new ProjectAlreadyExistsError({
502 operation: "addProject",
503 projectId: existingProject.id,
504 workspaceRoot,
505 });
506 }
507​
508 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
509 const projectId = ProjectId.make(yield* projectCommandUuid);
510 yield* dispatch({
511 type: "project.create",
512 commandId: CommandId.make(yield* projectCommandUuid),
513 projectId,
514 title,
515 workspaceRoot,
516 defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(),
517 });
518 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
519 }),
520 ),
521 ),
522);
523​
524const projectRemoveCommand = Command.make("remove", {
525 ...projectLocationFlags,
526 project: Argument.string("project").pipe(
527 Argument.withDescription("Project id or workspace root to remove."),
528 ),
529 force: Flag.boolean("force").pipe(
530 Flag.withDescription("Delete the project and all of its threads."),
531 Flag.withDefault(false),
532 ),
533}).pipe(
534 Command.withDescription("Remove a project."),
535 Command.withHandler((flags) =>
536 runProjectMutation(
537 flags,
538 Effect.fn("projectRemoveMutation")(function* ({
539 snapshot,
540 dispatch,
541 }: {
542 readonly snapshot: ProjectSnapshot;
543 readonly dispatch: (
544 command: ProjectCliDispatchCommand,
545 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
546 }) {
547 const project = yield* findActiveProjectTarget({
548 snapshot,
549 identifier: flags.project,
550 });
551 yield* dispatch({
552 type: "project.delete",
553 commandId: CommandId.make(yield* projectCommandUuid),
554 projectId: project.id,
555 force: flags.force,
556 });
557 return `Removed project ${project.id} (${project.title}).`;
558 }),
559 ),
560 ),
561);
562​
563const projectRenameCommand = Command.make("rename", {
564 ...projectLocationFlags,
565 project: Argument.string("project").pipe(
566 Argument.withDescription("Project id or workspace root to rename."),
567 ),
568 title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
569}).pipe(
570 Command.withDescription("Rename a project."),
571 Command.withHandler((flags) =>
572 runProjectMutation(
573 flags,
574 Effect.fn("projectRenameMutation")(function* ({
575 snapshot,
576 dispatch,
577 }: {
578 readonly snapshot: ProjectSnapshot;
579 readonly dispatch: (
580 command: ProjectCliDispatchCommand,
581 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
582 }) {
583 const project = yield* findActiveProjectTarget({
584 snapshot,
585 identifier: flags.project,
586 });
587 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
588 if (nextTitle === project.title) {
589 return `Project ${project.id} is already named ${nextTitle}.`;
590 }
591​
592 yield* dispatch({
593 type: "project.update",
594 commandId: CommandId.make(yield* projectCommandUuid),
595 projectId: project.id,
596 title: nextTitle,
597 });
598 return `Renamed project ${project.id} to ${nextTitle}.`;
599 }),
600 ),
601 ),
602);
603​
604export const projectCommand = Command.make("project").pipe(
605 Command.withDescription("Manage projects."),
606 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
607);