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

threadSnapshotHttp.ts

71 lines2.7 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 * as ManagedRelay from "../relay/managedRelay.ts";
9import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
10import {
11 executeAuthenticatedEnvironmentHttpRequest,
12 withOrchestrationProtocolHeader,
13} from "./environmentHttpAuth.ts";
14​
15// Long enough for a slow but alive server to finish. On a cold open a timeout makes the socket
16// ask the same server for the same snapshot again, and older turn pages have no fallback, so a
17// short deadline only drops work. The socket fallback is for setups where /api fails but /ws
18// works, such as a proxy that blocks /api.
19const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 20_000;
20​
21export type ThreadSnapshotHistoryMeta = {
22 readonly historyCursor: string | null;
23 readonly hasMoreHistory: boolean;
24 readonly latestLocalTurnOrdinal?: number | null;
25};
26​
27export type ThreadSnapshotLoadResult =
28 | {
29 readonly _tag: "present";
30 readonly snapshot: OrchestrationV2ThreadDetailSnapshot;
31 readonly history?: ThreadSnapshotHistoryMeta;
32 }
33 | { readonly _tag: "missing" }
34 | { readonly _tag: "unavailable" };
35​
36export const fetchEnvironmentThreadSnapshot = Effect.fn(
37 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
38)(function* (input: {
39 readonly prepared: PreparedConnection;
40 readonly threadId: ThreadId;
41 readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
42 readonly remoteAuthorization?: Option.Option<
43 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
44 >;
45 readonly timeoutMs?: number;
46}) {
47 return yield* executeAuthenticatedEnvironmentHttpRequest({
48 ...input,
49 group: "orchestration",
50 method: "GET",
51 url: (urls) => urls.threadSnapshot({ params: { threadId: input.threadId } }),
52 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
53 request: ({ client, headers }) =>
54 client.threadSnapshot({
55 params: { threadId: input.threadId },
56 headers: withOrchestrationProtocolHeader(headers),
57 }),
58 });
59});
60​
61export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
62​
63export class ThreadSnapshotLoader extends Context.Service<
64 ThreadSnapshotLoader,
65 {
66 readonly load: (
67 prepared: PreparedConnection,
68 threadId: ThreadId,
69 ) => Effect.Effect<ThreadSnapshotLoadResult>;
70 }
71>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}