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

shellSnapshotHttp.ts

114 lines4.4 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 * 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({ query: { compactPullRequests: "true" } }),
42 timeoutMs: input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
43 request: ({ client, headers }) =>
44 client
45 .shellSnapshot({
46 headers: withOrchestrationProtocolHeader(headers),
47 query: { compactPullRequests: "true" },
48 responseMode: "response-only",
49 })
50 .pipe(Effect.flatMap(decodeShellSnapshotResponse)),
51 });
52});
53​
54const decodeEnvironmentHttpCommonError = Schema.decodeUnknownEffect(
55 Schema.toCodecJson(EnvironmentHttpCommonError),
56);
57​
58const decodeShellSnapshotResponse = (
59 response: HttpClientResponse.HttpClientResponse,
60): Effect.Effect<
61 DeferredShellSnapshot,
62 HttpClientError.HttpClientError | Schema.SchemaError | EnvironmentHttpCommonError
63> => {
64 if (response.status === 200) {
65 return response.json.pipe(Effect.flatMap(decodeShellSnapshotDeferringPullRequests));
66 }
67 const statusError = new HttpClientError.HttpClientError({
68 reason: new HttpClientError.StatusCodeError({ request: response.request, response }),
69 });
70 return response.json.pipe(
71 Effect.flatMap(decodeEnvironmentHttpCommonError),
72 Effect.matchEffect({
73 onFailure: () => Effect.fail(statusError),
74 onSuccess: Effect.fail,
75 }),
76 );
77};
78​
79export class ShellSnapshotLoader extends Context.Service<
80 ShellSnapshotLoader,
81 {
82 readonly load: (
83 prepared: PreparedConnection,
84 ) => Effect.Effect<Option.Option<DeferredShellSnapshot>>;
85 }
86>()("@t3tools/client-runtime/state/shellSnapshotHttp/ShellSnapshotLoader") {}
87​
88export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClient> = Layer.effect(
89 ShellSnapshotLoader,
90 Effect.gen(function* () {
91 const httpClient = yield* HttpClient.HttpClient;
92 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
93 // connections, so the loader must not hard-require it.
94 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
95 const remoteAuthorization = yield* Effect.serviceOption(
96 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
97 );
98 return ShellSnapshotLoader.of({
99 load: (prepared: PreparedConnection) =>
100 fetchEnvironmentShellSnapshot({ prepared, signer, remoteAuthorization }).pipe(
101 Effect.map(Option.some<DeferredShellSnapshot>),
102 Effect.provideService(HttpClient.HttpClient, httpClient),
103 Effect.catchCause((cause) =>
104 Effect.logWarning(
105 "Could not load the environment shell snapshot over HTTP; using the socket snapshot instead.",
106 ).pipe(
107 Effect.annotateLogs({ cause: Cause.pretty(cause) }),
108 Effect.as(Option.none<DeferredShellSnapshot>()),
109 ),
110 ),
111 ),
112 });
113 }),
114);