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

threadSnapshotHttp.ts

97 lines3.9 KB

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 * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
7import type { PreparedConnection } from "../connection/model.ts";
8import { environmentEndpointUrl } from "../environment/endpoint.ts";
9import * as ManagedRelay from "../relay/managedRelay.ts";
10import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
11import {
12 executeAuthenticatedEnvironmentHttpRequest,
13 withOrchestrationProtocolHeader,
14} from "./environmentHttpAuth.ts";
15​
16// Long enough for a slow but alive server to finish. On a cold open a timeout
17// makes the socket ask the same server for the same snapshot again, and older
18// turn pages have no fallback, so a short deadline only drops work. The socket
19// fallback is for setups where /api fails but /ws works, such as a proxy that
20// blocks /api. A dead server drops the socket session, which interrupts a
21// cold-open load. Older turn pages wait for this deadline.
22const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 20_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<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
59 readonly remoteAuthorization?: Option.Option<
60 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
61 >;
62 readonly timeoutMs?: number;
63}) {
64 return yield* executeAuthenticatedEnvironmentHttpRequest({
65 ...input,
66 group: "orchestration",
67 method: "GET",
68 url: (httpBaseUrl) =>
69 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
70 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
71 request: ({ client, headers }) =>
72 client.threadSnapshot({
73 params: { threadId: input.threadId },
74 headers: withOrchestrationProtocolHeader(headers),
75 }),
76 });
77});
78​
79export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
80​
81/**
82 * Loads a thread's detail snapshot over HTTP.
83 *
84 * Distinguishes a definitive missing thread (HTTP 404) from transient snapshot
85 * unavailability so the thread state machine can mark the thread deleted without
86 * opening a socket subscription, while still falling back to the socket when the
87 * HTTP path is merely unavailable.
88 */
89export class ThreadSnapshotLoader extends Context.Service<
90 ThreadSnapshotLoader,
91 {
92 readonly load: (
93 prepared: PreparedConnection,
94 threadId: ThreadId,
95 ) => Effect.Effect<ThreadSnapshotLoadResult>;
96 }
97>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}