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

project.ts

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