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

boundedThreadSnapshotHttp.ts

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