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