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

threadSnapshotHttp.ts

95 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 { 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// 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<ManagedRelayDpopSigner["Service"]>;
59 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
60 readonly timeoutMs?: number;
61}) {
62 return yield* executeAuthenticatedEnvironmentHttpRequest({
63 ...input,
64 group: "orchestration",
65 method: "GET",
66 url: (httpBaseUrl) =>
67 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
68 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
69 request: ({ client, headers }) =>
70 client.threadSnapshot({
71 params: { threadId: input.threadId },
72 headers: withOrchestrationProtocolHeader(headers),
73 }),
74 });
75});
76​
77export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
78​
79/**
80 * Loads a thread's detail snapshot over HTTP.
81 *
82 * Distinguishes a definitive missing thread (HTTP 404) from transient snapshot
83 * unavailability so the thread state machine can mark the thread deleted without
84 * opening a socket subscription, while still falling back to the socket when the
85 * HTTP path is merely unavailable.
86 */
87export class ThreadSnapshotLoader extends Context.Service<
88 ThreadSnapshotLoader,
89 {
90 readonly load: (
91 prepared: PreparedConnection,
92 threadId: ThreadId,
93 ) => Effect.Effect<ThreadSnapshotLoadResult>;
94 }
95>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}