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