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

shellSnapshotHttp.ts

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