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

threadSnapshotHttp.ts

143 lines5.8 KB

1import type { OrchestrationThreadDetailSnapshot, ThreadId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import { HttpClient } from "effect/unstable/http";
8​
9import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
10import type { PreparedConnection } from "../connection/model.ts";
11import { environmentEndpointUrl } from "../environment/endpoint.ts";
12import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
13import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
14import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
15​
16// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
17// fallback for long. The cached thread renders while this runs, so the wait only
18// delays the transition to live data on the first open, not the initial paint.
19const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000;
20​
21/**
22 * Load a thread's detail snapshot over HTTP instead of embedding it in the
23 * WebSocket subscription's first frame. The response is gzip-compressible by
24 * the transport and keeps the (potentially multi-KB) snapshot off the socket.
25 */
26/**
27 * Optional turn window for a snapshot fetch. Only send a window to servers
28 * that advertise `threadSnapshotPagination`; older servers reject unknown
29 * query parameters.
30 */
31export interface ThreadSnapshotWindow {
32 readonly turnLimit: number;
33 readonly beforeCursor?: string;
35​
36export const fetchEnvironmentThreadSnapshot = Effect.fn(
37 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
38)(function* (input: {
39 readonly prepared: PreparedConnection;
40 readonly threadId: ThreadId;
41 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
42 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
43 readonly timeoutMs?: number;
44 readonly window?: ThreadSnapshotWindow;
45 readonly reasoningMessages?: boolean;
46}) {
47 return yield* executeAuthenticatedEnvironmentHttpRequest({
48 ...input,
49 group: "orchestration",
50 method: "GET",
51 url: (httpBaseUrl) =>
52 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
53 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
54 request: ({ client, headers }) =>
55 client.threadSnapshot({
56 params: { threadId: input.threadId },
57 payload: {
58 ...(input.reasoningMessages === true ? { reasoningMessages: "true" as const } : {}),
59 ...(input.window !== undefined ? { turnLimit: input.window.turnLimit } : {}),
60 ...(input.window?.beforeCursor !== undefined
61 ? { beforeCursor: input.window.beforeCursor }
62 : {}),
63 },
64 headers,
65 }),
66 });
67});
68​
69export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
70​
71/**
72 * Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it
73 * cannot be loaded (so the caller falls back to the socket-embedded snapshot).
74 * Decouples the thread state machine from the underlying HTTP + DPoP details and
75 * keeps them out of test contexts.
76 */
77export class ThreadSnapshotLoader extends Context.Service<
78 ThreadSnapshotLoader,
79 {
80 readonly load: (
81 prepared: PreparedConnection,
82 threadId: ThreadId,
83 window?: ThreadSnapshotWindow,
84 reasoningMessages?: boolean,
85 ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
86 }
87>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
88​
89export const threadSnapshotLoaderLayer: Layer.Layer<
90 ThreadSnapshotLoader,
91 never,
92 HttpClient.HttpClient
93> = Layer.effect(
94 ThreadSnapshotLoader,
95 Effect.gen(function* () {
96 const httpClient = yield* HttpClient.HttpClient;
97 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
98 // connections, so the loader must not hard-require it (bearer/primary
99 // connections work without one).
100 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
101 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
102 return ThreadSnapshotLoader.of({
103 load: (
104 prepared: PreparedConnection,
105 threadId: ThreadId,
106 window?: ThreadSnapshotWindow,
107 reasoningMessages?: boolean,
108 ) =>
109 fetchEnvironmentThreadSnapshot({
110 prepared,
111 threadId,
112 signer,
113 remoteAuthorization,
114 ...(reasoningMessages === true ? { reasoningMessages: true } : {}),
115 ...(window !== undefined ? { window } : {}),
116 }).pipe(
117 Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
118 Effect.provideService(HttpClient.HttpClient, httpClient),
119 // A genuinely missing thread (404) is expected — the socket
120 // subscription is the source of truth for thread existence and will
121 // surface the deletion — so don't treat it as an error worth warning
122 // about; just defer to the socket path.
123 Effect.catchTags({
124 EnvironmentResourceNotFoundError: () =>
125 Effect.logDebug(
126 "Thread snapshot not found over HTTP; deferring to the socket subscription.",
127 ).pipe(
128 Effect.annotateLogs({ threadId }),
129 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
130 ),
131 }),
132 Effect.catchCause((cause) =>
133 Effect.logWarning(
134 "Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
135 ).pipe(
136 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
137 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
138 ),
139 ),
140 ),
141 });
142 }),
143);