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

boundedThreadSnapshotHttp.ts

120 lines4.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", 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 * A structured EnvironmentResourceNotFoundError means the thread is missing. Any other failure
56 * leaves the snapshot to the socket.
57 */
58export const layer: Layer.Layer<
59 ThreadSnapshotLoader.ThreadSnapshotLoader,
60 never,
61 HttpClient.HttpClient
62> = Layer.effect(
63 ThreadSnapshotLoader.ThreadSnapshotLoader,
64 Effect.gen(function* () {
65 const httpClient = yield* HttpClient.HttpClient;
66 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
67 const remoteAuthorization = yield* Effect.serviceOption(
68 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
69 );
70 return ThreadSnapshotLoader.ThreadSnapshotLoader.of({
71 load: Effect.fn("ThreadSnapshotLoader.load")(function (
72 prepared: PreparedConnection,
73 threadId: ThreadId,
74 ) {
75 return fetchEnvironmentBoundedThreadSnapshot({
76 prepared,
77 threadId,
78 signer,
79 remoteAuthorization,
80 }).pipe(
81 Effect.map((bounded): ThreadSnapshotLoader.ThreadSnapshotLoadResult => ({
82 _tag: "present",
83 snapshot: {
84 snapshotSequence: bounded.snapshotSequence,
85 projection: bounded.projection,
86 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
87 },
88 history: {
89 historyCursor: bounded.historyCursor,
90 hasMoreHistory: bounded.hasMoreHistory,
91 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
92 },
93 })),
94 Effect.provideService(HttpClient.HttpClient, httpClient),
95 Effect.catchTags({
96 EnvironmentResourceNotFoundError: () =>
97 Effect.logDebug(
98 "Bounded thread snapshot not found over HTTP; 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 bounded thread snapshot over HTTP; 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 });
119 }),
120);