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

boundedThreadSnapshotHttp.ts

160 lines6.4 KB

1import type { ThreadId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import { HttpClient } from "effect/unstable/http";
7​
8import type { PreparedConnection } from "../connection/model.ts";
9import { environmentEndpointUrl } from "../environment/endpoint.ts";
10import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
11import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts";
12import {
13 buildEnvironmentAuthHeaders,
14 withEnvironmentCredentials,
15 withOrchestrationProtocolHeader,
16} from "./environmentHttpAuth.ts";
17import {
18 fetchEnvironmentThreadSnapshot,
19 ThreadSnapshotLoader,
20 type ThreadSnapshotLoadResult,
21} from "./threadSnapshotHttp.ts";
22​
23// Same cold-open budget as the full snapshot path; bounded payloads should fit.
24const DEFAULT_BOUNDED_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000;
25​
26/** Load a bounded recent-window thread snapshot over HTTP. */
27export const fetchEnvironmentBoundedThreadSnapshot = Effect.fn(
28 "clientRuntime.state.fetchEnvironmentBoundedThreadSnapshot",
29)(function* (input: {
30 readonly prepared: PreparedConnection;
31 readonly threadId: ThreadId;
32 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
33 readonly timeoutMs?: number;
34}) {
35 const requestUrl = environmentEndpointUrl(
36 input.prepared.httpBaseUrl,
37 `/api/orchestration/threads/${input.threadId}/bounded`,
38 );
39 const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
40 const headers = yield* buildEnvironmentAuthHeaders(
41 input.prepared.httpAuthorization,
42 "GET",
43 requestUrl,
44 input.signer,
45 );
46 return yield* executeEnvironmentHttpRequest(
47 requestUrl,
48 input.timeoutMs ?? DEFAULT_BOUNDED_THREAD_SNAPSHOT_TIMEOUT_MS,
49 withEnvironmentCredentials(
50 input.prepared.httpAuthorization,
51 client.orchestration.threadBoundedSnapshot({
52 params: { threadId: input.threadId },
53 headers: withOrchestrationProtocolHeader(headers),
54 }),
55 ),
56 );
57});
58​
59/**
60 * Shared ThreadSnapshotLoader for clients that render progressive history.
61 * Seeds from the bounded HTTP snapshot when available. Older servers that lack
62 * the bounded route (plain/generic 404) fall back to the existing full HTTP
63 * thread snapshot. Structured EnvironmentResourceNotFoundError from either
64 * endpoint still means missing. Transient failures report `unavailable` so the
65 * socket path remains a last resort for connectivity issues.
66 */
67export const boundedThreadSnapshotLoaderLayer: Layer.Layer<
68 ThreadSnapshotLoader,
69 never,
70 HttpClient.HttpClient
71> = Layer.effect(
72 ThreadSnapshotLoader,
73 Effect.gen(function* () {
74 const httpClient = yield* HttpClient.HttpClient;
75 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
76 return ThreadSnapshotLoader.of({
77 load: (prepared: PreparedConnection, threadId: ThreadId) => {
78 const loadFullFallback = fetchEnvironmentThreadSnapshot({
79 prepared,
80 threadId,
81 signer,
82 }).pipe(
83 Effect.map(
84 (snapshot): ThreadSnapshotLoadResult => ({
85 _tag: "present",
86 snapshot,
87 }),
88 ),
89 Effect.provideService(HttpClient.HttpClient, httpClient),
90 Effect.catchTags({
91 EnvironmentResourceNotFoundError: () =>
92 Effect.logDebug(
93 "Full thread snapshot not found over HTTP after bounded fallback; treating the thread as deleted.",
94 ).pipe(
95 Effect.annotateLogs({ threadId }),
96 Effect.as({ _tag: "missing" } satisfies ThreadSnapshotLoadResult),
97 ),
98 }),
99 Effect.catchCause((cause) =>
100 Effect.logWarning(
101 "Could not load the full thread snapshot over HTTP after bounded fallback; using the socket snapshot instead.",
102 ).pipe(
103 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
104 Effect.as({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult),
105 ),
106 ),
107 );
108​
109 return fetchEnvironmentBoundedThreadSnapshot({ prepared, threadId, signer }).pipe(
110 Effect.map(
111 (bounded): ThreadSnapshotLoadResult => ({
112 _tag: "present",
113 snapshot: {
114 snapshotSequence: bounded.snapshotSequence,
115 projection: bounded.projection,
116 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
117 },
118 history: {
119 historyCursor: bounded.historyCursor,
120 hasMoreHistory: bounded.hasMoreHistory,
121 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
122 },
123 }),
124 ),
125 Effect.provideService(HttpClient.HttpClient, httpClient),
126 Effect.catchTags({
127 EnvironmentResourceNotFoundError: () =>
128 Effect.logDebug(
129 "Bounded thread snapshot not found over HTTP; treating the thread as deleted.",
130 ).pipe(
131 Effect.annotateLogs({ threadId }),
132 Effect.as({ _tag: "missing" } satisfies ThreadSnapshotLoadResult),
133 ),
134 RemoteEnvironmentAuthInvalidJsonError: (error) =>
135 Effect.logDebug(
136 "Bounded thread snapshot returned an invalid response; trying the full HTTP thread snapshot for an older server.",
137 ).pipe(
138 Effect.annotateLogs({ threadId, cause: error.message }),
139 Effect.andThen(loadFullFallback),
140 ),
141 RemoteEnvironmentAuthUndeclaredStatusError: (error) =>
142 error.status === 404
143 ? Effect.logDebug(
144 "Bounded thread snapshot route was not found; trying the full HTTP thread snapshot for an older server.",
145 ).pipe(Effect.annotateLogs({ threadId }), Effect.andThen(loadFullFallback))
146 : Effect.fail(error),
147 }),
148 Effect.catchCause((cause) =>
149 Effect.logWarning(
150 "Could not load the bounded thread snapshot over HTTP; using the socket snapshot instead.",
151 ).pipe(
152 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
153 Effect.as({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult),
154 ),
155 ),
156 );
157 },
158 });
159 }),
160);