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

threadSnapshotHttp.ts

150 lines6.0 KB

1import {
2 type EnvironmentResourceNotFoundError,
3 type OrchestrationThreadDetailSnapshot,
4 type ThreadId,
5} from "@t3tools/contracts";
6import * as Cause from "effect/Cause";
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import { HttpClient } from "effect/unstable/http";
12​
13import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
14import type { PreparedConnection } from "../connection/model.ts";
15import { environmentEndpointUrl } from "../environment/endpoint.ts";
16import { findHttpThreadNotFoundError } from "../errors/orchestration.ts";
17import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
18import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
19import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
20​
21// Long enough for a slow but alive server to finish. On a cold open a timeout
22// makes the socket ask the same server for the same snapshot again, and older
23// turn pages have no fallback, so a short deadline only drops work. The socket
24// fallback is for setups where /api fails but /ws works, such as a proxy that
25// blocks /api. A dead server drops the socket session, which interrupts a
26// cold-open load. Older turn pages wait for this deadline.
27const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 20_000;
28​
29/**
30 * Load a thread's detail snapshot over HTTP instead of embedding it in the
31 * WebSocket subscription's first frame. The response is gzip-compressible by
32 * the transport and keeps the (potentially multi-KB) snapshot off the socket.
33 */
34/**
35 * Optional turn window for a snapshot fetch. Only send a window to servers
36 * that advertise `threadSnapshotPagination`; older servers reject unknown
37 * query parameters.
38 */
39export interface ThreadSnapshotWindow {
40 readonly turnLimit: number;
41 readonly beforeCursor?: string;
43​
44export const fetchEnvironmentThreadSnapshot = Effect.fn(
45 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
46)(function* (input: {
47 readonly prepared: PreparedConnection;
48 readonly threadId: ThreadId;
49 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
50 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
51 readonly timeoutMs?: number;
52 readonly window?: ThreadSnapshotWindow;
53 readonly reasoningMessages?: boolean;
54}) {
55 return yield* executeAuthenticatedEnvironmentHttpRequest({
56 ...input,
57 group: "orchestration",
58 method: "GET",
59 url: (httpBaseUrl) =>
60 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
61 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
62 request: ({ client, headers }) =>
63 client.threadSnapshot({
64 params: { threadId: input.threadId },
65 payload: {
66 ...(input.reasoningMessages === true ? { reasoningMessages: "true" as const } : {}),
67 ...(input.window !== undefined ? { turnLimit: input.window.turnLimit } : {}),
68 ...(input.window?.beforeCursor !== undefined
69 ? { beforeCursor: input.window.beforeCursor }
70 : {}),
71 },
72 headers,
73 }),
74 });
75});
76​
77export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
78​
79/**
80 * Loads a thread's detail snapshot over HTTP, returning `Option.none()` for
81 * transient failures so the caller can fall back to the socket-embedded
82 * snapshot. An authoritative `thread_not_found` response remains in the error
83 * channel so the thread state machine can terminate the subscription.
84 * Decouples the thread state machine from the underlying HTTP + DPoP details
85 * and keeps them out of test contexts.
86 */
87export class ThreadSnapshotLoader extends Context.Service<
88 ThreadSnapshotLoader,
89 {
90 readonly load: (
91 prepared: PreparedConnection,
92 threadId: ThreadId,
93 window?: ThreadSnapshotWindow,
94 reasoningMessages?: boolean,
95 ) => Effect.Effect<
96 Option.Option<OrchestrationThreadDetailSnapshot>,
97 EnvironmentResourceNotFoundError
98 >;
99 }
100>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
101​
102export const threadSnapshotLoaderLayer: Layer.Layer<
103 ThreadSnapshotLoader,
104 never,
105 HttpClient.HttpClient
106> = Layer.effect(
107 ThreadSnapshotLoader,
108 Effect.gen(function* () {
109 const httpClient = yield* HttpClient.HttpClient;
110 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
111 // connections, so the loader must not hard-require it (bearer/primary
112 // connections work without one).
113 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
114 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
115 return ThreadSnapshotLoader.of({
116 load: (
117 prepared: PreparedConnection,
118 threadId: ThreadId,
119 window?: ThreadSnapshotWindow,
120 reasoningMessages?: boolean,
121 ) =>
122 fetchEnvironmentThreadSnapshot({
123 prepared,
124 threadId,
125 signer,
126 remoteAuthorization,
127 ...(reasoningMessages === true ? { reasoningMessages: true } : {}),
128 ...(window !== undefined ? { window } : {}),
129 }).pipe(
130 Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
131 Effect.provideService(HttpClient.HttpClient, httpClient),
132 // Preserve the declared 404 in the error channel. It is authoritative
133 // for this resource and must terminate the thread subscription rather
134 // than fall into its retry loop.
135 Effect.catchCause((cause) => {
136 const notFound = findHttpThreadNotFoundError(cause);
137 if (notFound !== undefined) {
138 return Effect.fail(notFound);
139 }
140 return Effect.logWarning(
141 "Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
142 ).pipe(
143 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
144 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
145 );
146 }),
147 ),
148 });
149 }),
150);