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

threadSnapshotHttp.ts

153 lines5.7 KB

1import type { OrchestrationV2ThreadDetailSnapshot, 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 {
18 buildEnvironmentAuthHeaders,
19 withEnvironmentCredentials,
20 withOrchestrationProtocolHeader,
21} from "./environmentHttpAuth.ts";
22​
23// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
24// fallback for long. The cached thread renders while this runs, so the wait only
25// delays the transition to live data on the first open, not the initial paint.
26const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000;
27​
28/** Progressive history metadata returned by a bounded snapshot loader. */
29export type ThreadSnapshotHistoryMeta = {
30 readonly historyCursor: string | null;
31 readonly hasMoreHistory: boolean;
32 /** Max local turn ordinal from the full projection; optional on older servers. */
33 readonly latestLocalTurnOrdinal?: number | null;
34};
35​
36/**
37 * Outcome of an HTTP thread-detail snapshot load.
38 *
39 * - `present`: snapshot body is available (seed projection, resume via socket).
40 * - `missing`: server definitively reported the thread does not exist (404).
41 * - `unavailable`: transport/timeout/5xx/etc.; fall back to the socket path.
42 */
43export type ThreadSnapshotLoadResult =
44 | {
45 readonly _tag: "present";
46 readonly snapshot: OrchestrationV2ThreadDetailSnapshot;
47 readonly history?: ThreadSnapshotHistoryMeta;
48 }
49 | { readonly _tag: "missing" }
50 | { readonly _tag: "unavailable" };
51​
52/**
53 * Load a thread's detail snapshot over HTTP instead of embedding it in the
54 * WebSocket subscription's first frame. The response is gzip-compressible by
55 * the transport and keeps the (potentially multi-KB) snapshot off the socket.
56 */
57export const fetchEnvironmentThreadSnapshot = Effect.fn(
58 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
59)(function* (input: {
60 readonly prepared: PreparedConnection;
61 readonly threadId: ThreadId;
62 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
63 readonly timeoutMs?: number;
64}) {
65 const requestUrl = environmentEndpointUrl(
66 input.prepared.httpBaseUrl,
67 `/api/orchestration/threads/${input.threadId}`,
68 );
69 const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
70 const headers = yield* buildEnvironmentAuthHeaders(
71 input.prepared.httpAuthorization,
72 "GET",
73 requestUrl,
74 input.signer,
75 );
76 return yield* executeEnvironmentHttpRequest(
77 requestUrl,
78 input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
79 withEnvironmentCredentials(
80 input.prepared.httpAuthorization,
81 client.orchestration.threadSnapshot({
82 params: { threadId: input.threadId },
83 headers: withOrchestrationProtocolHeader(headers),
84 }),
85 ),
86 );
87});
88​
89export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
90​
91/**
92 * Loads a thread's detail snapshot over HTTP.
93 *
94 * Distinguishes a definitive missing thread (HTTP 404) from transient snapshot
95 * unavailability so the thread state machine can mark the thread deleted without
96 * opening a socket subscription, while still falling back to the socket when the
97 * HTTP path is merely unavailable.
98 */
99export class ThreadSnapshotLoader extends Context.Service<
100 ThreadSnapshotLoader,
101 {
102 readonly load: (
103 prepared: PreparedConnection,
104 threadId: ThreadId,
105 ) => Effect.Effect<ThreadSnapshotLoadResult>;
106 }
107>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
108​
109export const threadSnapshotLoaderLayer: Layer.Layer<
110 ThreadSnapshotLoader,
111 never,
112 HttpClient.HttpClient
113> = Layer.effect(
114 ThreadSnapshotLoader,
115 Effect.gen(function* () {
116 const httpClient = yield* HttpClient.HttpClient;
117 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
118 // connections, so the loader must not hard-require it (bearer/primary
119 // connections work without one).
120 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
121 return ThreadSnapshotLoader.of({
122 load: (prepared: PreparedConnection, threadId: ThreadId) =>
123 fetchEnvironmentThreadSnapshot({ prepared, threadId, signer }).pipe(
124 Effect.map(
125 (snapshot): ThreadSnapshotLoadResult => ({
126 _tag: "present",
127 snapshot,
128 }),
129 ),
130 Effect.provideService(HttpClient.HttpClient, httpClient),
131 // A genuinely missing thread (404) is definitive: do not fall back to
132 // the socket or retry. Callers mark the thread deleted and clear cache.
133 Effect.catchTags({
134 EnvironmentResourceNotFoundError: () =>
135 Effect.logDebug(
136 "Thread snapshot not found over HTTP; treating the thread as deleted.",
137 ).pipe(
138 Effect.annotateLogs({ threadId }),
139 Effect.as({ _tag: "missing" } satisfies ThreadSnapshotLoadResult),
140 ),
141 }),
142 Effect.catchCause((cause) =>
143 Effect.logWarning(
144 "Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
145 ).pipe(
146 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
147 Effect.as({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult),
148 ),
149 ),
150 ),
151 });
152 }),
153);