Open History to see the last commit
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 */
29export const fetchEnvironmentThreadSnapshot = Effect.fn(
30 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
31)(function* (input: {
32 readonly prepared: PreparedConnection;
33 readonly threadId: ThreadId;
34 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
35 readonly timeoutMs?: number;
36}) {
37 const requestUrl = environmentEndpointUrl(
38 input.prepared.httpBaseUrl,
39 `/api/orchestration/threads/${input.threadId}`,
40 );
41 const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
42 const headers = yield* buildEnvironmentAuthHeaders(
43 input.prepared.httpAuthorization,
44 "GET",
45 requestUrl,
46 input.signer,
47 );
48 return yield* executeEnvironmentHttpRequest(
49 requestUrl,
50 input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
51 withEnvironmentCredentials(
52 input.prepared.httpAuthorization,
53 client.orchestration.threadSnapshot({
54 params: { threadId: input.threadId },
55 headers,
56 }),
57 ),
58 );
59});
60
61export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
62
63/**
64 * Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it
65 * cannot be loaded (so the caller falls back to the socket-embedded snapshot).
66 * Decouples the thread state machine from the underlying HTTP + DPoP details and
67 * keeps them out of test contexts.
68 */
69export class ThreadSnapshotLoader extends Context.Service<
70 ThreadSnapshotLoader,
71 {
72 readonly load: (
73 prepared: PreparedConnection,
74 threadId: ThreadId,
75 ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
76 }
77>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
78
79export const threadSnapshotLoaderLayer: Layer.Layer<
80 ThreadSnapshotLoader,
81 never,
82 HttpClient.HttpClient
83> = Layer.effect(
84 ThreadSnapshotLoader,
85 Effect.gen(function* () {
86 const httpClient = yield* HttpClient.HttpClient;
87 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
88 // connections, so the loader must not hard-require it (bearer/primary
89 // connections work without one).
90 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
91 return ThreadSnapshotLoader.of({
92 load: (prepared: PreparedConnection, threadId: ThreadId) =>
93 fetchEnvironmentThreadSnapshot({ prepared, threadId, signer }).pipe(
94 Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
95 Effect.provideService(HttpClient.HttpClient, httpClient),
96 // A genuinely missing thread (404) is expected — the socket
97 // subscription is the source of truth for thread existence and will
98 // surface the deletion — so don't treat it as an error worth warning
99 // about; just defer to the socket path.
100 Effect.catchTags({
101 EnvironmentResourceNotFoundError: () =>
102 Effect.logDebug(
103 "Thread snapshot not found over HTTP; deferring to the socket subscription.",
104 ).pipe(
105 Effect.annotateLogs({ threadId }),
106 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
107 ),
108 }),
109 Effect.catchCause((cause) =>
110 Effect.logWarning(
111 "Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
112 ).pipe(
113 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
114 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
115 ),
116 ),
117 ),
118 });
119 }),
120);