fix(connect): remove tunnels after hosts go offline #9386
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 30 commits into
main fromrefs/pull/9386/headmerged by juliusmarminge 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:XXL
- infra/relay/src/environments/ManagedEndpointAllocations.ts line 579Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -346,0 +553,21 @@553+ .from(relayManagedEndpointAllocations)554+ .where(555+ and(556+ whereAllocation(input),557+ eq(relayManagedEndpointAllocations.tunnelId, input.tunnelId),558+ eq(relayManagedEndpointAllocations.generation, input.generation),559+ ),560+ )561+ .limit(1)562+ .for("update")563+ .pipe(564+ Effect.mapError(lockError),565+ Effect.flatMap((rows) =>566+ rows.length === 0567+ ? Effect.succeed(Option.none())568+ : effect.pipe(Effect.map(Option.some)),569+ ),570+ ),571+ )572+ .pipe(Effect.mapError((cause) => (isSqlError(cause) ? lockError(cause) : cause)));573+ },
- apps/server/src/cloud/http.ts line 896OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -632,3 +877,20 @@632877 export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileDesiredLink")(633878 function* (localOrigin: string) {634- return yield* reconcileDesiredCloudLinkWith(yield* cloudHttpDependencies, localOrigin);879+ const dependencies = yield* cloudHttpDependencies;880+ return yield* dependencies.endpointRuntime.withLinkStateLock(881+ reconcileDesiredCloudLinkWith(dependencies, localOrigin),882+ );883+ },884+);885+886+export const reconcileDesiredCloudLinkIfStillDesired = Effect.fn(887+ "environment.cloud.reconcileDesiredLinkIfStillDesired",888+)(function* (localOrigin: string) {889+ const dependencies = yield* cloudHttpDependencies;890+ return yield* dependencies.endpointRuntime.withLinkStateLock(891+ Effect.gen(function* () {892+ if (!(yield* readCliDesiredCloudLink)) {893+ return null;894+ }895+ const mode = yield* readCliDesiredLinkMode;896+ yield* reconcileDesiredCloudLinkWith(dependencies, localOrigin);@@ -496,6 +667,20 @@667+ if (endpointRuntimeStatus.status !== "running") {668+ return yield* new EnvironmentCloudEndpointUnavailableError({669+ message: "Managed endpoint runtime could not be started.",670+ endpointRuntimeStatus,671+ });672+ }673+ const marker = yield* encodeConfirmedOriginJson({674+ config: payload.endpointRuntime,675+ origin: options.confirmedOrigin,676+ });677+ yield* dependencies.secrets.set(CLOUD_ENDPOINT_CONFIRMED_ORIGIN, stringToBytes(marker));678+ return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;679+ });680+ return yield* options?.lockHeld ? apply : dependencies.endpointRuntime.withLinkStateLock(apply);496681 });497682498683 const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(499684 function* (dependencies: CloudHttpDependencies, payload: RelayEnvironmentConfigRequest) {500685 yield* requireEnvironmentScope(AuthRelayWriteScope);501- return yield* applyCloudRelayConfig(dependencies, payload);686+ const result = yield* applyCloudRelayConfig(dependencies, payload);infra/relay/src/environments/ManagedEndpointProvider.ts line 1047OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -737,3 +1027,21 @@7371027 }),7381028 ),7391029 );1030+ if (tunnelGeneration === null) {1031+ if (selectedTunnel.created) {1032+ const current = yield* allocations.get(input).pipe(1033+ Effect.mapError(1034+ (cause) =>1035+ new ManagedEndpointProvisioningFailed({1036+ userId: input.userId,1037+ environmentId: input.environmentId,1038+ stage: "record-tunnel",1039+ hostname,1040+ tunnelName,1041+ tunnelId: tunnel.id,1042+ cause,1043+ }),1044+ ),1045+ );1046+ if (current?.tunnelId !== tunnel.id) {1047+ yield* ignoreNotFound(tunnels.delete(tunnel.id)).pipe(infra/relay/src/environments/ManagedEndpointProvider.ts line 701Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -517,0 +682,21 @@682+ .removeClaimed({683+ userId: input.userId,684+ environmentId: input.environmentId,685+ generation: claimedGeneration,686+ })687+ .pipe(688+ Effect.mapError(689+ (cause) =>690+ new ManagedEndpointDeprovisioningFailed({691+ ...input,692+ stage: "remove-allocation",693+ ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),694+ ...(allocation.dnsRecordId === null695+ ? {}696+ : { dnsRecordId: allocation.dnsRecordId }),697+ cause,698+ }),699+ ),700+ );701+ });702+ if (tunnelId === null) {apps/server/src/cloud/http.ts lines 895 to 897OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -633,2 +878,20 @@633878 function* (localOrigin: string) {634- return yield* reconcileDesiredCloudLinkWith(yield* cloudHttpDependencies, localOrigin);879+ const dependencies = yield* cloudHttpDependencies;880+ return yield* dependencies.endpointRuntime.withLinkStateLock(881+ reconcileDesiredCloudLinkWith(dependencies, localOrigin),882+ );883+ },884+);885+886+export const reconcileDesiredCloudLinkIfStillDesired = Effect.fn(887+ "environment.cloud.reconcileDesiredLinkIfStillDesired",888+)(function* (localOrigin: string) {889+ const dependencies = yield* cloudHttpDependencies;890+ return yield* dependencies.endpointRuntime.withLinkStateLock(891+ Effect.gen(function* () {892+ if (!(yield* readCliDesiredCloudLink)) {893+ return null;894+ }895+ const mode = yield* readCliDesiredLinkMode;896+ yield* reconcileDesiredCloudLinkWith(dependencies, localOrigin);897+ return mode;
- infra/relay/src/environments/ManagedEndpointProvider.ts lines 542 to 546Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -457,0 +526,21 @@526+ allocation.readyAt === null527+ ) {528+ return "recovery_required";529+ }530+ const cf = yield* requireCloudflareSettings(config, input);531+ const recordedEndpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({532+ allocation,533+ baseDomain: cf.baseDomain,534+ });535+ if (536+ recordedEndpoint === null ||537+ recordedEndpoint.httpBaseUrl !== input.endpoint.httpBaseUrl ||538+ recordedEndpoint.wsBaseUrl !== input.endpoint.wsBaseUrl ||539+ recordedEndpoint.providerKind !== input.endpoint.providerKind540+ ) {541+ return yield* new ManagedEndpointProvisioningFailed({542+ ...input,543+ stage: "sync-origin",544+ hostname: allocation.hostname,545+ cause: "The recorded tunnel endpoint does not match the active environment link.",546+ });
- @@ -467,0 +546,21 @@546+ readonly userId: string;547+ readonly environmentId: string;548+ readonly environmentPublicKey: string;549+ readonly tunnelId: string;550+ readonly origin: RelayManagedEndpointOrigin;551+}) {552+ const links = yield* EnvironmentLinks.EnvironmentLinks;553+ const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;554+ const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;555+ const link = yield* links.getForUser({556+ userId: input.userId,557+ environmentId: input.environmentId,558+ });559+ if (560+ link === null ||561+ link.environmentPublicKey !== input.environmentPublicKey ||562+ link.endpoint.providerKind !== "cloudflare_tunnel"563+ ) {564+ return yield* new HttpApiError.Unauthorized({});565+ }566+ const status = yield* managedEndpointProvider.reconcileOrigin({infra/relay/src/environments/ManagedEndpointProvider.ts line 758Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -554,11 +745,14 @@554745 if (allocation === null || tunnelId === null) {555746 return true;556747 }748+ if (input.expectedTunnelId !== undefined && input.expectedTunnelId !== tunnelId) {749+ return false;750+ }557751 // Claim the release against the allocation's current generation before558752 // touching Cloudflare. A provision racing this release (fast environment559- // restart) rewrites updatedAt when it records its tunnel, so a stale753+ // restart) increments the generation when it records its tunnel, so a stale560754 // claim means the recorded tunnel may already back a fresh connector and561755 // must be left alive. A provision that starts after the claim instead562756 // fails loudly on the deleted tunnel and the client-side retry563757 // provisions a replacement.564- const claimed = yield* allocations758+ const claimedGeneration = yield* allocations
- apps/server/src/cloud/http.ts lines 635 to 646Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -473,2 +613,20 @@613+) {614+ const apply = Effect.gen(function* () {615+ yield* validateRelayConfigPayload(payload);616+ yield* validateLinkedCloudUser({617+ secrets: dependencies.secrets,618+ cloudUserId: payload.cloudUserId,473619 });474- }620+ yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);621+ if (622+ payload.endpointRuntime !== null &&623+ payload.endpointRuntime.providerKind !== "cloudflare_tunnel"624+ ) {625+ const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(626+ payload.endpointRuntime,627+ );628+ return yield* new EnvironmentCloudEndpointUnavailableError({629+ message: "Managed endpoint runtime could not be started.",630+ endpointRuntimeStatus,631+ });632+ }infra/relay/src/environments/ManagedEndpointProvider.ts lines 790 to 792Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -593,3 +787,6 @@593787 }),594788 ),595789 );790+ if (input.expectedInactiveBefore !== undefined && input.expectedStatus !== undefined) {791+ const expectedStatus = input.expectedStatus;792+ const inactiveBefore = input.expectedInactiveBefore;infra/relay/src/environments/ManagedEndpointProvider.ts lines 1106 to 1113Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -771,10 +1132,11 @@7711132 proxied: true,7721133 } as const;7731134774- const dnsRecordId = yield* ensureDnsRecord(hostname, allocation.dnsRecordId, dnsRecord).pipe(775- Effect.mapError(776- (cause) =>777- new ManagedEndpointProvisioningFailed({778- userId: input.userId,779- environmentId: input.environmentId,780- stage: "ensure-dns-record",1135+ const recordedDns = yield* allocations1136+ .withClaimedTunnel(1137+ {1138+ userId: input.userId,1139+ environmentId: input.environmentId,1140+ tunnelId: tunnel.id,1141+ generation: tunnelGeneration,1142+ },
- infra/relay/src/environments/ManagedEndpointAllocations.ts line 10OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1,7 +1,10 @@1-import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";2-import { and, eq } from "drizzle-orm";1+import type { RelayManagedEndpoint, RelayManagedEndpointOrigin } from "@t3tools/contracts/relay";2+import { and, eq, exists, inArray, isNull, sql } from "drizzle-orm";3+import { QueryBuilder } from "drizzle-orm/pg-core";34 import * as Context from "effect/Context";45 import * as DateTime from "effect/DateTime";56 import * as Effect from "effect/Effect";67 import * as Layer from "effect/Layer";8+import * as Option from "effect/Option";79 import * as Schema from "effect/Schema";10+import { isSqlError } from "effect/unstable/sql/SqlError";
- docs/internals/t3-connect.md lines 87 to 87OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -67 +67,21 @@676768+## Idle tunnels are reclaimed and recovered69+70+Cloudflare bills a tunnel whether or not a connector is attached, so a laptop71+that sleeps with a linked environment leaves a paid tunnel behind. The relay's72+five-minute maintenance job can reclaim those tunnels. `RELAY_TUNNEL_CLEANUP_MODE`73+selects `off`, `dry-run`, or `enabled`, with `off` as the default. A candidate is74+a same-stage tunnel that Cloudflare reports down for at least five minutes, or75+one that never connected and is at least that old.76+77+Cleanup deletes only tunnels whose host has registered recovery, or tunnels with78+no allocation record at all. Allocations without recovery registration belong to79+hosts that cannot replace a deleted tunnel and are left alone. Allocations with80+no recorded tunnel ID, or a different tunnel ID, are skipped because a provision81+may own them. Each sweep is bounded: at most ten list requests, 100 deletions, a82+two-minute deadline, and an early stop on a Cloudflare rate limit. See the83+[reaper](../../infra/relay/src/environments/ManagedEndpointReaper.ts).84+85+A host registers recovery at startup by sending its tunnel ID and loopback86+origin with a short-lived signature from the environment key. Registration87+touches Cloudflare only when the local port changed. The host stores a
github-actions[bot](GitHub profile, opens in a new tab) added labels📱 Native Change
- @@ -753,2 +810,20 @@810+ retryRuntimeFailures: true,753811 }),754- Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),812+ (error) =>813+ shouldRetryCloudLink(error) &&814+ error._tag !== "EnvironmentCloudEndpointUnavailableError",815+ ).pipe(816+ Effect.tap((result) =>817+ result.status === "ready"818+ ? Effect.logInfo("T3 Connect managed tunnel recovery registered")819+ : Effect.void,820+ ),821+ Effect.catchCause((cause) =>822+ Cause.hasInterrupts(cause)823+ ? Effect.interrupt824+ : Effect.logWarning("Failed to register T3 Connect managed tunnel recovery", {825+ cause,826+ }).pipe(Effect.as({ status: "unavailable" as const })),827+ ),828+ );829+ const startedConfirmed = yield* startManagedCloudTunnelIfOriginConfirmed(
- @@ -743,10 +795,13 @@743795 // reachability after a restart.744- yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(745- Effect.retry({746- while: shouldRetryCloudLink,747- schedule: Schedule.exponential("1 second").pipe(748- Schedule.modifyDelay(({ duration }) =>749- Effect.succeed(Duration.min(duration, Duration.seconds(30))),796+ const wantsCliLink = hasCloudPublicConfig797+ ? yield* CloudCliState.readCliDesiredCloudLink.pipe(798+ Effect.catch((cause) =>799+ Effect.logWarning("Failed to read the desired T3 Connect link", { cause }).pipe(800+ Effect.as(false),801+ ),750802 ),751- Schedule.upTo({ duration: "10 minutes" }),752- ),803+ )804+ : false;805+ const desiredCliLinkMode = wantsCliLink806+ ? yield* CloudCliState.readCliDesiredLinkMode807+ : null;
github-actions[bot](GitHub profile, opens in a new tab) removed labels📱 Native Change
- infra/relay/src/environments/ManagedEndpointAllocations.ts line 26Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -18,8 +21,6 @@1821 readonly tunnelName: string;1922 readonly dnsRecordId: string | null;2023 readonly readyAt: string | null;21- /**22- * Doubles as the allocation's generation marker: every mutation rewrites it,23- * so `claimRelease` can detect a provision that raced a release.24- */24+ readonly origin: RelayManagedEndpointOrigin | null;2525 readonly updatedAt: string;26+ readonly generation: number;infra/relay/migrations/postgres/20260915062950_managed_endpoint_recovery/snapshot.json line 5OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,5 @@1+{2+ "version": "8",3+ "dialect": "postgres",4+ "id": "1bf86e6d-8ae5-4a2f-8f88-6b3ca69c26ac",5+ "prevIds": ["1109ed23-036c-4c39-a459-52422a7ffd99"],infra/relay/src/environments/ManagedEndpointReaper.ts line 169Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +149,21 @@149+ readonly status: "down" | "inactive";150+ readonly cutoff: DateTime.Utc;151+ }> = [];152+153+ for (const status of ["down", "inactive"] as const) {154+ const cutoff = cutoffFor(status);155+ const cutoffIso = DateTime.formatIso(cutoff);156+ const listPage = (page: number) => {157+ listRequests += 1;158+ return tunnels.list({159+ isDeleted: false,160+ includePrefix: prefix,161+ status,162+ existedAt: cutoffIso,163+ ...(status === "down" ? { wasInactiveAt: cutoffIso } : {}),164+ page,165+ perPage: MANAGED_ENDPOINT_SWEEP_PAGE_SIZE,166+ });167+ };168+ const first = yield* listPage(1);169+ const totalCount =
- @@ -630,0 +988,21 @@988+ environmentId,989+ cloudUserId: cloudUserIdValue,990+ relayUrl: relayUrlValue,991+ tunnelId: config.tunnelId,992+ origin,993+ });994+ const registered = yield* relayClientRequest(dependencies, {995+ url: `${relayUrlValue}/v1/environments/${encodeURIComponent(environmentId)}/tunnel/recovery`,996+ token: bytesToString(environmentCredential.value),997+ payload: {998+ cloudUserId: cloudUserIdValue,999+ tunnelId: config.tunnelId,1000+ origin,1001+ proof,1002+ },1003+ schema: RelayManagedEndpointRecoveryRegistrationResponse,1004+ });1005+ if (registered.status === "recovery_required") {1006+ return { status: registered.status, config };1007+ }1008+ const endpointRuntimeStatus = yield* activateManagedTunnelWithRetry(
- @@ -344,3 +536,9 @@344536 );345537 return claimed;346538 }),539+ withClaimedTunnel: Effect.fn("relay.managed_endpoint_allocations.with_claimed_tunnel")(540+ function* <A, E, R>(541+ input: ClaimManagedEndpointReleaseInput,542+ effect: Effect.Effect<A, E, R>,543+ ): Effect.fn.Return<Option.Option<A>, E | ManagedEndpointAllocationPersistenceError, R> {544+ const lockError = (cause: unknown) =>
- @@ -344,3 +536,18 @@344536 );345537 return claimed;346538 }),539+ withClaimedTunnel: Effect.fn("relay.managed_endpoint_allocations.with_claimed_tunnel")(540+ function* <A, E, R>(541+ input: ClaimManagedEndpointReleaseInput,542+ effect: Effect.Effect<A, E, R>,543+ ): Effect.fn.Return<Option.Option<A>, E | ManagedEndpointAllocationPersistenceError, R> {544+ const lockError = (cause: unknown) =>545+ new ManagedEndpointAllocationPersistenceError({546+ operation: "lock-tunnel",547+ stage: "database-request",548+ userId: input.userId,549+ environmentId: input.environmentId,550+ tunnelId: input.tunnelId,551+ cause,552+ });553+ return yield* db.$client
juliusmarminge merged this8d7b5e9
juliusmarminge closed this
Sign in to join this conversation.


Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
d4a3345· PR result:9f48a2c· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.