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

project.ts

434 lines14.9 KB

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