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

http.ts

236 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, loadShellSnapshotParts } 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 = buildActiveShellSnapshot(
80 yield* loadShellSnapshotParts({
81 sql,
82 readThreads: threadManagement.readShellSnapshot({ location: "active" }),
83 listProjects: projectStore.listShells(),
84 latestSequence: applicationEvents.latestApplicationSequence,
85 }),
86 );
87 const projects = yield* enrichProjectShells(base.projects);
88 return { ...base, projects };
89 });
90​
91 const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (
92 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
93 failureReason:
94 | "orchestration_thread_snapshot_failed"
95 | "orchestration_thread_bounded_snapshot_failed"
96 | "orchestration_thread_history_failed",
97 ) {
98 return yield* threadManagement.getThreadSnapshot(threadId).pipe(
99 Effect.map((snapshot) => ({
100 ...snapshot,
101 projection: projectThreadProjectionForWire(snapshot.projection),
102 })),
103 Effect.catch(
104 Effect.fnUntraced(function* (error) {
105 if (isThreadNotFound(error)) {
106 return yield* failEnvironmentNotFound("thread_not_found");
107 }
108 return yield* failEnvironmentInternal(failureReason, error);
109 }),
110 ),
111 );
112 });
113​
114 const loadThreadSnapshotWindow = Effect.fn("http.orchestration.loadThreadSnapshotWindow")(
115 function* (
116 threadId: Parameters<typeof threadManagement.getThreadSnapshot>[0],
117 anchorItemId?: Parameters<
118 typeof threadManagement.getThreadSnapshotWindow
119 >[1]["anchorItemId"],
120 anchorThreadId?: Parameters<
121 typeof threadManagement.getThreadSnapshotWindow
122 >[1]["anchorThreadId"],
123 ) {
124 return yield* threadManagement
125 .getThreadSnapshotWindow(threadId, {
126 rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,
127 userTurnLimit:
128 anchorItemId === undefined
129 ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns
130 : OLDER_THREAD_USER_TURN_LIMIT,
131 ...(anchorItemId === undefined ? {} : { anchorItemId }),
132 ...(anchorThreadId === undefined ? {} : { anchorThreadId }),
133 })
134 .pipe(
135 Effect.map((snapshot) => ({
136 ...snapshot,
137 projection: projectThreadProjectionForWire(snapshot.projection),
138 })),
139 Effect.catch(
140 Effect.fnUntraced(function* (error) {
141 if (isThreadNotFound(error)) {
142 return yield* failEnvironmentNotFound("thread_not_found");
143 }
144 return yield* failEnvironmentInternal("orchestration_thread_history_failed", error);
145 }),
146 ),
147 );
148 },
149 );
150​
151 return handlers
152 .handle(
153 "shellSnapshot",
154 Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
155 yield* annotateEnvironmentRequest(args.endpoint.name);
156 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
157 return yield* loadShellSnapshot().pipe(
158 traceLocalHandlerWork,
159 Effect.catch((cause) =>
160 failEnvironmentInternal("orchestration_snapshot_failed", cause),
161 ),
162 );
163 }),
164 )
165 .handle(
166 "threadSnapshot",
167 Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {
168 yield* annotateEnvironmentRequest(args.endpoint.name);
169 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
170 const snapshot = yield* loadThreadSnapshot(
171 args.params.threadId,
172 "orchestration_thread_snapshot_failed",
173 ).pipe(traceLocalHandlerWork);
174 return {
175 snapshotSequence: snapshot.snapshotSequence,
176 projection: snapshot.projection,
177 };
178 }),
179 )
180 .handle(
181 "threadBoundedSnapshot",
182 Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) {
183 yield* annotateEnvironmentRequest(args.endpoint.name);
184 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
185 const snapshot = yield* loadThreadSnapshotWindow(args.params.threadId).pipe(
186 traceLocalHandlerWork,
187 );
188 const bounded = buildBoundedThreadProjection({
189 projection: snapshot.projection,
190 snapshotSequence: snapshot.snapshotSequence,
191 });
192 return {
193 snapshotSequence: snapshot.snapshotSequence,
194 ...boundedSnapshotResponseFields({
195 bounded,
196 compactTurnItems: args.query.compactTurnItems === "1",
197 }),
198 };
199 }),
200 )
201 .handle(
202 "threadHistoryPage",
203 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
204 yield* annotateEnvironmentRequest(args.endpoint.name);
205 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
206 try {
207 decodeThreadHistoryCursor(args.query.cursor);
208 } catch (cause) {
209 if (cause instanceof InvalidThreadHistoryCursorError)
210 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
211 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
212 }
213 return yield* threadManagement
214 .getThreadHistoryPage(
215 args.params.threadId,
216 args.query.cursor,
217 args.query.throughEntryId,
218 args.query.view === "conversation",
219 )
220 .pipe(
221 traceLocalHandlerWork,
222 Effect.catch(
223 Effect.fnUntraced(function* (cause) {
224 if (isThreadNotFound(cause))
225 return yield* failEnvironmentNotFound("thread_not_found");
226 return yield* failEnvironmentInternal(
227 "orchestration_thread_history_failed",
228 cause,
229 );
230 }),
231 ),
232 );
233 }),
234 );
235 }),
236);