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

boundedThreadSnapshotHttp.ts

165 lines6.5 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" },
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: (prepared: PreparedConnection, threadId: ThreadId) => {
73 const loadFullFallback = ThreadSnapshotLoader.fetchEnvironmentThreadSnapshot({
74 prepared,
75 threadId,
76 signer,
77 remoteAuthorization,
78 }).pipe(
79 Effect.map((snapshot): ThreadSnapshotLoader.ThreadSnapshotLoadResult => ({
80 _tag: "present",
81 snapshot,
82 })),
83 Effect.provideService(HttpClient.HttpClient, httpClient),
84 Effect.catchTags({
85 EnvironmentResourceNotFoundError: () =>
86 Effect.logDebug(
87 "Full thread snapshot not found over HTTP after bounded fallback; treating the thread as deleted.",
88 ).pipe(
89 Effect.annotateLogs({ threadId }),
90 Effect.as({
91 _tag: "missing",
92 } satisfies ThreadSnapshotLoader.ThreadSnapshotLoadResult),
93 ),
94 }),
95 Effect.catchCause((cause) =>
96 Effect.logWarning(
97 "Could not load the full thread snapshot over HTTP after bounded fallback; using the socket snapshot instead.",
98 ).pipe(
99 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
100 Effect.as({
101 _tag: "unavailable",
102 } satisfies ThreadSnapshotLoader.ThreadSnapshotLoadResult),
103 ),
104 ),
105 );
106​
107 return fetchEnvironmentBoundedThreadSnapshot({
108 prepared,
109 threadId,
110 signer,
111 remoteAuthorization,
112 }).pipe(
113 Effect.map((bounded): ThreadSnapshotLoader.ThreadSnapshotLoadResult => ({
114 _tag: "present",
115 snapshot: {
116 snapshotSequence: bounded.snapshotSequence,
117 projection: bounded.projection,
118 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
119 },
120 history: {
121 historyCursor: bounded.historyCursor,
122 hasMoreHistory: bounded.hasMoreHistory,
123 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
124 },
125 })),
126 Effect.provideService(HttpClient.HttpClient, httpClient),
127 Effect.catchTags({
128 EnvironmentResourceNotFoundError: () =>
129 Effect.logDebug(
130 "Bounded thread snapshot not found over HTTP; treating the thread as deleted.",
131 ).pipe(
132 Effect.annotateLogs({ threadId }),
133 Effect.as({
134 _tag: "missing",
135 } satisfies ThreadSnapshotLoader.ThreadSnapshotLoadResult),
136 ),
137 RemoteEnvironmentAuthInvalidJsonError: (error) =>
138 Effect.logDebug(
139 "Bounded thread snapshot returned an invalid response; trying the full HTTP thread snapshot for an older server.",
140 ).pipe(
141 Effect.annotateLogs({ threadId, cause: error.message }),
142 Effect.andThen(loadFullFallback),
143 ),
144 RemoteEnvironmentAuthUndeclaredStatusError: (error) =>
145 error.status === 404
146 ? Effect.logDebug(
147 "Bounded thread snapshot route was not found; trying the full HTTP thread snapshot for an older server.",
148 ).pipe(Effect.annotateLogs({ threadId }), Effect.andThen(loadFullFallback))
149 : Effect.fail(error),
150 }),
151 Effect.catchCause((cause) =>
152 Effect.logWarning(
153 "Could not load the bounded thread snapshot over HTTP; using the socket snapshot instead.",
154 ).pipe(
155 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
156 Effect.as({
157 _tag: "unavailable",
158 } satisfies ThreadSnapshotLoader.ThreadSnapshotLoadResult),
159 ),
160 ),
161 );
162 },
163 });
164 }),
165);