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

http.ts

238 lines9.2 KB

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