feat: T3 Connect environments switch to local connections automatically #5463
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromt3code/promote-t3-connect-localopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- packages/client-runtime/src/connection/promotion.ts line 80OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +60,21 @@60+ readonly endpoints: readonly AdvertisedEndpoint[];61+ readonly currentHttpBaseUrl: string;62+ readonly cooldownEndpointIds?: ReadonlySet<string>;63+}): readonly AdvertisedEndpoint[] {64+ const currentBaseUrl = normalizedBaseUrl(input.currentHttpBaseUrl);65+ return input.endpoints66+ .filter((endpoint) => {67+ if (endpoint.status === "unavailable") return false;68+ if (endpoint.reachability !== "lan" && endpoint.reachability !== "private-network") {69+ return false;70+ }71+ if (input.cooldownEndpointIds?.has(endpoint.id)) return false;72+ return normalizedBaseUrl(endpoint.httpBaseUrl) !== currentBaseUrl;73+ })74+ .sort(75+ (left, right) => reachabilityRank[left.reachability] - reachabilityRank[right.reachability],76+ )77+ .slice(0, MAX_PROBED_CANDIDATES);78+}79+80+interface PromotionCooldown {apps/server/src/remoteAccess/ServerAdvertisedEndpoints.ts lines 77 to 82OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +62,21 @@62+63+export interface ResolveServerAdvertisedEndpointsInput {64+ readonly port: number;65+ readonly host: string | undefined;66+ readonly networkInterfaces: TailscaleNetworkInterfaces;67+ readonly tailscaleEndpoints: readonly AdvertisedEndpoint[];68+}69+70+/** Pure projection of the server's own reachable endpoints, given its binding,71+ * the host's network interfaces, and any Tailscale endpoints resolved72+ * separately. Exported for tests. */73+export function resolveServerAdvertisedEndpoints(74+ input: ResolveServerAdvertisedEndpointsInput,75+): readonly AdvertisedEndpoint[] {76+ const mode = resolveBindingMode(input.host);77+ const loopbackEndpoint = createAdvertisedEndpoint({78+ provider: SERVER_ENDPOINT_PROVIDER,79+ source: "server",80+ id: `server-loopback:${input.port}`,81+ label: "This machine",82+ httpBaseUrl: `http://127.0.0.1:${input.port}`,apps/server/src/remoteAccess/ServerAdvertisedEndpoints.ts line 100Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +68,21 @@68+}69+70+/** Pure projection of the server's own reachable endpoints, given its binding,71+ * the host's network interfaces, and any Tailscale endpoints resolved72+ * separately. Exported for tests. */73+export function resolveServerAdvertisedEndpoints(74+ input: ResolveServerAdvertisedEndpointsInput,75+): readonly AdvertisedEndpoint[] {76+ const mode = resolveBindingMode(input.host);77+ const loopbackEndpoint = createAdvertisedEndpoint({78+ provider: SERVER_ENDPOINT_PROVIDER,79+ source: "server",80+ id: `server-loopback:${input.port}`,81+ label: "This machine",82+ httpBaseUrl: `http://127.0.0.1:${input.port}`,83+ reachability: "loopback",84+ status: "available",85+ description: "Loopback endpoint for this server.",86+ });87+88+ if (mode === "loopback") {
- packages/client-runtime/src/connection/promotion.ts line 165Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +141,21 @@141+ return override === undefined ? Option.none<PromotedRoute>() : Option.some(override);142+ });143+144+ const reportOverrideFailed = Effect.fn("ConnectionPromotion.reportOverrideFailed")(function* (145+ environmentId: EnvironmentId,146+ ) {147+ const override = (yield* Ref.get(overrides)).get(environmentId);148+ if (override === undefined) {149+ return;150+ }151+ const now = yield* Clock.currentTimeMillis;152+ yield* Ref.update(overrides, (current) => {153+ const next = new Map(current);154+ next.delete(environmentId);155+ return next;156+ });157+ yield* Ref.update(cooldowns, (current) => {158+ const next = new Map(current);159+ next.set(environmentId, { endpointId: override.endpointId, failedAtEpochMs: now });160+ return next;161+ });packages/client-runtime/src/authorization/service.ts line 382Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -298,0 +340,21 @@340+ detail: "Could not load the environment authorization key.",341+ }),342+ ),343+ );344+ const now = yield* Clock.currentTimeMillis;345+ const cached = yield* tokenStore.get(input.expectedEnvironmentId);346+ if (347+ Option.isNone(cached) ||348+ cached.value.dpopThumbprint !== thumbprint ||349+ cached.value.expiresAtEpochMs <= now + TOKEN_EXPIRY_SAFETY_MARGIN_MS350+ ) {351+ return yield* new ConnectionTransientError({352+ reason: "endpoint-unavailable",353+ detail: "No cached environment credential is available for the direct route.",354+ });355+ }356+ // The descriptor check keeps us from talking to an unrelated server that357+ // answers on the direct address.358+ const descriptor = yield* fetchDescriptor(input.endpoint.httpBaseUrl).pipe(359+ Effect.provideService(HttpClient.HttpClient, httpClient),360+ );
- apps/server/src/remoteAccess/ServerAdvertisedEndpoints.ts line 140Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +120,21 @@120+ provider: SERVER_ENDPOINT_PROVIDER,121+ source: "server",122+ id: `server-${reachability}:${httpBaseUrl}`,123+ label,124+ httpBaseUrl,125+ reachability,126+ status: "available",127+ }),128+ ];129+ }130+131+ const endpoints: AdvertisedEndpoint[] = [loopbackEndpoint];132+ const seen = new Set<string>();133+ let hasDefaultLan = false;134+135+ for (const interfaceAddresses of Object.values(input.networkInterfaces)) {136+ if (!interfaceAddresses) continue;137+138+ for (const entry of interfaceAddresses) {139+ if (entry.internal) continue;140+ if (!isIpv4Family(entry.family)) continue;apps/server/src/remoteAccess/ServerAdvertisedEndpoints.ts line 153Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ let hasDefaultLan = false;134+135+ for (const interfaceAddresses of Object.values(input.networkInterfaces)) {136+ if (!interfaceAddresses) continue;137+138+ for (const entry of interfaceAddresses) {139+ if (entry.internal) continue;140+ if (!isIpv4Family(entry.family)) continue;141+ const address = entry.address;142+ if (address.startsWith("127.") || address.startsWith("169.254.")) continue;143+ // Tailnet addresses are advertised by the Tailscale provider instead.144+ if (isTailscaleIpv4Address(address)) continue;145+ if (seen.has(address)) continue;146+ seen.add(address);147+148+ const isLan = isPrivateIpv4(address);149+ const httpBaseUrl = `http://${address}:${input.port}`;150+ const isDefault = isLan && !hasDefaultLan;151+ if (isDefault) hasDefaultLan = true;152+153+ endpoints.push(
- apps/server/src/remoteAccess/http.ts line 6OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+import { AuthRelayReadScope, EnvironmentHttpApi } from "@t3tools/contracts";2+import * as Effect from "effect/Effect";3+import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";4+5+import { annotateEnvironmentRequest, requireEnvironmentScope } from "../auth/http.ts";6+import { ServerAdvertisedEndpoints } from "./ServerAdvertisedEndpoints.ts";
- packages/client-runtime/src/connection/promotion.ts line 104Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +81,21 @@81+ * two flaky routes cannot clear each other's cooldown. */82+type PromotionCooldowns = ReadonlyMap<string, number>;83+84+/**85+ * Discovers direct routes for relay-connected environments and remembers the86+ * chosen route as a per-environment override. The relay connection broker87+ * consults the override at prepare time and tries the direct route before88+ * falling back to the managed relay tunnel; the supervisor runs `discover`89+ * over the live session after a relay connection is established.90+ */91+export class ConnectionPromotion extends Context.Service<92+ ConnectionPromotion,93+ {94+ /** Current route override for an environment, if a promotion is active. */95+ readonly overrideFor: (96+ environmentId: EnvironmentId,97+ ) => Effect.Effect<Option.Option<PromotedRoute>>;98+ /** Clears the override and starts the failure cooldown for its endpoint.99+ * Called when connecting through the override failed and the connection100+ * fell back to the relay. */101+ readonly reportOverrideFailed: (environmentId: EnvironmentId) => Effect.Effect<void>;
juliusmarminge added labelsmacroscope-review
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
5dcce6d0-0b9f-4fe9-8718-8e48cab2fcd2You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share