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

project.ts

440 lines15.5 KB

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