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

shellSnapshotHttp.ts

133 lines5.5 KB

1import { EnvironmentHttpCommonError } 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 * as Schema from "effect/Schema";
8import { HttpClient, HttpClientError, type HttpClientResponse } from "effect/http";
9​
10import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
11import type { PreparedConnection } from "../connection/model.ts";
12import { environmentEndpointUrl } from "../environment/endpoint.ts";
13import * as ManagedRelay from "../relay/managedRelay.ts";
14import {
15 executeAuthenticatedEnvironmentHttpRequest,
16 withOrchestrationProtocolHeader,
17} from "./environmentHttpAuth.ts";
18import {
19 decodeShellSnapshotDeferringPullRequests,
20 type DeferredShellSnapshot,
21} from "./shellPullRequests.ts";
22​
23// Long enough for a slow but alive server to finish. On timeout the socket asks
24// the same server for the same full snapshot, so a short deadline only throws
25// the first build away. The socket fallback is for setups where /api fails but
26// /ws works, such as a proxy that blocks /api. A dead server is caught by the
27// socket ping, which drops the session and interrupts this load. The cached
28// shell renders while this runs.
29const DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS = 20_000;
30​
31/**
32 * Load the environment shell snapshot (projects + thread shells) over HTTP
33 * instead of as the WebSocket subscription's first frame. The response is
34 * gzip-compressible by the transport and keeps the (potentially large) list off
35 * the socket.
36 */
37export const fetchEnvironmentShellSnapshot = Effect.fn(
38 "clientRuntime.state.fetchEnvironmentShellSnapshot",
39)(function* (input: {
40 readonly prepared: PreparedConnection;
41 readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
42 readonly remoteAuthorization?: Option.Option<
43 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
44 >;
45 readonly timeoutMs?: number;
46}) {
47 return yield* executeAuthenticatedEnvironmentHttpRequest({
48 ...input,
49 group: "orchestration",
50 method: "GET",
51 url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/orchestration/shell"),
52 timeoutMs: input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
53 // The body is decoded here so each thread's pull request links can decode after its
54 // rows. Every declared error is an `EnvironmentHttpCommonError`, so decoding one keeps
55 // the error the credential retry checks for.
56 request: ({ client, headers }) =>
57 client
58 .shellSnapshot({
59 headers: withOrchestrationProtocolHeader(headers),
60 responseMode: "response-only",
61 })
62 .pipe(Effect.flatMap(decodeShellSnapshotResponse)),
63 });
64});
65​
66const decodeEnvironmentHttpCommonError = Schema.decodeUnknownEffect(
67 Schema.toCodecJson(EnvironmentHttpCommonError),
68);
69​
70const decodeShellSnapshotResponse = (
71 response: HttpClientResponse.HttpClientResponse,
72): Effect.Effect<
73 DeferredShellSnapshot,
74 HttpClientError.HttpClientError | Schema.SchemaError | EnvironmentHttpCommonError
75> => {
76 if (response.status === 200) {
77 return response.json.pipe(Effect.flatMap(decodeShellSnapshotDeferringPullRequests));
78 }
79 // A body that is not a declared error keeps its status, as the generated decoder reported.
80 const statusError = new HttpClientError.HttpClientError({
81 reason: new HttpClientError.StatusCodeError({ request: response.request, response }),
82 });
83 return response.json.pipe(
84 Effect.flatMap(decodeEnvironmentHttpCommonError),
85 Effect.matchEffect({
86 onFailure: () => Effect.fail(statusError),
87 onSuccess: Effect.fail,
88 }),
89 );
90};
91​
92/**
93 * Loads the environment shell snapshot over HTTP, returning `Option.none()` when
94 * it cannot be loaded (so the caller falls back to the socket-embedded snapshot).
95 * Decouples the shell state machine from the underlying HTTP + DPoP details and
96 * keeps them out of test contexts.
97 */
98export class ShellSnapshotLoader extends Context.Service<
99 ShellSnapshotLoader,
100 {
101 readonly load: (
102 prepared: PreparedConnection,
103 ) => Effect.Effect<Option.Option<DeferredShellSnapshot>>;
104 }
105>()("@t3tools/client-runtime/state/shellSnapshotHttp/ShellSnapshotLoader") {}
106​
107export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClient> = Layer.effect(
108 ShellSnapshotLoader,
109 Effect.gen(function* () {
110 const httpClient = yield* HttpClient.HttpClient;
111 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
112 // connections, so the loader must not hard-require it.
113 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
114 const remoteAuthorization = yield* Effect.serviceOption(
115 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
116 );
117 return ShellSnapshotLoader.of({
118 load: (prepared: PreparedConnection) =>
119 fetchEnvironmentShellSnapshot({ prepared, signer, remoteAuthorization }).pipe(
120 Effect.map(Option.some<DeferredShellSnapshot>),
121 Effect.provideService(HttpClient.HttpClient, httpClient),
122 Effect.catchCause((cause) =>
123 Effect.logWarning(
124 "Could not load the environment shell snapshot over HTTP; using the socket snapshot instead.",
125 ).pipe(
126 Effect.annotateLogs({ cause: Cause.pretty(cause) }),
127 Effect.as(Option.none<DeferredShellSnapshot>()),
128 ),
129 ),
130 ),
131 });
132 }),
133);