Skip to content
TypeScript

fix(connections): retry unsupported saved direct connections (#15107)

Nick Anisimov9878f487fac5
diff --git a/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx b/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx
index 5ea1f5c3dc5..dc498a873cc 100644
--- a/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx
+++ b/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx
@@ -2,7 +2,10 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import { ConnectionTraceId } from "./ConnectionTraceId";
import { useAuth } from "@clerk/expo";
import { SymbolView } from "../../components/ui/AppSymbol";
-import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
+import {
+ hasSavedBearerRoute,
+ type EnvironmentConnectionPhase,
+} from "@t3tools/client-runtime/connection";
import {
type EnvironmentId,
type EnvironmentMachineKind,
@@ -20,6 +23,7 @@ import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { serverEnvironment } from "../../state/server";
+import { environmentPresentations } from "../../state/presentation";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
@@ -185,6 +189,10 @@ function ConnectedCloudEnvironmentRow(props: {
serverEnvironment.configValueAtom(props.environment.environmentId),
);
const unsupported = props.environment.connectionState === "unsupported";
+ const presentation = useAtomValue(
+ environmentPresentations.presentationAtom(props.environment.environmentId),
+ );
+ const canRetry = presentation !== null && hasSavedBearerRoute(presentation.entry);
const enabled = props.environment.isEnabled && !unsupported;
const [lastDescriptor, setLastDescriptor] = useState(props.descriptor);
if (props.descriptor !== undefined && props.descriptor !== lastDescriptor) {
@@ -205,7 +213,7 @@ function ConnectedCloudEnvironmentRow(props: {
)}
onValueChange={props.onSetEnabled}
onToggleError={props.onToggleError}
- disabled={unsupported}
+ disabled={unsupported && !canRetry}
{...(enabled || unsupported ? {} : { statusText: "Off" })}
value={enabled}
/>
diff --git a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx
index 610312f9350..e3f76ef5014 100644
--- a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx
+++ b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx
@@ -1,6 +1,7 @@
import * as Dialog from "../../components/ui/Dialog";
import { ConnectionTraceId } from "./ConnectionTraceId";
import { SymbolView } from "../../components/ui/AppSymbol";
+import { hasSavedBearerRoute } from "@t3tools/client-runtime/connection";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
@@ -18,6 +19,7 @@ import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
import { cn } from "../../lib/cn";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { serverEnvironment } from "../../state/server";
+import { environmentPresentations } from "../../state/presentation";
import { ConnectionFormField } from "./ConnectionFormField";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { environmentStatusText } from "./environmentStatusText";
@@ -52,6 +54,10 @@ export function ConnectionEnvironmentRow(props: {
serverEnvironment.configValueAtom(props.environment.environmentId),
);
const unsupported = props.environment.connectionState === "unsupported";
+ const presentation = useAtomValue(
+ environmentPresentations.presentationAtom(props.environment.environmentId),
+ );
+ const canRetry = presentation !== null && hasSavedBearerRoute(presentation.entry);
const enabled = props.environment.isEnabled && !unsupported;
const statusLabel = connectionStatusLabel(props.environment);
const statusTraceId = enabled ? props.environment.connectionErrorTraceId : null;
@@ -136,7 +142,7 @@ export function ConnectionEnvironmentRow(props: {
<ThemedSwitch
accessibilityLabel={`Enable ${props.environment.environmentLabel}`}
style={{ alignSelf: "center" }}
- disabled={unsupported}
+ disabled={unsupported && !canRetry}
onValueChange={(next) => props.onSetEnabled(props.environment.environmentId, next)}
value={enabled}
/>
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index b465b39cd2e..364475abc10 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -47,6 +47,7 @@ import {
RelayConnectionRegistration,
RelayConnectionTarget,
connectionRoutes,
+ hasSavedBearerRoute,
connectionStatusText,
environmentMcpUrl,
} from "@t3tools/client-runtime/connection";
@@ -1467,6 +1468,7 @@ function SavedBackendListRow({
const [permissionsOpen, setPermissionsOpen] = useState(false);
const environmentId = environment.environmentId;
const unsupported = environment.connection.phase === "unsupported";
+ const blocked = unsupported && !hasSavedBearerRoute(environment.entry);
const enabled = environment.entry.enabled && !unsupported;
const isConnected = environment.connection.phase === "connected";
const isRemoving = removingEnvironmentId === environmentId;
@@ -1704,14 +1706,14 @@ function SavedBackendListRow({
<Switch
size="sm"
checked={enabled}
- disabled={isRemoving || unsupported}
+ disabled={isRemoving || blocked}
aria-label={`${enabled ? "Switch off" : "Switch on"} ${environment.label}`}
onCheckedChange={(checked) => onSetEnabled(environmentId, checked)}
/>
}
/>
<TooltipPopup side="top">
- {unsupported ? "Client not supported" : enabled ? "Switch off" : "Switch on"}
+ {blocked ? "Client not supported" : enabled ? "Switch off" : "Switch on"}
</TooltipPopup>
</Tooltip>
<Menu>
diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts
index 279d39ecd70..35705a58188 100644
--- a/packages/client-runtime/src/connection/registry.test.ts
+++ b/packages/client-runtime/src/connection/registry.test.ts
@@ -995,39 +995,49 @@ describe("EnvironmentRegistry", () => {
}),
);
- it.effect("discovery keeps unsupported environments off until compatibility changes", () =>
- Effect.gen(function* () {
- const harness = yield* makeHarness([RELAY_TARGET], [], [], {
- initialDisabled: [RELAY_TARGET.environmentId],
- });
- yield* Effect.gen(function* () {
- const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
- yield* registry.start;
- const error = new ConnectionBlockedError({
- reason: "unsupported",
- detail: "Use a compatible client.",
+ it.effect.each([false, true])(
+ "discovery keeps unsupported environments off (learned route: %s)",
+ (learned) =>
+ Effect.gen(function* () {
+ const environmentId = BEARER_TARGET.environmentId;
+ const relay = new RelayConnectionTarget({ ...RELAY_TARGET, environmentId });
+ const profile = new BearerConnectionProfile({
+ ...BEARER_PROFILE,
+ learned: true,
+ authorization: "t3-connect",
});
- yield* registry.setCompatibility(RELAY_TARGET.environmentId, error);
- const entry = (yield* SubscriptionRef.get(registry.entries)).get(
- RELAY_TARGET.environmentId,
+ const harness = yield* makeHarness(
+ learned ? [relay, BEARER_TARGET] : [relay],
+ learned ? [profile] : [],
+ [],
+ { initialDisabled: [environmentId] },
);
- expect(entry).toMatchObject({ enabled: false, unsupportedReason: error.message });
- expect(
- yield* Effect.flip(registry.setEnabled(RELAY_TARGET.environmentId, true)),
- ).toMatchObject({ reason: "unsupported" });
- expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
- yield* registry.setCompatibility(RELAY_TARGET.environmentId, null);
- expect(
- (yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId)?.enabled,
- ).toBe(false);
- yield* registry.setEnabled(RELAY_TARGET.environmentId, true);
- yield* awaitConnectionState(
- registry,
- RELAY_TARGET.environmentId,
- (state) => state.phase === "connected",
- );
- }).pipe(Effect.provide(harness.layer));
- }),
+ yield* Effect.gen(function* () {
+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
+ yield* registry.start;
+ const error = new ConnectionBlockedError({
+ reason: "unsupported",
+ detail: "Use a compatible client.",
+ });
+ yield* registry.setCompatibility(environmentId, error);
+ const entry = (yield* SubscriptionRef.get(registry.entries)).get(environmentId);
+ expect(entry).toMatchObject({ enabled: false, unsupportedReason: error.message });
+ expect(yield* Effect.flip(registry.setEnabled(environmentId, true))).toMatchObject({
+ reason: "unsupported",
+ });
+ expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
+ yield* registry.setCompatibility(environmentId, null);
+ expect((yield* SubscriptionRef.get(registry.entries)).get(environmentId)?.enabled).toBe(
+ false,
+ );
+ yield* registry.setEnabled(environmentId, true);
+ yield* awaitConnectionState(
+ registry,
+ environmentId,
+ (state) => state.phase === "connected",
+ );
+ }).pipe(Effect.provide(harness.layer));
+ }),
);
it.effect("a socket preflight rejection persists the connection as switched off", () =>
@@ -1055,6 +1065,87 @@ describe("EnvironmentRegistry", () => {
}),
);
+ it.effect.each([
+ { outcome: "connects after a server update", compatible: true, relayFirst: false },
+ { outcome: "connects with a preferred relay route", compatible: true, relayFirst: true },
+ { outcome: "blocks again if still incompatible", compatible: false, relayFirst: false },
+ ])("retrying an unsupported saved URL $outcome", ({ compatible, relayFirst }) =>
+ Effect.gen(function* () {
+ const environmentId = BEARER_TARGET.environmentId;
+ const error = new ConnectionBlockedError({
+ reason: "unsupported",
+ detail: "Update the server to use this client.",
+ serverUpdateRequired: true,
+ });
+ const relay = new RelayConnectionTarget({
+ environmentId,
+ label: "Relay route",
+ });
+ const attempts = yield* Ref.make(0);
+ const retryStarted = yield* Deferred.make<void>();
+ const retryResult = yield* Deferred.make<ConnectionBlockedError | undefined>();
+ const harness = yield* makeHarness(
+ relayFirst ? [relay, BEARER_TARGET] : [BEARER_TARGET],
+ [BEARER_PROFILE],
+ [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]],
+ {
+ beforePrepareRoute: () =>
+ Effect.gen(function* () {
+ if ((yield* Ref.updateAndGet(attempts, (count) => count + 1)) === 1) return error;
+ yield* Deferred.succeed(retryStarted, undefined);
+ return yield* Deferred.await(retryResult);
+ }),
+ },
+ );
+ yield* Effect.gen(function* () {
+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
+ yield* registry.start;
+ const awaitDisabled = SubscriptionRef.changes(registry.entries).pipe(
+ Stream.filter((entries) => entries.get(environmentId)?.enabled === false),
+ Stream.take(1),
+ Stream.runDrain,
+ );
+ yield* awaitDisabled;
+ expect((yield* Ref.get(harness.storedDisabled)).has(environmentId)).toBe(true);
+ expect((yield* SubscriptionRef.get(registry.entries)).get(environmentId)).toMatchObject({
+ target: relayFirst ? relay : BEARER_TARGET,
+ enabled: false,
+ unsupportedReason: error.message,
+ serverUpdateRequired: true,
+ });
+ expect(yield* Ref.get(attempts)).toBe(1);
+
+ yield* registry.setEnabled(environmentId, true);
+ yield* Deferred.await(retryStarted);
+ const retrying = (yield* SubscriptionRef.get(registry.entries)).get(environmentId);
+ expect(retrying?.enabled).toBe(true);
+ expect(retrying?.unsupportedReason).toBeUndefined();
+ expect(retrying?.serverUpdateRequired).toBeUndefined();
+ expect((yield* Ref.get(harness.storedDisabled)).has(environmentId)).toBe(false);
+
+ yield* Deferred.succeed(retryResult, compatible ? undefined : error);
+ if (compatible) {
+ yield* awaitConnectionState(
+ registry,
+ environmentId,
+ (state) => state.phase === "connected",
+ );
+ expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
+ } else {
+ yield* awaitDisabled;
+ expect((yield* SubscriptionRef.get(registry.entries)).get(environmentId)).toMatchObject({
+ enabled: false,
+ unsupportedReason: error.message,
+ serverUpdateRequired: true,
+ });
+ expect((yield* Ref.get(harness.storedDisabled)).has(environmentId)).toBe(true);
+ expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
+ }
+ expect(yield* Ref.get(attempts)).toBe(2);
+ }).pipe(Effect.provide(harness.layer));
+ }),
+ );
+
it.effect("switching an environment off disconnects it and persists the flag", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([RELAY_TARGET]);
diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.ts
index c3ad705e3d2..32ad38d1f08 100644
--- a/packages/client-runtime/src/connection/registry.ts
+++ b/packages/client-runtime/src/connection/registry.ts
@@ -50,6 +50,7 @@ import {
credentialConnectionId,
entryWithRoutes,
findRouteToSameAddress,
+ hasSavedBearerRoute,
mergeLearnedRoutes,
routesAfterRemoving,
upsertRoute,
@@ -1019,19 +1020,22 @@ export const make = Effect.gen(function* () {
environmentId,
Effect.gen(function* () {
const entry = yield* getEntry(environmentId);
- if (enabled && entry.unsupportedReason !== undefined) {
+ const retryUnsupported = enabled && entry.unsupportedReason !== undefined;
+ if (retryUnsupported && !hasSavedBearerRoute(entry)) {
return yield* new ConnectionBlockedError({
reason: "unsupported",
detail: entry.unsupportedReason,
});
}
- if (entry.enabled === enabled) {
+ if (entry.enabled === enabled && !retryUnsupported) {
return;
}
if (!(yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
yield* registrations.setEnabled(environmentId, enabled);
}
- const next: ConnectionCatalogEntry = { ...entry, enabled };
+ // A cached rejection can outlive a server update.
+ const { unsupportedReason: _reason, serverUpdateRequired: _update, ...rest } = entry;
+ const next: ConnectionCatalogEntry = { ...(retryUnsupported ? rest : entry), enabled };
// Update the lease in place so the supervisor keeps its generation and
// durable streams; `installEntryLocked` would tear it down instead.
const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
diff --git a/packages/client-runtime/src/connection/routes.ts b/packages/client-runtime/src/connection/routes.ts
index 9d70ea8c844..23aa1efa36f 100644
--- a/packages/client-runtime/src/connection/routes.ts
+++ b/packages/client-runtime/src/connection/routes.ts
@@ -186,6 +186,10 @@ export function connectionRouteAddress(route: ConnectionRoute): string | null {
return routeHttpBaseUrl(route);
}
+/** Learned routes alone must not make relay environments manually retryable. */
+export const hasSavedBearerRoute = (entry: ConnectionCatalogEntry) =>
+ connectionRoutes(entry).some((r) => !isLearned(r) && r.target._tag === "BearerConnectionTarget");
+
export function hasRelayRoute(
entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">,
): boolean {