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

project.ts

577 lines19.4 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 { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
34import * as ServerOwnership from "../serverOwnership.ts";
35import * as ProcessRunner from "../processRunner.ts";
36import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
37import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
38​
39type ProjectMutationTarget = {
40 readonly id: ProjectId;
41 readonly title: string;
42 readonly workspaceRoot: string;
43};
44​
45type ProjectCommandExecutionMode = "live" | "offline";
46type ProjectCliDispatchCommand = Extract<
47 ClientOrchestrationCommand,
48 { type: "project.create" | "project.meta.update" | "project.delete" }
49>;
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 ProjectCliRuntimeLive = Layer.mergeAll(
200 WorkspacePaths.layer,
201 OrchestrationLayerLive.pipe(
202 Layer.provideMerge(RepositoryIdentityResolver.layer),
203 Layer.provideMerge(SqlitePersistenceLayerLive),
204 ),
205);
206​
207const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
208const withProjectCliSessionToken = <A, E, R>(
209 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
210 run: (token: string) => Effect.Effect<A, E, R>,
211) =>
212 Effect.acquireUseRelease(
213 environmentAuth.issueSession({
214 scopes: AuthAdministrativeScopes,
215 label: "t3 project cli",
216 }),
217 (issued) => run(issued.token),
218 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
219 );
220​
221const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
222 effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
223​
224const makeLiveServerClient = (origin: string) =>
225 HttpApiClient.make(EnvironmentHttpApi, {
226 baseUrl: origin,
227 });
228​
229const normalizeWorkspaceRootForProjectCommand = Effect.fn(
230 "normalizeWorkspaceRootForProjectCommand",
231)(function* (workspaceRoot: string) {
232 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
233 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
234});
235​
236const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
237 workspaceRoot: string,
238 explicitTitle?: string,
239) {
240 if (explicitTitle !== undefined) {
241 const trimmed = explicitTitle.trim();
242 if (trimmed.length > 0) {
243 return trimmed;
244 }
245 return yield* new ProjectTitleEmptyError({
246 operation: "validateProjectTitle",
247 title: explicitTitle,
248 });
249 }
250​
251 const path = yield* Path.Path;
252 const basename = path.basename(workspaceRoot).trim();
253 return basename.length > 0 ? basename : "project";
254});
255​
256const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
257 readonly snapshot: OrchestrationReadModel;
258 readonly identifier: string;
259}) {
260 const trimmedIdentifier = input.identifier.trim();
261 if (trimmedIdentifier.length === 0) {
262 return yield* new ProjectIdentifierEmptyError({
263 operation: "resolveProjectTarget",
264 identifier: input.identifier,
265 });
266 }
267​
268 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
269 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
270 if (exactIdMatch) {
271 return {
272 id: exactIdMatch.id,
273 title: exactIdMatch.title,
274 workspaceRoot: exactIdMatch.workspaceRoot,
275 } satisfies ProjectMutationTarget;
276 }
277​
278 const normalizedWorkspaceRootResult = yield* Effect.result(
279 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
280 );
281 const normalizedWorkspaceRoot =
282 normalizedWorkspaceRootResult._tag === "Success" ? normalizedWorkspaceRootResult.success : null;
283​
284 // A stored workspace path still identifies its project after the directory is gone.
285 const exactWorkspaceMatch = activeProjects.find(
286 (project) => project.workspaceRoot === (normalizedWorkspaceRoot ?? trimmedIdentifier),
287 );
288​
289 const resolved = exactWorkspaceMatch;
290 if (!resolved) {
291 return yield* new ProjectNotFoundError({
292 operation: "resolveProjectTarget",
293 identifier: trimmedIdentifier,
294 activeProjectCount: activeProjects.length,
295 ...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
296 ...(normalizedWorkspaceRootResult._tag === "Failure"
297 ? { cause: normalizedWorkspaceRootResult.failure }
298 : {}),
299 });
300 }
301​
302 return {
303 id: resolved.id,
304 title: resolved.title,
305 workspaceRoot: resolved.workspaceRoot,
306 } satisfies ProjectMutationTarget;
307});
308​
309const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
310 Effect.gen(function* () {
311 const client = yield* makeLiveServerClient(origin);
312 return yield* client.orchestration.snapshot({
313 headers: { authorization: `Bearer ${bearerToken}` },
314 });
315 }).pipe(
316 withProjectCliLiveServerTimeout,
317 Effect.mapError(projectCommandErrorFromLiveServerRequest),
318 );
319​
320const dispatchLiveOrchestrationCommand = (
321 origin: string,
322 bearerToken: string,
323 command: ProjectCliDispatchCommand,
324) =>
325 Effect.gen(function* () {
326 const client = yield* makeLiveServerClient(origin);
327 yield* client.orchestration.dispatch({
328 headers: { authorization: `Bearer ${bearerToken}` },
329 payload: command,
330 } as Parameters<typeof client.orchestration.dispatch>[0]);
331 }).pipe(
332 withProjectCliLiveServerTimeout,
333 Effect.mapError(projectCommandErrorFromLiveServerRequest),
334 );
335​
336const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
337 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
338 // Project commands only read the project list, so use the lightweight
339 // command read model instead of hydrating every thread body in the database.
340 return yield* projectionSnapshotQuery.getCommandReadModel();
341});
342​
343const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
344 function* (
345 environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
346 config: ServerConfig.ServerConfig["Service"],
347 ) {
348 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
349 if (Option.isNone(runtimeState) || !isProcessAlive(runtimeState.value.pid)) {
350 return Option.none<{ readonly origin: string }>();
351 }
352​
353 const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
354 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
355 Effect.as({
356 origin: runtimeState.value.origin,
357 }),
358 ),
359 );
360​
361 const attempted = yield* Effect.result(attempt);
362 if (attempted._tag === "Success") {
363 return Option.some(attempted.success);
364 }
365​
366 yield* Effect.logDebug("Failed to connect to the persisted project CLI server.", {
367 origin: runtimeState.value.origin,
368 cause: attempted.failure,
369 });
370 return Option.none<{ readonly origin: string }>();
371 },
372);
373​
374const runProjectMutation = Effect.fn("runProjectMutation")(function* (
375 flags: CliAuthLocationFlags,
376 run: (input: {
377 readonly snapshot: OrchestrationReadModel;
378 readonly dispatch: (
379 command: ProjectCliDispatchCommand,
380 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
381 readonly mode: ProjectCommandExecutionMode;
382 }) => Effect.Effect<
383 string,
384 Error,
385 | Crypto.Crypto
386 | FileSystem.FileSystem
387 | HttpClient.HttpClient
388 | Path.Path
389 | WorkspacePaths.WorkspacePaths
390 >,
391) {
392 const logLevel = yield* GlobalFlag.LogLevel;
393 const config = yield* resolveCliAuthConfig(flags, logLevel);
394 const minimumLogLevel = config.logLevel;
395​
396 return yield* Effect.gen(function* () {
397 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
398 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
399​
400 if (Option.isSome(liveMode)) {
401 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
402 Effect.gen(function* () {
403 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
404 const output = yield* run({
405 snapshot,
406 dispatch: (command) =>
407 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
408 mode: "live",
409 });
410 yield* Console.log(output);
411 }),
412 );
413 }
414​
415 // A failed request is not proof the server stopped. Claim ownership before
416 // building the offline command model or writing to the shared event store.
417 yield* ServerOwnership.acquireServerOwnership(config.serverRuntimeStatePath);
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.scoped,
435 Effect.provide(
436 Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePaths.layer).pipe(
437 Layer.provideMerge(ProcessRunner.layer),
438 Layer.provideMerge(FetchHttpClient.layer),
439 Layer.provide(ServerConfig.layer(config)),
440 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
441 ),
442 ),
443 );
444});
445​
446const projectAddCommand = Command.make("add", {
447 ...projectLocationFlags,
448 workspaceRoot: Argument.String("path").pipe(
449 Argument.withDescription("Workspace root to add as a project."),
450 ),
451 title: Flag.String("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
452}).pipe(
453 Command.withDescription("Add a project."),
454 Command.withHandler((flags) =>
455 runProjectMutation(
456 flags,
457 Effect.fn("projectAddMutation")(function* ({
458 snapshot,
459 dispatch,
460 }: {
461 readonly snapshot: OrchestrationReadModel;
462 readonly dispatch: (
463 command: ProjectCliDispatchCommand,
464 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
465 }) {
466 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
467 const existingProject = snapshot.projects.find(
468 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
469 );
470 if (existingProject) {
471 return yield* new ProjectAlreadyExistsError({
472 operation: "addProject",
473 projectId: existingProject.id,
474 workspaceRoot,
475 });
476 }
477​
478 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
479 const projectId = ProjectId.make(yield* projectCommandUuid);
480 yield* dispatch({
481 type: "project.create",
482 commandId: CommandId.make(yield* projectCommandUuid),
483 projectId,
484 title,
485 workspaceRoot,
486 createdAt: DateTime.formatIso(yield* DateTime.now),
487 });
488 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
489 }),
490 ),
491 ),
492);
493​
494const projectRemoveCommand = Command.make("remove", {
495 ...projectLocationFlags,
496 project: Argument.String("project").pipe(
497 Argument.withDescription("Project id or workspace root to remove."),
498 ),
499 force: Flag.Boolean("force").pipe(
500 Flag.withDescription("Delete the project and all of its threads."),
501 Flag.withDefault(false),
502 ),
503}).pipe(
504 Command.withDescription("Remove a project."),
505 Command.withHandler((flags) =>
506 runProjectMutation(
507 flags,
508 Effect.fn("projectRemoveMutation")(function* ({
509 snapshot,
510 dispatch,
511 }: {
512 readonly snapshot: OrchestrationReadModel;
513 readonly dispatch: (
514 command: ProjectCliDispatchCommand,
515 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
516 }) {
517 const project = yield* findActiveProjectTarget({
518 snapshot,
519 identifier: flags.project,
520 });
521 yield* dispatch({
522 type: "project.delete",
523 commandId: CommandId.make(yield* projectCommandUuid),
524 projectId: project.id,
525 force: flags.force,
526 });
527 return `Removed project ${project.id} (${project.title}).`;
528 }),
529 ),
530 ),
531);
532​
533const projectRenameCommand = Command.make("rename", {
534 ...projectLocationFlags,
535 project: Argument.String("project").pipe(
536 Argument.withDescription("Project id or workspace root to rename."),
537 ),
538 title: Argument.String("title").pipe(Argument.withDescription("New project title.")),
539}).pipe(
540 Command.withDescription("Rename a project."),
541 Command.withHandler((flags) =>
542 runProjectMutation(
543 flags,
544 Effect.fn("projectRenameMutation")(function* ({
545 snapshot,
546 dispatch,
547 }: {
548 readonly snapshot: OrchestrationReadModel;
549 readonly dispatch: (
550 command: ProjectCliDispatchCommand,
551 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
552 }) {
553 const project = yield* findActiveProjectTarget({
554 snapshot,
555 identifier: flags.project,
556 });
557 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
558 if (nextTitle === project.title) {
559 return `Project ${project.id} is already named ${nextTitle}.`;
560 }
561​
562 yield* dispatch({
563 type: "project.meta.update",
564 commandId: CommandId.make(yield* projectCommandUuid),
565 projectId: project.id,
566 title: nextTitle,
567 });
568 return `Renamed project ${project.id} to ${nextTitle}.`;
569 }),
570 ),
571 ),
572);
573​
574export const projectCommand = Command.make("project").pipe(
575 Command.withDescription("Manage projects."),
576 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
577);