Open History to see the last commit
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 * as ManagedRelay from "../relay/managedRelay.ts";
13import {
14 executeAuthenticatedEnvironmentHttpRequest,
15 withOrchestrationProtocolHeader,
16} from "./environmentHttpAuth.ts";
17import {
18 decodeShellSnapshotDeferringPullRequests,
19 type DeferredShellSnapshot,
20} from "./shellPullRequests.ts";
21
22// On timeout the socket asks the same server for the same full snapshot, so a
23// short deadline only throws the first build away. The socket fallback is for
24// setups where /api fails but /ws works, such as a proxy that blocks /api.
25const DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS = 20_000;
26
27export const fetchEnvironmentShellSnapshot = Effect.fn(
28 "clientRuntime.state.fetchEnvironmentShellSnapshot",
29)(function* (input: {
30 readonly prepared: PreparedConnection;
31 readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
32 readonly remoteAuthorization?: Option.Option<
33 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
34 >;
35 readonly timeoutMs?: number;
36}) {
37 return yield* executeAuthenticatedEnvironmentHttpRequest({
38 ...input,
39 group: "orchestration",
40 method: "GET",
41 url: (urls) => urls.shellSnapshot(),
42 timeoutMs: input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
43 request: ({ client, headers }) =>
44 client
45 .shellSnapshot({
46 headers: withOrchestrationProtocolHeader(headers),
47 responseMode: "response-only",
48 })
49 .pipe(Effect.flatMap(decodeShellSnapshotResponse)),
50 });
51});
52
53const decodeEnvironmentHttpCommonError = Schema.decodeUnknownEffect(
54 Schema.toCodecJson(EnvironmentHttpCommonError),
55);
56
57const decodeShellSnapshotResponse = (
58 response: HttpClientResponse.HttpClientResponse,
59): Effect.Effect<
60 DeferredShellSnapshot,
61 HttpClientError.HttpClientError | Schema.SchemaError | EnvironmentHttpCommonError
62> => {
63 if (response.status === 200) {
64 return response.json.pipe(Effect.flatMap(decodeShellSnapshotDeferringPullRequests));
65 }
66 const statusError = new HttpClientError.HttpClientError({
67 reason: new HttpClientError.StatusCodeError({ request: response.request, response }),
68 });
69 return response.json.pipe(
70 Effect.flatMap(decodeEnvironmentHttpCommonError),
71 Effect.matchEffect({
72 onFailure: () => Effect.fail(statusError),
73 onSuccess: Effect.fail,
74 }),
75 );
76};
77
78export class ShellSnapshotLoader extends Context.Service<
79 ShellSnapshotLoader,
80 {
81 readonly load: (
82 prepared: PreparedConnection,
83 ) => Effect.Effect<Option.Option<DeferredShellSnapshot>>;
84 }
85>()("@t3tools/client-runtime/state/shellSnapshotHttp/ShellSnapshotLoader") {}
86
87export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClient> = Layer.effect(
88 ShellSnapshotLoader,
89 Effect.gen(function* () {
90 const httpClient = yield* HttpClient.HttpClient;
91 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
92 // connections, so the loader must not hard-require it.
93 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
94 const remoteAuthorization = yield* Effect.serviceOption(
95 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
96 );
97 return ShellSnapshotLoader.of({
98 load: (prepared: PreparedConnection) =>
99 fetchEnvironmentShellSnapshot({ prepared, signer, remoteAuthorization }).pipe(
100 Effect.map(Option.some<DeferredShellSnapshot>),
101 Effect.provideService(HttpClient.HttpClient, httpClient),
102 Effect.catchCause((cause) =>
103 Effect.logWarning(
104 "Could not load the environment shell snapshot over HTTP; using the socket snapshot instead.",
105 ).pipe(
106 Effect.annotateLogs({ cause: Cause.pretty(cause) }),
107 Effect.as(Option.none<DeferredShellSnapshot>()),
108 ),
109 ),
110 ),
111 });
112 }),
113);