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

http.ts

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