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

project.ts

431 lines15.1 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 Data from "effect/Data";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import * as References from "effect/References";
22import * as Schema from "effect/Schema";
23import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
24import { FetchHttpClient, HttpClient, HttpClientError } from "effect/unstable/http";
25import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
26​
27import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
28​
29import { ServerConfig, type ServerConfigShape } from "../config.ts";
30import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
31import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
32import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
33import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
34import { RepositoryIdentityResolverLive } from "../project/Layers/RepositoryIdentityResolver.ts";
35import { getAutoBootstrapDefaultModelSelection } from "../serverRuntimeStartup.ts";
36import {
37 clearPersistedServerRuntimeState,
38 readPersistedServerRuntimeState,
39} from "../serverRuntimeState.ts";
40import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
41import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
42import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
43​
44type ProjectMutationTarget = {
45 readonly id: ProjectId;
46 readonly title: string;
47 readonly workspaceRoot: string;
48};
49​
50type ProjectCommandExecutionMode = "live" | "offline";
51type ProjectCliDispatchCommand = Extract<
52 ClientOrchestrationCommand,
53 { type: "project.create" | "project.meta.update" | "project.delete" }
54>;
55​
56class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
57 readonly message: string;
58}> {}
59​
60const projectCommandUuid = Crypto.Crypto.pipe(
61 Effect.flatMap((crypto) => crypto.randomUUIDv4),
62 Effect.mapError(
63 () =>
64 new ProjectCommandError({
65 message: "Failed to generate a project command identifier.",
66 }),
67 ),
68);
69​
70const ProjectCliRuntimeLive = Layer.mergeAll(
71 WorkspacePathsLive,
72 OrchestrationLayerLive.pipe(
73 Layer.provideMerge(RepositoryIdentityResolverLive),
74 Layer.provideMerge(SqlitePersistenceLayerLive),
75 ),
76);
77​
78const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
79const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
80const withProjectCliSessionToken = <A, E, R>(
81 environmentAuth: EnvironmentAuth.EnvironmentAuthShape,
82 run: (token: string) => Effect.Effect<A, E, R>,
83) =>
84 Effect.acquireUseRelease(
85 environmentAuth.issueSession({
86 scopes: AuthAdministrativeScopes,
87 label: "t3 project cli",
88 }),
89 (issued) => run(issued.token),
90 (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
91 );
92​
93const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
94 effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
95​
96const failLiveServerRequest = (cause: unknown) => {
97 if (isEnvironmentHttpCommonError(cause)) {
98 return Effect.fail(
99 new ProjectCommandError({
100 message: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
101 }),
102 );
103 }
104 if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
105 return Effect.fail(
106 new ProjectCommandError({
107 message: `Server request failed with undeclared status ${cause.response.status}.`,
108 }),
109 );
110 }
111 return Effect.fail(
112 new ProjectCommandError({
113 message: `Failed to call running server: ${String(cause)}.`,
114 }),
115 );
116};
117​
118const makeLiveServerClient = (origin: string) =>
119 HttpApiClient.make(EnvironmentHttpApi, {
120 baseUrl: origin,
121 });
122​
123const normalizeWorkspaceRootForProjectCommand = Effect.fn(
124 "normalizeWorkspaceRootForProjectCommand",
125)(function* (workspaceRoot: string) {
126 const workspacePaths = yield* WorkspacePaths;
127 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
128});
129​
130const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
131 workspaceRoot: string,
132 explicitTitle?: string,
133) {
134 if (explicitTitle !== undefined) {
135 const trimmed = explicitTitle.trim();
136 if (trimmed.length > 0) {
137 return trimmed;
138 }
139 return yield* new ProjectCommandError({ message: "Project title cannot be empty." });
140 }
141​
142 const path = yield* Path.Path;
143 const basename = path.basename(workspaceRoot).trim();
144 return basename.length > 0 ? basename : "project";
145});
146​
147const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
148 readonly snapshot: OrchestrationReadModel;
149 readonly identifier: string;
150}) {
151 const trimmedIdentifier = input.identifier.trim();
152 if (trimmedIdentifier.length === 0) {
153 return yield* new ProjectCommandError({ message: "Project identifier cannot be empty." });
154 }
155​
156 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
157 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
158 if (exactIdMatch) {
159 return {
160 id: exactIdMatch.id,
161 title: exactIdMatch.title,
162 workspaceRoot: exactIdMatch.workspaceRoot,
163 } satisfies ProjectMutationTarget;
164 }
165​
166 const normalizedWorkspaceRootResult = yield* Effect.exit(
167 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
168 );
169 const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
170 ? normalizedWorkspaceRootResult.value
171 : null;
172​
173 const exactWorkspaceMatch =
174 normalizedWorkspaceRoot === null
175 ? undefined
176 : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
177​
178 const resolved = exactWorkspaceMatch;
179 if (!resolved) {
180 return yield* new ProjectCommandError({
181 message: `No active project found for '${trimmedIdentifier}'.`,
182 });
183 }
184​
185 return {
186 id: resolved.id,
187 title: resolved.title,
188 workspaceRoot: resolved.workspaceRoot,
189 } satisfies ProjectMutationTarget;
190});
191​
192const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
193 Effect.gen(function* () {
194 const client = yield* makeLiveServerClient(origin);
195 return yield* client.orchestration.snapshot({
196 headers: { authorization: `Bearer ${bearerToken}` },
197 });
198 }).pipe(withProjectCliLiveServerTimeout, Effect.catch(failLiveServerRequest));
199​
200const dispatchLiveOrchestrationCommand = (
201 origin: string,
202 bearerToken: string,
203 command: ProjectCliDispatchCommand,
204) =>
205 Effect.gen(function* () {
206 const client = yield* makeLiveServerClient(origin);
207 yield* client.orchestration.dispatch({
208 headers: { authorization: `Bearer ${bearerToken}` },
209 payload: command,
210 } as Parameters<typeof client.orchestration.dispatch>[0]);
211 }).pipe(withProjectCliLiveServerTimeout, Effect.catch(failLiveServerRequest));
212​
213const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
214 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
215 return yield* projectionSnapshotQuery.getSnapshot();
216});
217​
218const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
219 function* (environmentAuth: EnvironmentAuth.EnvironmentAuthShape, config: ServerConfigShape) {
220 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
221 if (Option.isNone(runtimeState)) {
222 return Option.none<{ readonly origin: string }>();
223 }
224​
225 const attempt = withProjectCliSessionToken(environmentAuth, (token) =>
226 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
227 Effect.as({
228 origin: runtimeState.value.origin,
229 }),
230 ),
231 );
232​
233 const attempted = yield* Effect.exit(attempt);
234 if (Exit.isSuccess(attempted)) {
235 return Option.some(attempted.value);
236 }
237​
238 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
239 return Option.none<{ readonly origin: string }>();
240 },
241);
242​
243const runProjectMutation = Effect.fn("runProjectMutation")(function* (
244 flags: CliAuthLocationFlags,
245 run: (input: {
246 readonly snapshot: OrchestrationReadModel;
247 readonly dispatch: (
248 command: ProjectCliDispatchCommand,
249 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
250 readonly mode: ProjectCommandExecutionMode;
251 }) => Effect.Effect<
252 string,
253 Error,
254 Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
255 >,
256) {
257 const logLevel = yield* GlobalFlag.LogLevel;
258 const config = yield* resolveCliAuthConfig(flags, logLevel);
259 const minimumLogLevel = config.logLevel;
260​
261 return yield* Effect.gen(function* () {
262 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
263 const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);
264​
265 if (Option.isSome(liveMode)) {
266 return yield* withProjectCliSessionToken(environmentAuth, (token) =>
267 Effect.gen(function* () {
268 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
269 const output = yield* run({
270 snapshot,
271 dispatch: (command) =>
272 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
273 mode: "live",
274 });
275 yield* Console.log(output);
276 }),
277 );
278 }
279​
280 const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
281 Layer.provide(Layer.succeed(ServerConfig, config)),
282 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
283 );
284​
285 return yield* Effect.gen(function* () {
286 const snapshot = yield* getOfflineSnapshot();
287 const orchestrationEngine = yield* OrchestrationEngineService;
288 const output = yield* run({
289 snapshot,
290 dispatch: (command) => orchestrationEngine.dispatch(command),
291 mode: "offline",
292 });
293 yield* Console.log(output);
294 }).pipe(Effect.provide(offlineRuntimeLayer));
295 }).pipe(
296 Effect.provide(
297 Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePathsLive).pipe(
298 Layer.provideMerge(FetchHttpClient.layer),
299 Layer.provide(Layer.succeed(ServerConfig, config)),
300 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
301 ),
302 ),
303 );
304});
305​
306const projectAddCommand = Command.make("add", {
307 ...projectLocationFlags,
308 workspaceRoot: Argument.string("path").pipe(
309 Argument.withDescription("Workspace root to add as a project."),
310 ),
311 title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
312}).pipe(
313 Command.withDescription("Add a project."),
314 Command.withHandler((flags) =>
315 runProjectMutation(
316 flags,
317 Effect.fn("projectAddMutation")(function* ({
318 snapshot,
319 dispatch,
320 }: {
321 readonly snapshot: OrchestrationReadModel;
322 readonly dispatch: (
323 command: ProjectCliDispatchCommand,
324 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
325 }) {
326 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
327 const existingProject = snapshot.projects.find(
328 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
329 );
330 if (existingProject) {
331 return yield* new ProjectCommandError({
332 message: `An active project already exists for '${workspaceRoot}'.`,
333 });
334 }
335​
336 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
337 const projectId = ProjectId.make(yield* projectCommandUuid);
338 yield* dispatch({
339 type: "project.create",
340 commandId: CommandId.make(yield* projectCommandUuid),
341 projectId,
342 title,
343 workspaceRoot,
344 defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
345 createdAt: DateTime.formatIso(yield* DateTime.now),
346 });
347 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
348 }),
349 ),
350 ),
351);
352​
353const projectRemoveCommand = Command.make("remove", {
354 ...projectLocationFlags,
355 project: Argument.string("project").pipe(
356 Argument.withDescription("Project id or workspace root to remove."),
357 ),
358}).pipe(
359 Command.withDescription("Remove a project."),
360 Command.withHandler((flags) =>
361 runProjectMutation(
362 flags,
363 Effect.fn("projectRemoveMutation")(function* ({
364 snapshot,
365 dispatch,
366 }: {
367 readonly snapshot: OrchestrationReadModel;
368 readonly dispatch: (
369 command: ProjectCliDispatchCommand,
370 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
371 }) {
372 const project = yield* findActiveProjectTarget({
373 snapshot,
374 identifier: flags.project,
375 });
376 yield* dispatch({
377 type: "project.delete",
378 commandId: CommandId.make(yield* projectCommandUuid),
379 projectId: project.id,
380 });
381 return `Removed project ${project.id} (${project.title}).`;
382 }),
383 ),
384 ),
385);
386​
387const projectRenameCommand = Command.make("rename", {
388 ...projectLocationFlags,
389 project: Argument.string("project").pipe(
390 Argument.withDescription("Project id or workspace root to rename."),
391 ),
392 title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
393}).pipe(
394 Command.withDescription("Rename a project."),
395 Command.withHandler((flags) =>
396 runProjectMutation(
397 flags,
398 Effect.fn("projectRenameMutation")(function* ({
399 snapshot,
400 dispatch,
401 }: {
402 readonly snapshot: OrchestrationReadModel;
403 readonly dispatch: (
404 command: ProjectCliDispatchCommand,
405 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
406 }) {
407 const project = yield* findActiveProjectTarget({
408 snapshot,
409 identifier: flags.project,
410 });
411 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
412 if (nextTitle === project.title) {
413 return `Project ${project.id} is already named ${nextTitle}.`;
414 }
415​
416 yield* dispatch({
417 type: "project.meta.update",
418 commandId: CommandId.make(yield* projectCommandUuid),
419 projectId: project.id,
420 title: nextTitle,
421 });
422 return `Renamed project ${project.id} to ${nextTitle}.`;
423 }),
424 ),
425 ),
426);
427​
428export const projectCommand = Command.make("project").pipe(
429 Command.withDescription("Manage projects."),
430 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
431);