diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts index c192e901961c6..a9aef06d93d34 100644 --- a/packages/client-runtime/src/connection/registry.test.ts +++ b/packages/client-runtime/src/connection/registry.test.ts @@ -5,6 +5,7 @@ import { ORCHESTRATION_PROTOCOL_VERSION, type ExecutionEnvironmentDescriptor, type ServerConfig, + type ServerConfigStreamEvent, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Context from "effect/Context"; @@ -21,6 +22,7 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Tracer from "effect/Tracer"; +import * as TestClock from "effect/testing/TestClock"; import * as ClientCapabilities from "../platform/capabilities.ts"; import * as TokenStore from "../authorization/tokenStore.ts"; @@ -42,7 +44,7 @@ import * as Connectivity from "./connectivity.ts"; import * as ConnectionCredentialStore from "./credentialStore.ts"; import * as ConnectionDriver from "./driver.ts"; import type { RouteCheck } from "./driver.ts"; -import { connectionRouteId, connectionRouteKind } from "./routes.ts"; +import { connectionRouteId, connectionRouteKind, connectionRoutes } from "./routes.ts"; import { ConnectionTransientError, ConnectionBlockedError, @@ -168,6 +170,9 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( ) => Effect.Effect; readonly initialDisabled?: ReadonlyArray; readonly directEndpoints?: ServerConfig["directEndpoints"]; + readonly configEvents?: Stream.Stream; + readonly beforeProfilePut?: Effect.Effect; + readonly beforeSetRoutes?: Effect.Effect; }, ) { const storedTargets = yield* Ref.make>(initialTargets); @@ -235,7 +240,11 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( } }), setRoutes: (environmentId, routes) => - Ref.update(storedTargets, (current) => replaceRoutes(current, environmentId, routes)), + (options?.beforeSetRoutes ?? Effect.void).pipe( + Effect.andThen( + Ref.update(storedTargets, (current) => replaceRoutes(current, environmentId, routes)), + ), + ), remove: (environmentId) => Effect.gen(function* () { yield* options?.beforeRegistrationRemove?.(environmentId) ?? Effect.void; @@ -323,11 +332,15 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))), ), put: (profile) => - Ref.update(storedProfiles, (current) => { - const next = new Map(current); - next.set(profile.connectionId, profile); - return next; - }), + (options?.beforeProfilePut ?? Effect.void).pipe( + Effect.andThen( + Ref.update(storedProfiles, (current) => { + const next = new Map(current); + next.set(profile.connectionId, profile); + return next; + }), + ), + ), remove: (connectionId) => Ref.update(storedProfiles, (current) => { const next = new Map(current); @@ -419,13 +432,14 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( ? Effect.die(new Error("Config is not used by registry tests.")) : Effect.succeed({ directEndpoints: options.directEndpoints } as ServerConfig), subscribeServerConfig: () => - options?.directEndpoints === undefined + options?.configEvents ?? + (options?.directEndpoints === undefined ? Stream.never : Stream.make({ version: 1 as const, type: "snapshot" as const, config: { directEndpoints: options.directEndpoints } as ServerConfig, - }), + })), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), @@ -2406,6 +2420,169 @@ describe("EnvironmentRegistry routes", () => { }), ); + it.effect( + "saves a direct route when a later snapshot repeats an endpoint after a write failure", + () => + Effect.gen(function* () { + const storageAvailable = yield* Deferred.make(); + const firstSnapshotProcessed = yield* Deferred.make(); + const snapshotsProcessed = yield* Deferred.make(); + const httpBaseUrl = "https://devbox.tail1234.ts.net/"; + const snapshot = { + version: 1, + type: "snapshot", + config: { + availableEditors: [], + directEndpoints: [{ kind: "tailnet", httpBaseUrl }], + } as unknown as ServerConfig, + } satisfies ServerConfigStreamEvent; + const harness = yield* makeHarness([RELAY_TARGET], [], [], { + beforeProfilePut: Deferred.isDone(storageAvailable).pipe( + Effect.flatMap((available) => + available + ? Effect.void + : Effect.fail( + new ConnectionTransientError({ + reason: "remote-unavailable", + detail: "Temporary storage failure", + }), + ), + ), + ), + configEvents: Stream.concat( + Stream.make(snapshot), + Stream.fromEffect( + Deferred.succeed(firstSnapshotProcessed, undefined).pipe( + Effect.andThen(Deferred.await(storageAvailable)), + Effect.as({ + ...snapshot, + config: { ...snapshot.config, availableEditors: ["file-manager"] }, + } satisfies ServerConfigStreamEvent), + ), + ), + ).pipe(Stream.ensuring(Deferred.succeed(snapshotsProcessed, undefined))), + }); + yield* Effect.gen(function* () { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + yield* registry.start; + yield* Deferred.await(firstSnapshotProcessed); + expect(yield* Ref.get(harness.storedTargets)).toEqual([RELAY_TARGET]); + yield* Deferred.succeed(storageAvailable, undefined); + yield* Deferred.await(snapshotsProcessed); + const routes = routesOf( + yield* Ref.get(harness.storedTargets), + RELAY_TARGET.environmentId, + ); + expect(routes.length).toBe(2); + const learned = routes.find((route) => route._tag === "BearerConnectionTarget"); + expect(learned).toMatchObject({ environmentId: RELAY_TARGET.environmentId }); + expect((yield* Ref.get(harness.storedProfiles)).get(learned!.connectionId)).toMatchObject( + { + httpBaseUrl, + learned: true, + network: "tailscale", + }, + ); + }).pipe(Effect.provide(harness.layer)); + }), + ); + + it.effect.each(["disconnect", "remove"] as const)( + "%s during a learned route save retry", + (action) => + Effect.gen(function* () { + const publish = yield* Deferred.make(); + const firstSaveFinished = yield* Deferred.make(); + const storageStarted = yield* Deferred.make(); + const finishStorage = yield* Deferred.make(); + const removalStarted = yield* Deferred.make(); + const finishRemoval = yield* Deferred.make(); + const attempts = yield* Ref.make(0); + const harness = yield* makeHarness([RELAY_TARGET], [], [], { + configEvents: Stream.fromEffect( + Deferred.await(publish).pipe( + Effect.as({ + version: 1, + type: "snapshot", + config: { + directEndpoints: [ + { kind: "tailnet", httpBaseUrl: "https://devbox.tail1234.ts.net/" }, + ], + } as unknown as ServerConfig, + } satisfies ServerConfigStreamEvent), + ), + ).pipe( + Stream.concat( + Stream.fromEffect(Deferred.succeed(firstSaveFinished, undefined)).pipe(Stream.drain), + ), + Stream.concat(Stream.never), + ), + beforeProfilePut: Ref.updateAndGet(attempts, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 1 + ? Effect.fail( + new ConnectionTransientError({ + reason: "remote-unavailable", + detail: "Temporary storage failure", + }), + ) + : Effect.void, + ), + ), + beforeSetRoutes: Deferred.succeed(storageStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishStorage)), + ), + beforeRegistrationRemove: () => + Deferred.succeed(removalStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishRemoval)), + ), + }); + yield* Effect.gen(function* () { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + yield* registry.start; + if (action === "remove") { + yield* Deferred.succeed(publish, undefined); + yield* Deferred.await(firstSaveFinished); + const removal = yield* registry + .remove(RELAY_TARGET.environmentId) + .pipe(Effect.forkChild); + yield* Deferred.await(removalStarted); + yield* TestClock.adjust("2 seconds"); + yield* Deferred.succeed(finishRemoval, undefined); + yield* Fiber.join(removal); + expect( + (yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId), + ).toBe(false); + expect(yield* Ref.get(harness.storedTargets)).toEqual([]); + return; + } + + yield* registry.run( + RELAY_TARGET.environmentId, + Effect.gen(function* () { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + yield* Deferred.succeed(publish, undefined); + yield* Deferred.await(firstSaveFinished); + yield* TestClock.adjust("2 seconds"); + yield* Deferred.await(storageStarted); + yield* supervisor.disconnect; + yield* TestClock.adjust(0); + yield* Deferred.succeed(finishStorage, undefined); + yield* TestClock.adjust(0); + }), + ); + const entry = (yield* SubscriptionRef.get(registry.entries)).get( + RELAY_TARGET.environmentId, + ); + expect(entry && connectionRoutes(entry).map((route) => route.target)).toEqual( + yield* Ref.get(harness.storedTargets), + ); + expect(yield* Ref.get(harness.storedTargets)).toHaveLength(2); + expect(yield* Ref.get(harness.releasedSessions)).toBe(1); + }).pipe(Effect.provide(harness.layer)); + }), + ); + it.effect("saves the Tailscale mark when the server reports a learned address as tailnet", () => Effect.gen(function* () { const httpBaseUrl = "http://100.101.102.103:3773/"; diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.ts index b8f408afa39f0..08c6d39cdb641 100644 --- a/packages/client-runtime/src/connection/registry.ts +++ b/packages/client-runtime/src/connection/registry.ts @@ -954,6 +954,8 @@ export const make = Effect.gen(function* () { readonly activeRoute: ConnectionRoute; readonly reported: ReadonlyArray; }) { + // Keep lock acquisition interruptible. Once locked, publish the result of a + // catalog write even if the session closes while desktop IPC is pending. return yield* withLeaseLock( input.environmentId, Effect.gen(function* () { @@ -997,13 +999,13 @@ export const make = Effect.gen(function* () { new Map(current).set(input.environmentId, next), ); return Option.some(next); - }), + }).pipe(Effect.uninterruptible), ).pipe( - Effect.catch((error) => + Effect.tapError((error) => Effect.logWarning("Could not save routes learned from the environment.", { environmentId: input.environmentId, error, - }).pipe(Effect.as(Option.none())), + }), ), ); }); diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts index 0c8c29fee863e..2551bdd10bf48 100644 --- a/packages/client-runtime/src/connection/supervisor.test.ts +++ b/packages/client-runtime/src/connection/supervisor.test.ts @@ -2852,7 +2852,16 @@ describe("EnvironmentSupervisor routes", () => { }), ); - it.effect.each(["initial", "late", "withdrawn", "withdrawn-upgrade", "omitted"] as const)( + const directEndpointReports = [ + "initial", + "late", + "withdrawn", + "withdrawn-upgrade", + "omitted", + "retry", + "retry-disconnect", + ] as const; + it.effect.each(directEndpointReports)( "learns the %s direct endpoint over T3 Connect", (discovery) => Effect.gen(function* () { @@ -2885,6 +2894,10 @@ describe("EnvironmentSupervisor routes", () => { const discoveryProcessed = yield* Deferred.make(); const discoveryStarted = yield* Deferred.make(); const finishDiscovery = yield* Deferred.make(); + const retrying = discovery === "retry" || discovery === "retry-disconnect"; + const saveAttempts = yield* Ref.make(0); + const retryWaiting = yield* Deferred.make(); + const releaseSaveLock = yield* Deferred.make(); const lateAddress = "https://fixture.tail1234.ts.net/"; const learned = yield* Ref.make>([]); const harness = yield* makeHarness({ @@ -2909,7 +2922,10 @@ describe("EnvironmentSupervisor routes", () => { }), ), ), - ).pipe(Stream.ensuring(Deferred.succeed(discoveryProcessed, undefined))) + ).pipe( + Stream.concat(retrying ? Stream.never : Stream.empty), + Stream.ensuring(Deferred.succeed(discoveryProcessed, undefined)), + ) : undefined, checkRoute: (route) => route.target._tag === "BearerConnectionTarget" @@ -2938,6 +2954,16 @@ describe("EnvironmentSupervisor routes", () => { allowInsecure: true, }); if (routes === null) return Option.none(); + if (retrying) { + const attempt = yield* Ref.updateAndGet(saveAttempts, (count) => count + 1); + if (attempt === 1 || (attempt === 2 && discovery === "retry")) { + return yield* transient("Temporary storage failure."); + } + if (discovery === "retry-disconnect") { + yield* Deferred.succeed(retryWaiting, undefined); + yield* Deferred.await(releaseSaveLock); + } + } const next = entryWithRoutes(entry, routes); yield* Ref.set(current, next); yield* Ref.update(learned, (all) => [ @@ -2956,6 +2982,23 @@ describe("EnvironmentSupervisor routes", () => { yield* Deferred.await(discoveryStarted); } yield* Deferred.succeed(finishDiscovery, undefined); + if (discovery === "retry") { + yield* TestClock.adjust("5 seconds"); + expect(yield* Ref.get(learned)).toContain( + `learned:${TARGET.environmentId}:https://fixture.tail1234.ts.net`, + ); + return; + } + if (discovery === "retry-disconnect") { + yield* TestClock.adjust("2 seconds"); + yield* Deferred.await(retryWaiting); + yield* supervisor.disconnect; + yield* TestClock.adjust(0); + const released = yield* Ref.get(harness.releaseCount); + yield* Deferred.succeed(releaseSaveLock, undefined); + expect(released).toBe(1); + return; + } if (discovery === "withdrawn-upgrade") { yield* Deferred.await(discoveryProcessed); yield* TestClock.adjust("60 seconds"); diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts index 1230dc5928a63..79ed7a05043d6 100644 --- a/packages/client-runtime/src/connection/supervisor.ts +++ b/packages/client-runtime/src/connection/supervisor.ts @@ -4,6 +4,7 @@ import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -30,6 +31,7 @@ import { type SupervisorConnectionState, } from "./model.ts"; import * as RpcSession from "../rpc/session.ts"; +import type { ConnectionPersistenceError } from "../platform/persistence.ts"; import { safeErrorLogAttributes } from "../errors/safeLog.ts"; import { NETWORK_BLOCKING_HINT } from "../errors/network.ts"; import * as ConnectionWakeups from "./wakeups.ts"; @@ -44,6 +46,7 @@ import { } from "./routes.ts"; const RETRY_BASE_DELAY_MS = 1_000; +const LEARNED_ROUTE_SAVE_RETRY_DELAY_MS = 1_000; const RETRY_MAX_DELAY_MS = 300_000; const SESSION_LOSS_RETRY_DELAY_MS = 250; // Someone is approving this device on the host; check back soon rather than climbing the ladder. @@ -161,7 +164,10 @@ export interface EnvironmentSupervisorOptions { readonly learnRoutes?: (input: { readonly activeRoute: ConnectionRoute; readonly reported: ReadonlyArray; - }) => Effect.Effect>; + }) => Effect.Effect< + Option.Option, + ConnectionAttemptError | ConnectionPersistenceError + >; } function retryDelayMs(failureCount: number, random: number): number { @@ -367,18 +373,49 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( ) { const activeRoute = lease.activeRoute; if (activeRoute === undefined) return; + let handled: string | undefined; + let pendingRetry: { cancel: Deferred.Deferred; fiber: Fiber.Fiber } | undefined; + const save = Effect.fnUntraced(function* ( + reported: ReadonlyArray, + fingerprint: string, + ) { + const updated = yield* learn({ activeRoute, reported }).pipe( + Effect.orElseSucceed(() => undefined), + ); + handled = updated === undefined ? undefined : fingerprint; + if (updated === undefined) return false; + if (Option.isSome(updated)) { + yield* Ref.set(currentEntry, updated.value); + yield* requestBetterRouteCheck(lease); + } + return true; + }); yield* lease.session.subscribeServerConfig().pipe( Stream.filter((event) => event.type === "snapshot"), Stream.map((event) => event.config.directEndpoints), Stream.filter((reported) => reported !== undefined), - Stream.changesWith((previous, next) => JSON.stringify(previous) === JSON.stringify(next)), - Stream.runForEach((reported) => + Stream.map((reported) => ({ reported, fingerprint: JSON.stringify(reported) })), + Stream.runForEach(({ reported, fingerprint }) => Effect.gen(function* () { - const updated = yield* learn({ activeRoute, reported }); - if (Option.isSome(updated)) { - yield* Ref.set(currentEntry, updated.value); - yield* requestBetterRouteCheck(lease); + if (pendingRetry !== undefined) { + // Cancel the delay, or let an in-flight save finish before applying the newer report. + yield* Deferred.succeed(pendingRetry.cancel, undefined); + yield* Fiber.join(pendingRetry.fiber); + pendingRetry = undefined; } + if (fingerprint === handled) return; + if (yield* save(reported, fingerprint)) return; + const cancel = yield* Deferred.make(); + const fiber = yield* Effect.gen(function* () { + let delay = LEARNED_ROUTE_SAVE_RETRY_DELAY_MS; + while (true) { + const canceled = yield* Deferred.await(cancel).pipe(Effect.timeoutOption(delay)); + if (Option.isSome(canceled)) return; + if (yield* save(reported, fingerprint)) return; + delay = Math.min(delay * 2, RETRY_MAX_DELAY_MS); + } + }).pipe(Effect.forkChild); + pendingRetry = { cancel, fiber }; }), ), Effect.ignoreCause({ log: true }),