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

threadSnapshotHttp.ts

134 lines5.5 KB

1import type { OrchestrationThreadDetailSnapshot, 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 { executeAuthenticatedEnvironmentHttpRequest } 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/**
22 * Load a thread's detail snapshot over HTTP instead of embedding it in the
23 * WebSocket subscription's first frame. The response is gzip-compressible by
24 * the transport and keeps the (potentially multi-KB) snapshot off the socket.
25 */
26/**
27 * Optional turn window for a snapshot fetch. Only send a window to servers
28 * that advertise `threadSnapshotPagination`; older servers reject unknown
29 * query parameters.
30 */
31export interface ThreadSnapshotWindow {
32 readonly turnLimit: number;
33 readonly beforeCursor?: string;
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<ManagedRelayDpopSigner["Service"]>;
42 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
43 readonly timeoutMs?: number;
44 readonly window?: ThreadSnapshotWindow;
45}) {
46 return yield* executeAuthenticatedEnvironmentHttpRequest({
47 ...input,
48 group: "orchestration",
49 method: "GET",
50 url: (httpBaseUrl) =>
51 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
52 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
53 request: ({ client, headers }) =>
54 client.threadSnapshot({
55 params: { threadId: input.threadId },
56 payload: {
57 ...(input.window !== undefined ? { turnLimit: input.window.turnLimit } : {}),
58 ...(input.window?.beforeCursor !== undefined
59 ? { beforeCursor: input.window.beforeCursor }
60 : {}),
61 },
62 headers,
63 }),
64 });
65});
66​
67export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
68​
69/**
70 * Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it
71 * cannot be loaded (so the caller falls back to the socket-embedded snapshot).
72 * Decouples the thread state machine from the underlying HTTP + DPoP details and
73 * keeps them out of test contexts.
74 */
75export class ThreadSnapshotLoader extends Context.Service<
76 ThreadSnapshotLoader,
77 {
78 readonly load: (
79 prepared: PreparedConnection,
80 threadId: ThreadId,
81 window?: ThreadSnapshotWindow,
82 ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
83 }
84>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
85​
86export const threadSnapshotLoaderLayer: Layer.Layer<
87 ThreadSnapshotLoader,
88 never,
89 HttpClient.HttpClient
90> = Layer.effect(
91 ThreadSnapshotLoader,
92 Effect.gen(function* () {
93 const httpClient = yield* HttpClient.HttpClient;
94 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
95 // connections, so the loader must not hard-require it (bearer/primary
96 // connections work without one).
97 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
98 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
99 return ThreadSnapshotLoader.of({
100 load: (prepared: PreparedConnection, threadId: ThreadId, window?: ThreadSnapshotWindow) =>
101 fetchEnvironmentThreadSnapshot({
102 prepared,
103 threadId,
104 signer,
105 remoteAuthorization,
106 ...(window !== undefined ? { window } : {}),
107 }).pipe(
108 Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
109 Effect.provideService(HttpClient.HttpClient, httpClient),
110 // A genuinely missing thread (404) is expected — the socket
111 // subscription is the source of truth for thread existence and will
112 // surface the deletion — so don't treat it as an error worth warning
113 // about; just defer to the socket path.
114 Effect.catchTags({
115 EnvironmentResourceNotFoundError: () =>
116 Effect.logDebug(
117 "Thread snapshot not found over HTTP; deferring to the socket subscription.",
118 ).pipe(
119 Effect.annotateLogs({ threadId }),
120 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
121 ),
122 }),
123 Effect.catchCause((cause) =>
124 Effect.logWarning(
125 "Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
126 ).pipe(
127 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
128 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
129 ),
130 ),
131 ),
132 });
133 }),
134);