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

boundedThreadSnapshotHttp.ts

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