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

boundedThreadSnapshotHttp.ts

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