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

boundedThreadSnapshotHttp.ts

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