Skip to content

Commit 4092c4a

Browse files
fix(client): retry the permissions check after a reconnect (#27008)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 08a463e commit 4092c4a

6 files changed

Lines changed: 230 additions & 16 deletions

File tree

‎apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@ import {
1212
isLearned,
1313
} from "@t3tools/client-runtime/connection";
1414
import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
15-
import { AUTH_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
15+
import {
16+
AUTH_SCOPE_OPTIONS,
17+
sessionPermissionsUnavailableMessage,
18+
} from "@t3tools/shared/authScopeOptions";
1619
import { AsyncResult } from "effect/reactivity";
1720
import * as Option from "effect/Option";
1821
import { useState } from "react";
@@ -163,8 +166,14 @@ export function EnvironmentRoutesSection({
163166
</>
164167
) : (
165168
<Text className="text-sm text-foreground-muted">
166-
Permissions not checked. Connect to this environment to view this session’s
167-
permissions.
169+
{sessionPermissionsUnavailableMessage({
170+
connected: activeRouteId !== null,
171+
failed: sessionResult._tag === "Failure",
172+
rejected:
173+
sessionResult._tag !== "Failure" &&
174+
!sessionResult.waiting &&
175+
session?.authenticated === false,
176+
})}
168177
</Text>
169178
)}
170179
</View>

‎apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
type ServerProvider,
99
} from "@t3tools/contracts";
1010
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11+
import { sessionPermissionsUnavailableMessage } from "@t3tools/shared/authScopeOptions";
1112
import * as Cause from "effect/Cause";
1213
import * as Exit from "effect/Exit";
1314
import { AsyncResult } from "effect/reactivity";
@@ -208,11 +209,14 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
208209
</Text>
209210
) : !allowed ? (
210211
<Text className="px-2 text-sm text-foreground-muted">
211-
{AsyncResult.isFailure(sessionResult)
212-
? "Could not verify your permissions. Reconnect to try again."
213-
: session === null
214-
? "Checking permissions…"
215-
: "This connection does not have permission to manage the environment."}
212+
{AsyncResult.isFailure(sessionResult) || session === null || !session.authenticated
213+
? sessionPermissionsUnavailableMessage({
214+
connected,
215+
failed: AsyncResult.isFailure(sessionResult),
216+
rejected:
217+
!AsyncResult.isFailure(sessionResult) && session?.authenticated === false,
218+
})
219+
: "This connection does not have permission to manage the environment."}
216220
</Text>
217221
) : null}
218222
{error ? (

‎apps/web/src/components/settings/SessionPermissions.tsx‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
2-
import { AUTH_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
2+
import {
3+
AUTH_SCOPE_OPTIONS,
4+
sessionPermissionsUnavailableMessage,
5+
} from "@t3tools/shared/authScopeOptions";
36
import { useEnvironmentSessionState } from "~/state/session";
47

58
export function SessionPermissions({
@@ -32,7 +35,11 @@ export function SessionPermissions({
3235
</div>
3336
) : (
3437
<p className="py-3 text-xs text-muted-foreground">
35-
Permissions not checked. Connect to this environment to view this session’s permissions.
38+
{sessionPermissionsUnavailableMessage({
39+
connected,
40+
failed: session.hasError,
41+
rejected: !session.hasError && !session.isPending && session.data?.authenticated === false,
42+
})}
3643
</p>
3744
);
3845
}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
import { EnvironmentId, type AuthSessionState } from "@t3tools/contracts";
3+
import * as Clock from "effect/Clock";
4+
import * as Effect from "effect/Effect";
5+
import * as Layer from "effect/Layer";
6+
import * as Option from "effect/Option";
7+
import * as Queue from "effect/Queue";
8+
import * as Stream from "effect/Stream";
9+
import * as SubscriptionRef from "effect/SubscriptionRef";
10+
import * as TestClock from "effect/testing/TestClock";
11+
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
12+
13+
import {
14+
AVAILABLE_CONNECTION_STATE,
15+
PrimaryConnectionTarget,
16+
type PreparedConnection,
17+
} from "../connection/model.ts";
18+
import * as EnvironmentRegistry from "../connection/registry.ts";
19+
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
20+
import * as RpcHttp from "../rpc/http.ts";
21+
import type { RpcSession } from "../rpc/session.ts";
22+
import { createEnvironmentSessionAtoms } from "./session.ts";
23+
24+
const TARGET = new PrimaryConnectionTarget({
25+
environmentId: EnvironmentId.make("environment-1"),
26+
label: "Test environment",
27+
httpBaseUrl: "https://environment.example.test",
28+
wsBaseUrl: "wss://environment.example.test",
29+
});
30+
const PREPARED: PreparedConnection = {
31+
environmentId: TARGET.environmentId,
32+
label: TARGET.label,
33+
httpBaseUrl: "https://environment.example.test",
34+
socketUrl: "wss://environment.example.test/ws",
35+
httpAuthorization: { _tag: "Bearer", token: "bearer-token" },
36+
target: TARGET,
37+
};
38+
const SESSION = {
39+
authenticated: true,
40+
auth: {
41+
policy: "remote-reachable",
42+
bootstrapMethods: [],
43+
sessionMethods: [],
44+
sessionCookieName: "t3_session",
45+
},
46+
scopes: ["orchestration:read"],
47+
} satisfies AuthSessionState;
48+
49+
const rpcSession = (): RpcSession => ({ closed: Effect.never }) as unknown as RpcSession;
50+
51+
const makeHarness = Effect.fn("TestSessionState.makeHarness")(function* (
52+
reply: (requestNumber: number) => Promise<Response>,
53+
) {
54+
let requestCount = 0;
55+
const transport = yield* SubscriptionRef.make(Option.some(rpcSession()));
56+
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
57+
target: TARGET,
58+
state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
59+
session: transport,
60+
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
61+
connect: Effect.void,
62+
disconnect: Effect.void,
63+
retryNow: Effect.void,
64+
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
65+
const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
66+
_environmentId,
67+
stream,
68+
) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
69+
const runtime = Atom.runtime(
70+
Layer.mergeAll(
71+
Layer.succeed(
72+
EnvironmentRegistry.EnvironmentRegistry,
73+
EnvironmentRegistry.EnvironmentRegistry.of({
74+
followStream,
75+
} as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
76+
),
77+
RpcHttp.layerRemoteHttpClient(async () => reply(++requestCount)),
78+
// The test's clock, so the retry wait moves with `TestClock.adjust`.
79+
Layer.succeed(Clock.Clock, yield* Clock.Clock),
80+
),
81+
);
82+
const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
83+
Effect.sync(() => registry.dispose()),
84+
);
85+
const results = yield* Queue.unbounded<AsyncResult.AsyncResult<AuthSessionState, unknown>>();
86+
const atom = createEnvironmentSessionAtoms(runtime).sessionStateAtom(TARGET.environmentId);
87+
const unsubscribe = registry.subscribe(atom, (result) => Queue.offerUnsafe(results, result), {
88+
immediate: true,
89+
});
90+
yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
91+
const nextSettled = Effect.fn("TestSessionState.nextSettled")(function* () {
92+
for (;;) {
93+
const result = yield* Queue.take(results);
94+
if (!result.waiting && result._tag !== "Initial") return result;
95+
}
96+
});
97+
return { transport, nextSettled };
98+
});
99+
100+
const unreachable = () => Promise.reject(new TypeError("Network request failed"));
101+
102+
describe("environment session state", () => {
103+
it.effect("fetches permissions again when the connection is re-established", () =>
104+
Effect.gen(function* () {
105+
const harness = yield* makeHarness((requestNumber) =>
106+
requestNumber === 1 ? unreachable() : Promise.resolve(Response.json(SESSION)),
107+
);
108+
expect((yield* harness.nextSettled())._tag).toBe("Failure");
109+
110+
yield* SubscriptionRef.set(harness.transport, Option.some(rpcSession()));
111+
112+
expect(yield* harness.nextSettled()).toMatchObject({ _tag: "Success", value: SESSION });
113+
}),
114+
);
115+
116+
it.effect("retries a failed permission check with backoff that restarts per connection", () =>
117+
Effect.gen(function* () {
118+
const harness = yield* makeHarness((requestNumber) =>
119+
requestNumber <= 3 ? unreachable() : Promise.resolve(Response.json(SESSION)),
120+
);
121+
expect((yield* harness.nextSettled())._tag).toBe("Failure");
122+
123+
yield* TestClock.adjust("2 seconds");
124+
expect((yield* harness.nextSettled())._tag).toBe("Failure");
125+
126+
yield* SubscriptionRef.set(harness.transport, Option.some(rpcSession()));
127+
expect((yield* harness.nextSettled())._tag).toBe("Failure");
128+
129+
yield* TestClock.adjust("2 seconds");
130+
expect(yield* harness.nextSettled()).toMatchObject({ _tag: "Success", value: SESSION });
131+
}),
132+
);
133+
});

‎packages/client-runtime/src/state/session.ts‎

Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type { PreparedConnection } from "../connection/model.ts";
1414
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
1515
import * as ManagedRelay from "../relay/managedRelay.ts";
1616
import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
17+
import type { RpcSession } from "../rpc/session.ts";
1718
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
1819
import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
1920
import { followStreamInEnvironment } from "./environmentStreams.ts";
@@ -39,6 +40,8 @@ function initialConfigOption<E>(
3940

4041
const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;
4142
const MAX_SESSION_STATE_TIMEOUT_MS = 60_000;
43+
const SESSION_STATE_RETRY_BASE_MS = 2_000;
44+
const SESSION_STATE_RETRY_MAX_MS = 60_000;
4245

4346
export const fetchEnvironmentSessionState = Effect.fn(
4447
"clientRuntime.state.fetchEnvironmentSessionState",
@@ -136,13 +139,38 @@ function makeEnvironmentSessionAtoms<R, E>(
136139
).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)),
137140
);
138141

139-
const sessionStateAtom = Atom.family((environmentId: EnvironmentId) =>
140-
runtime
142+
const transportSessionAtom = Atom.family((environmentId: EnvironmentId) =>
143+
runtime.atom(
144+
followStreamInEnvironment(
145+
environmentId,
146+
Stream.unwrap(
147+
EnvironmentSupervisor.EnvironmentSupervisor.pipe(
148+
Effect.map((supervisor) => SubscriptionRef.changes(supervisor.session)),
149+
),
150+
),
151+
),
152+
{ initialValue: Option.none() },
153+
),
154+
);
155+
156+
const sessionStateAtom = Atom.family((environmentId: EnvironmentId) => {
157+
let consecutiveFailures = 0;
158+
let backoffConnection: RpcSession | null = null;
159+
return runtime
141160
.atom((get) => {
142161
const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId)));
143-
if (prepared === null) {
162+
// Each established connection fetches anew, and a failure retries while it stays up,
163+
// so a fetch that failed mid-reconnect cannot outlive the socket that recovered.
164+
const connection = AsyncResult.getOrElse(get(transportSessionAtom(environmentId)), () =>
165+
Option.none(),
166+
);
167+
if (prepared === null || Option.isNone(connection)) {
144168
return Effect.never;
145169
}
170+
if (connection.value !== backoffConnection) {
171+
backoffConnection = connection.value;
172+
consecutiveFailures = 0;
173+
}
146174
return Effect.gen(function* () {
147175
const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
148176
const remoteAuthorization = yield* Effect.serviceOption(
@@ -155,14 +183,31 @@ function makeEnvironmentSessionAtoms<R, E>(
155183
signer,
156184
remoteAuthorization,
157185
}).pipe(Effect.provideService(HttpClient.HttpClient, client.value));
158-
});
186+
}).pipe(
187+
Effect.tap(() =>
188+
Effect.sync(() => {
189+
consecutiveFailures = 0;
190+
}),
191+
),
192+
Effect.tapError(() => {
193+
const delayMs = Math.min(
194+
SESSION_STATE_RETRY_BASE_MS * 2 ** consecutiveFailures,
195+
SESSION_STATE_RETRY_MAX_MS,
196+
);
197+
consecutiveFailures += 1;
198+
return Effect.sleep(delayMs).pipe(
199+
Effect.andThen(Effect.sync(() => get.refreshSelf())),
200+
Effect.forkScoped,
201+
);
202+
}),
203+
);
159204
})
160205
.pipe(
161206
Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
162207
Atom.setIdleTTL(5 * 60_000),
163208
Atom.withLabel(`environment-session-state:${environmentId}`),
164-
),
165-
);
209+
);
210+
});
166211

167212
const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
168213
Atom.make(

‎packages/shared/src/authScopeOptions.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,19 @@ export const AUTH_SCOPE_OPTIONS: ReadonlyArray<{
104104
description: "Change managed tunnel connectivity.",
105105
},
106106
];
107+
108+
/** Shown instead of the granted scopes while they are unknown, so every surface says the same thing. */
109+
export function sessionPermissionsUnavailableMessage(input: {
110+
readonly connected: boolean;
111+
/** The check errored; the client retries it while connected. */
112+
readonly failed: boolean;
113+
/** The environment answered that this session is not signed in; retrying will not change that. */
114+
readonly rejected: boolean;
115+
}): string {
116+
if (!input.connected) return "Connect to this environment to view this session’s permissions.";
117+
if (input.rejected)
118+
return "This environment did not accept your session. Reconnect to try again.";
119+
return input.failed
120+
? "Could not verify your permissions. Retrying automatically."
121+
: "Checking permissions…";
122+
}

0 commit comments

Comments
 (0)