Open History to see the last commit
1import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import { HttpClient } from "effect/unstable/http";
8
9import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
10import type { PreparedConnection } from "../connection/model.ts";
11import { environmentEndpointUrl } from "../environment/endpoint.ts";
12import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
13import {
14 executeAuthenticatedEnvironmentHttpRequest,
15 withOrchestrationProtocolHeader,
16} from "./environmentHttpAuth.ts";
17
18// Long enough for a slow but alive server to finish. On timeout the socket asks
19// the same server for the same full snapshot, so a short deadline only throws
20// the first build away. The socket fallback is for setups where /api fails but
21// /ws works, such as a proxy that blocks /api. A dead server is caught by the
22// socket ping, which drops the session and interrupts this load. The cached
23// shell renders while this runs.
24const DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS = 20_000;
25
26/**
27 * Load the environment shell snapshot (projects + thread shells) over HTTP
28 * instead of as the WebSocket subscription's first frame. The response is
29 * gzip-compressible by the transport and keeps the (potentially large) list off
30 * the socket.
31 */
32export const fetchEnvironmentShellSnapshot = Effect.fn(
33 "clientRuntime.state.fetchEnvironmentShellSnapshot",
34)(function* (input: {
35 readonly prepared: PreparedConnection;
36 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
37 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
38 readonly timeoutMs?: number;
39}) {
40 return yield* executeAuthenticatedEnvironmentHttpRequest({
41 ...input,
42 group: "orchestration",
43 method: "GET",
44 url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/orchestration/shell"),
45 timeoutMs: input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
46 request: ({ client, headers }) =>
47 client.shellSnapshot({ headers: withOrchestrationProtocolHeader(headers) }),
48 });
49});
50
51/**
52 * Loads the environment shell snapshot over HTTP, returning `Option.none()` when
53 * it cannot be loaded (so the caller falls back to the socket-embedded snapshot).
54 * Decouples the shell state machine from the underlying HTTP + DPoP details and
55 * keeps them out of test contexts.
56 */
57export class ShellSnapshotLoader extends Context.Service<
58 ShellSnapshotLoader,
59 {
60 readonly load: (
61 prepared: PreparedConnection,
62 ) => Effect.Effect<Option.Option<OrchestrationV2ShellSnapshot>>;
63 }
64>()("@t3tools/client-runtime/state/shellSnapshotHttp/ShellSnapshotLoader") {}
65
66export const shellSnapshotLoaderLayer: Layer.Layer<
67 ShellSnapshotLoader,
68 never,
69 HttpClient.HttpClient
70> = Layer.effect(
71 ShellSnapshotLoader,
72 Effect.gen(function* () {
73 const httpClient = yield* HttpClient.HttpClient;
74 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
75 // connections, so the loader must not hard-require it.
76 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
77 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
78 return ShellSnapshotLoader.of({
79 load: (prepared: PreparedConnection) =>
80 fetchEnvironmentShellSnapshot({ prepared, signer, remoteAuthorization }).pipe(
81 Effect.map(Option.some<OrchestrationV2ShellSnapshot>),
82 Effect.provideService(HttpClient.HttpClient, httpClient),
83 Effect.catchCause((cause) =>
84 Effect.logWarning(
85 "Could not load the environment shell snapshot over HTTP; using the socket snapshot instead.",
86 ).pipe(
87 Effect.annotateLogs({ cause: Cause.pretty(cause) }),
88 Effect.as(Option.none<OrchestrationV2ShellSnapshot>()),
89 ),
90 ),
91 ),
92 });
93 }),
94);