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

project.ts

576 lines19.2 KB

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