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

http.ts

258 lines10.2 KB

1import {
2 AuthOrchestrationReadScope,
3 EnvironmentHttpApi,
4 ThreadId,
5 TurnItemId,
6 type OrchestrationProjectShell,
7} from "@t3tools/contracts";
8import * as Effect from "effect/Effect";
9import * as Predicate from "effect/Predicate";
10import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
11import * as SqlClient from "effect/unstable/sql/SqlClient";
12​
13import {
14 annotateEnvironmentRequest,
15 failEnvironmentInternal,
16 failEnvironmentInvalidRequest,
17 failEnvironmentNotFound,
18 requireEnvironmentScope,
19} from "../auth/http.ts";
20import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
21import * as OrchestrationEventStore from "../persistence/Services/OrchestrationEventStore.ts";
22import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
23import {
24 buildBoundedThreadProjection,
25 decodeThreadHistoryCursor,
26 InvalidThreadHistoryCursorError,
27 selectHistoryPageFromCursor,
28 THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
29} from "./threadHistoryPaging.ts";
30import * as ThreadManagementService from "./ThreadManagementService.ts";
31import { buildActiveShellSnapshot } from "./ShellStream.ts";
32import { projectThreadProjectionForWire } from "./WireProjection.ts";
33​
34function isThreadNotFound(error: unknown): boolean {
35 return (
36 Predicate.hasProperty(error, "cause") &&
37 Predicate.hasProperty(error.cause, "_tag") &&
38 error.cause._tag === "ProjectionStoreThreadNotFoundError"
39 );
41​
42function selectHistoryPageFromCursorOrError(
43 input: Parameters<typeof selectHistoryPageFromCursor>[0],
44):
45 | { readonly _tag: "ok"; readonly page: ReturnType<typeof selectHistoryPageFromCursor> }
46 | { readonly _tag: "invalid_cursor" }
47 | { readonly _tag: "error"; readonly cause: unknown } {
48 try {
49 return { _tag: "ok", page: selectHistoryPageFromCursor(input) };
50 } catch (cause) {
51 if (cause instanceof InvalidThreadHistoryCursorError) {
52 return { _tag: "invalid_cursor" };
53 }
54 return { _tag: "error", cause };
55 }
57​
58/**
59 * Serves orchestration V2 snapshots over HTTP so clients can load the
60 * (potentially large) shell and thread projections off the socket; gzip
61 * compressible and cacheable — and then resume the WebSocket subscription via
62 * `afterSequence`.
63 */
64export const orchestrationHttpApiLayer = HttpApiBuilder.group(
65 EnvironmentHttpApi,
66 "orchestration",
67 Effect.fnUntraced(function* (handlers) {
68 const sql = yield* SqlClient.SqlClient;
69 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
70 const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore;
71 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
72 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
73​
74 const enrichProjectShells = Effect.fn("http.orchestration.enrichProjectShells")(
75 (projects: ReadonlyArray<OrchestrationProjectShell>) =>
76 Effect.forEach(
77 projects,
78 (project) =>
79 // Use immediately available enrichment only. Awaiting git-backed
80 // identity resolution can exceed the client shell-snapshot budget
81 // (ProcessRunner allows probes up to one minute). Background workers
82 // plus the WS enrichment subscription fill in repositoryIdentity.
83 projectEnrichment.getAvailable(project.workspaceRoot).pipe(
84 Effect.map((enrichment) => ({
85 ...project,
86 repositoryIdentity: enrichment.repositoryIdentity,
87 })),
88 ),
89 { concurrency: 16 },
90 ),
91 );
92​
93 const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(function* () {
94 const base = yield* sql.withTransaction(
95 Effect.gen(function* () {
96 const projects = yield* projectionSnapshotQuery.getProjectShellsWithoutEnrichment();
97 const threads = yield* threadManagement.getShellSnapshot({ location: "active" });
98 return buildActiveShellSnapshot({
99 projects,
100 threads,
101 snapshotSequence: yield* applicationEvents.latestApplicationSequence,
102 });
103 }),
104 );
105 const projects = yield* enrichProjectShells(base.projects);
106 return { ...base, projects };
107 });
108​
109 const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (
110 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
111 failureReason:
112 | "orchestration_thread_snapshot_failed"
113 | "orchestration_thread_bounded_snapshot_failed"
114 | "orchestration_thread_history_failed",
115 ) {
116 return yield* threadManagement.getThreadSnapshot(threadId).pipe(
117 Effect.map((snapshot) => ({
118 ...snapshot,
119 projection: projectThreadProjectionForWire(snapshot.projection),
120 })),
121 Effect.catch(
122 Effect.fnUntraced(function* (error) {
123 if (isThreadNotFound(error)) {
124 return yield* failEnvironmentNotFound("thread_not_found");
125 }
126 return yield* failEnvironmentInternal(failureReason, error);
127 }),
128 ),
129 );
130 });
131​
132 const loadThreadSnapshotWindow = Effect.fn("http.orchestration.loadThreadSnapshotWindow")(
133 function* (
134 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
135 anchorItemId?: Parameters<
136 typeof threadManagement.getThreadSnapshotWindow
137 >[1]["anchorItemId"],
138 anchorThreadId?: Parameters<
139 typeof threadManagement.getThreadSnapshotWindow
140 >[1]["anchorThreadId"],
141 ) {
142 return yield* threadManagement
143 .getThreadSnapshotWindow(threadId, {
144 // The SQL anchor is inclusive. History paging excludes that row,
145 // then needs one more row to prove another page exists.
146 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
147 ...(anchorItemId === undefined ? {} : { anchorItemId }),
148 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
149 })
150 .pipe(
151 Effect.map((snapshot) => ({
152 ...snapshot,
153 projection: projectThreadProjectionForWire(snapshot.projection),
154 })),
155 Effect.catch(
156 Effect.fnUntraced(function* (error) {
157 if (isThreadNotFound(error)) {
158 return yield* failEnvironmentNotFound("thread_not_found");
159 }
160 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
161 }),
162 ),
163 );
164 },
165 );
166​
167 return handlers
168 .handle(
169 "shellSnapshot",
170 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
171 yield* annotateEnvironmentRequest(args.endpoint.name);
172 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
173 return yield* loadShellSnapshot().pipe(
174 Effect.catch((cause) =>
175 failEnvironmentInternal("orchestration_snapshot_failed", cause),
176 ),
177 );
178 }),
179 )
180 .handle(
181 "threadSnapshot",
182 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
183 yield* annotateEnvironmentRequest(args.endpoint.name);
184 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
185 const snapshot = yield* loadThreadSnapshot(
186 args.params.threadId,
187 "orchestration_thread_snapshot_failed",
188 );
189 return {
190 snapshotSequence: snapshot.snapshotSequence,
191 projection: snapshot.projection,
192 };
193 }),
194 )
195 .handle(
196 "threadBoundedSnapshot",
197 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
198 yield* annotateEnvironmentRequest(args.endpoint.name);
199 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
200 const snapshot = yield* loadThreadSnapshotWindow(args.params.threadId);
201 const bounded = buildBoundedThreadProjection({
202 projection: snapshot.projection,
203 snapshotSequence: snapshot.snapshotSequence,
204 });
205 return {
206 snapshotSequence: snapshot.snapshotSequence,
207 projection: bounded.projection,
208 historyCursor: bounded.historyCursor,
209 hasMoreHistory: bounded.hasMoreHistory,
210 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
211 payloadBudgetExceeded: bounded.payloadBudgetExceeded,
212 };
213 }),
214 )
215 .handle(
216 "threadHistoryPage",
217 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
218 yield* annotateEnvironmentRequest(args.endpoint.name);
219 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
220 let anchorItemId;
221 try {
222 anchorItemId = TurnItemId.make(decodeThreadHistoryCursor(args.query.cursor).si);
223 } catch (cause) {
224 if (cause instanceof InvalidThreadHistoryCursorError) {
225 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
226 }
227 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
228 }
229 const decodedCursor = decodeThreadHistoryCursor(args.query.cursor);
230 const snapshot = yield* loadThreadSnapshotWindow(
231 args.params.threadId,
232 anchorItemId,
233 ThreadId.make(decodedCursor.st),
234 );
235 const pageOrError = selectHistoryPageFromCursorOrError({
236 items: snapshot.projection.visibleTurnItems,
237 cursor: args.query.cursor,
238 snapshotSequence: snapshot.snapshotSequence,
239 });
240 if (pageOrError._tag === "invalid_cursor") {
241 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
242 }
243 if (pageOrError._tag === "error") {
244 return yield* failEnvironmentInternal(
245 "orchestration_thread_history_failed",
246 pageOrError.cause,
247 );
248 }
249 return {
250 snapshotSequence: snapshot.snapshotSequence,
251 items: pageOrError.page.items,
252 nextCursor: pageOrError.page.nextCursor,
253 hasMoreHistory: pageOrError.page.hasMoreHistory,
254 };
255 }),
256 );
257 }),
258);