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

environmentProbe.ts

50 lines2.5 KB

1/**
2 * "Is a T3 Code server answering at this origin?" — shared by `t3 pair`
3 * discovery and by the Tailscale Serve ownership check, which both have to
4 * decide whether an endpoint is safe to take over.
5 */
6import { ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
10​
11const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
12const ENVIRONMENT_PROBE_TIMEOUT = Duration.millis(2_500);
13​
14/**
15 * Three outcomes, because they drive different decisions: a T3 descriptor
16 * (pair with it, or leave its serve mapping alone), nothing answering (safe to
17 * configure Tailscale Serve), or something answering that is not a T3 server
18 * (do NOT overwrite its mapping).
19 */
20export type EnvironmentProbeResult =
21 | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor }
22 | { readonly _tag: "unreachable" }
23 | { readonly _tag: "not-a-t3-server" };
24​
25export const probeEnvironmentDescriptor = (
26 baseUrl: string,
27): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>
28 Effect.gen(function* () {
29 const client = yield* HttpClient.HttpClient;
30 const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());
31 const response = yield* client.execute(request).pipe(
32 Effect.timeout(ENVIRONMENT_PROBE_TIMEOUT),
33 // Transport failure or timeout: nothing (reachable) is listening there.
34 Effect.mapError(() => ({ _tag: "unreachable" }) as const),
35 );
36 // Bad-gateway family means a proxy (Tailscale Serve) answered for a
37 // backend that is gone — a stale mapping, not a live occupant. Treating
38 // it as unreachable lets a server repair its own mapping after the
39 // previous owner's port went away.
40 if (response.status === 502 || response.status === 503 || response.status === 504) {
41 return { _tag: "unreachable" } as const;
42 }
43 // Anything else that answered HTTP but not with a valid descriptor is
44 // some other service.
45 const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(
46 Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),
47 Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const),
48 );
49 return { _tag: "descriptor", descriptor } as const;
50 }).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));