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

boundedThreadSnapshotHttp.ts

174 lines7.2 KB

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