Open History to see the last commit
1import type { OrchestrationV2ThreadDetailSnapshot, ThreadId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5
6import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
7import type { PreparedConnection } from "../connection/model.ts";
8import { environmentEndpointUrl } from "../environment/endpoint.ts";
9import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
10import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
11import {
12 executeAuthenticatedEnvironmentHttpRequest,
13 withOrchestrationProtocolHeader,
14} 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/** Progressive history metadata returned by a bounded snapshot loader. */
22export type ThreadSnapshotHistoryMeta = {
23 readonly historyCursor: string | null;
24 readonly hasMoreHistory: boolean;
25 /** Max local turn ordinal from the full projection; optional on older servers. */
26 readonly latestLocalTurnOrdinal?: number | null;
27};
28
29/**
30 * Outcome of an HTTP thread-detail snapshot load.
31 *
32 * - `present`: snapshot body is available (seed projection, resume via socket).
33 * - `missing`: server definitively reported the thread does not exist (404).
34 * - `unavailable`: transport/timeout/5xx/etc.; fall back to the socket path.
35 */
36export type ThreadSnapshotLoadResult =
37 | {
38 readonly _tag: "present";
39 readonly snapshot: OrchestrationV2ThreadDetailSnapshot;
40 readonly history?: ThreadSnapshotHistoryMeta;
41 }
42 | { readonly _tag: "missing" }
43 | { readonly _tag: "unavailable" };
44
45/**
46 * Load a thread's detail snapshot over HTTP instead of embedding it in the
47 * WebSocket subscription's first frame. The response is gzip-compressible by
48 * the transport and keeps the (potentially multi-KB) snapshot off the socket.
49 */
50export const fetchEnvironmentThreadSnapshot = Effect.fn(
51 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
52)(function* (input: {
53 readonly prepared: PreparedConnection;
54 readonly threadId: ThreadId;
55 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
56 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
57 readonly timeoutMs?: number;
58}) {
59 return yield* executeAuthenticatedEnvironmentHttpRequest({
60 ...input,
61 group: "orchestration",
62 method: "GET",
63 url: (httpBaseUrl) =>
64 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
65 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
66 request: ({ client, headers }) =>
67 client.threadSnapshot({
68 params: { threadId: input.threadId },
69 headers: withOrchestrationProtocolHeader(headers),
70 }),
71 });
72});
73
74export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
75
76/**
77 * Loads a thread's detail snapshot over HTTP.
78 *
79 * Distinguishes a definitive missing thread (HTTP 404) from transient snapshot
80 * unavailability so the thread state machine can mark the thread deleted without
81 * opening a socket subscription, while still falling back to the socket when the
82 * HTTP path is merely unavailable.
83 */
84export class ThreadSnapshotLoader extends Context.Service<
85 ThreadSnapshotLoader,
86 {
87 readonly load: (
88 prepared: PreparedConnection,
89 threadId: ThreadId,
90 ) => Effect.Effect<ThreadSnapshotLoadResult>;
91 }
92>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}