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

threadSnapshotHttp.ts

143 lines5.5 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 type { PreparedConnection } from "../connection/model.ts";
10import { environmentEndpointUrl } from "../environment/endpoint.ts";
11import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
12import {
13 executeEnvironmentHttpRequest,
14 makeEnvironmentHttpApiClient,
15 type RemoteEnvironmentRequestError,
16} from "../rpc/http.ts";
17import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
18​
19// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
20// fallback for long. The cached thread renders while this runs, so the wait only
21// delays the transition to live data on the first open, not the initial paint.
22const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000;
23​
24/**
25 * Load a thread's detail snapshot over HTTP instead of embedding it in the
26 * WebSocket subscription's first frame. The response is gzip-compressible by
27 * the transport and keeps the (potentially multi-KB) snapshot off the socket.
28 */
29/**
30 * Optional turn window for a snapshot fetch. Only send a window to servers
31 * that advertise `threadSnapshotPagination`; older servers reject unknown
32 * query parameters.
33 */
34export interface ThreadSnapshotWindow {
35 readonly turnLimit: number;
36 readonly beforeCursor?: string;
38​
39export const fetchEnvironmentThreadSnapshot = Effect.fn(
40 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
41)(function* (input: {
42 readonly prepared: PreparedConnection;
43 readonly threadId: ThreadId;
44 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
45 readonly timeoutMs?: number;
46 readonly window?: ThreadSnapshotWindow;
47}) {
48 const requestUrl = environmentEndpointUrl(
49 input.prepared.httpBaseUrl,
50 `/api/orchestration/threads/${input.threadId}`,
51 );
52 const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
53 const headers = yield* buildEnvironmentAuthHeaders(
54 input.prepared.httpAuthorization,
55 "GET",
56 requestUrl,
57 input.signer,
58 );
59 return yield* executeEnvironmentHttpRequest(
60 requestUrl,
61 input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
62 withEnvironmentCredentials(
63 input.prepared.httpAuthorization,
64 client.orchestration.threadSnapshot({
65 params: { threadId: input.threadId },
66 payload: {
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});
77​
78export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
79​
80/**
81 * Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it
82 * cannot be loaded (so the caller falls back to the socket-embedded snapshot).
83 * Decouples the thread state machine from the underlying HTTP + DPoP details and
84 * keeps them out of test contexts.
85 */
86export class ThreadSnapshotLoader extends Context.Service<
87 ThreadSnapshotLoader,
88 {
89 readonly load: (
90 prepared: PreparedConnection,
91 threadId: ThreadId,
92 window?: ThreadSnapshotWindow,
93 ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
94 }
95>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
96​
97export const threadSnapshotLoaderLayer: Layer.Layer<
98 ThreadSnapshotLoader,
99 never,
100 HttpClient.HttpClient
101> = Layer.effect(
102 ThreadSnapshotLoader,
103 Effect.gen(function* () {
104 const httpClient = yield* HttpClient.HttpClient;
105 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
106 // connections, so the loader must not hard-require it (bearer/primary
107 // connections work without one).
108 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
109 return ThreadSnapshotLoader.of({
110 load: (prepared: PreparedConnection, threadId: ThreadId, window?: ThreadSnapshotWindow) =>
111 fetchEnvironmentThreadSnapshot({
112 prepared,
113 threadId,
114 signer,
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);