Open History to see the last commit
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 method: "GET",
38 url: (httpBaseUrl) =>
39 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}/bounded`),
40 timeoutMs: input.timeoutMs ?? DEFAULT_BOUNDED_THREAD_SNAPSHOT_TIMEOUT_MS,
41 request: ({ client, headers }) =>
42 client.orchestration.threadBoundedSnapshot({
43 params: { threadId: input.threadId },
44 headers: withOrchestrationProtocolHeader(headers),
45 }),
46 });
47});
48
49/**
50 * Shared ThreadSnapshotLoader for clients that render progressive history.
51 * Seeds from the bounded HTTP snapshot when available. Older servers that lack
52 * the bounded route (plain/generic 404) fall back to the existing full HTTP
53 * thread snapshot. Structured EnvironmentResourceNotFoundError from either
54 * endpoint still means missing. Transient failures report `unavailable` so the
55 * socket path remains a last resort for connectivity issues.
56 */
57export const boundedThreadSnapshotLoaderLayer: Layer.Layer<
58 ThreadSnapshotLoader,
59 never,
60 HttpClient.HttpClient
61> = Layer.effect(
62 ThreadSnapshotLoader,
63 Effect.gen(function* () {
64 const httpClient = yield* HttpClient.HttpClient;
65 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
66 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
67 return ThreadSnapshotLoader.of({
68 load: (prepared: PreparedConnection, threadId: ThreadId) => {
69 const loadFullFallback = fetchEnvironmentThreadSnapshot({
70 prepared,
71 threadId,
72 signer,
73 remoteAuthorization,
74 }).pipe(
75 Effect.map((snapshot): ThreadSnapshotLoadResult => ({
76 _tag: "present",
77 snapshot,
78 })),
79 Effect.provideService(HttpClient.HttpClient, httpClient),
80 Effect.catchTags({
81 EnvironmentResourceNotFoundError: () =>
82 Effect.logDebug(
83 "Full thread snapshot not found over HTTP after bounded fallback; treating the thread as deleted.",
84 ).pipe(
85 Effect.annotateLogs({ threadId }),
86 Effect.as({ _tag: "missing" } satisfies ThreadSnapshotLoadResult),
87 ),
88 }),
89 Effect.catchCause((cause) =>
90 Effect.logWarning(
91 "Could not load the full thread snapshot over HTTP after bounded fallback; using the socket snapshot instead.",
92 ).pipe(
93 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
94 Effect.as({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult),
95 ),
96 ),
97 );
98
99 return fetchEnvironmentBoundedThreadSnapshot({
100 prepared,
101 threadId,
102 signer,
103 remoteAuthorization,
104 }).pipe(
105 Effect.map((bounded): ThreadSnapshotLoadResult => ({
106 _tag: "present",
107 snapshot: {
108 snapshotSequence: bounded.snapshotSequence,
109 projection: bounded.projection,
110 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
111 },
112 history: {
113 historyCursor: bounded.historyCursor,
114 hasMoreHistory: bounded.hasMoreHistory,
115 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
116 },
117 })),
118 Effect.provideService(HttpClient.HttpClient, httpClient),
119 Effect.catchTags({
120 EnvironmentResourceNotFoundError: () =>
121 Effect.logDebug(
122 "Bounded thread snapshot not found over HTTP; treating the thread as deleted.",
123 ).pipe(
124 Effect.annotateLogs({ threadId }),
125 Effect.as({ _tag: "missing" } satisfies ThreadSnapshotLoadResult),
126 ),
127 RemoteEnvironmentAuthInvalidJsonError: (error) =>
128 Effect.logDebug(
129 "Bounded thread snapshot returned an invalid response; trying the full HTTP thread snapshot for an older server.",
130 ).pipe(
131 Effect.annotateLogs({ threadId, cause: error.message }),
132 Effect.andThen(loadFullFallback),
133 ),
134 RemoteEnvironmentAuthUndeclaredStatusError: (error) =>
135 error.status === 404
136 ? Effect.logDebug(
137 "Bounded thread snapshot route was not found; trying the full HTTP thread snapshot for an older server.",
138 ).pipe(Effect.annotateLogs({ threadId }), Effect.andThen(loadFullFallback))
139 : Effect.fail(error),
140 }),
141 Effect.catchCause((cause) =>
142 Effect.logWarning(
143 "Could not load the bounded thread snapshot over HTTP; using the socket snapshot instead.",
144 ).pipe(
145 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
146 Effect.as({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult),
147 ),
148 ),
149 );
150 },
151 });
152 }),
153);