Skip to content

Commit a9bfba9

Browse files
fix(clients): reconnect retries hear the session change the query sees
The session generation now derives from the same per-runtime connection atom every environment query reads, so a read started when it changes already sees the new session. Readers mount the generation atom: a bare registry listener never computes it, so it followed no connection. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c82cea6 commit a9bfba9

10 files changed

Lines changed: 161 additions & 54 deletions

File tree

‎apps/mobile/src/features/files/useFileTreeEntries.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useAtomSubscribe } from "@effect/atom-react";
1+
import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
22
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
33
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
44
import * as Cause from "effect/Cause";
@@ -101,14 +101,15 @@ export function useFileTreeEntries(input: {
101101
};
102102
// A folder read fails at once while its environment is unreachable; read it again once a new
103103
// session is up rather than leaving the error until someone refreshes.
104-
useAtomSubscribe(
104+
const sessionGeneration =
105105
environmentId === null
106106
? noSessionGeneration
107-
: environmentCatalog.sessionGenerationAtom(environmentId),
108-
() => {
109-
for (const path of directories.errors.keys()) void loadDirectory(path);
110-
},
111-
);
107+
: environmentCatalog.sessionGenerationAtom(environmentId);
108+
// A listener alone does not compute the atom, so nothing would follow the connection.
109+
useAtomMount(sessionGeneration);
110+
useAtomSubscribe(sessionGeneration, () => {
111+
for (const path of directories.errors.keys()) void loadDirectory(path);
112+
});
112113
const { refresh: refreshRoot, data: rootData } = root;
113114
const { refresh: refreshSearch, data: searchData } = search;
114115
const snapshot = (() => {

‎apps/mobile/src/features/pull-requests/usePullRequestList.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { RegistryContext, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
1+
import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
22
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
33
import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts";
44
import * as Cause from "effect/Cause";
@@ -168,6 +168,8 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
168168

169169
// A page asked for while an environment was unreachable fails at once; ask again once it is
170170
// back, since the error stops loading on scroll.
171+
// A listener alone does not compute the atom, so nothing would follow the connections.
172+
useAtomMount(sessionsFamily(scopeKey));
171173
useAtomSubscribe(sessionsFamily(scopeKey), () => {
172174
if (settledError(page) !== null && !refresh.waiting) registry.set(pageAtom, true);
173175
});

‎apps/mobile/src/state/assets.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const state = vi.hoisted(() => ({
1919

2020
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
2121
vi.mock("@effect/atom-react", () => ({
22+
useAtomMount: () => undefined,
2223
useAtomSubscribe: () => undefined,
2324
useAtomValue: (atom: unknown) =>
2425
atom === state.assetAtom

‎apps/mobile/src/state/assets.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useAtomSubscribe, useAtomValue } from "@effect/atom-react";
1+
import { useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
22
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
33
import {
44
assetUrlStateFromResult,
@@ -174,13 +174,14 @@ export function useFreshAssetUrl(
174174
: freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision });
175175
// Minting fails at once while the environment is unreachable; mint again once a new session is
176176
// up instead of keeping the error until Retry.
177-
useAtomSubscribe(
177+
const sessionGeneration =
178178
environmentId === null
179179
? noSessionGeneration
180-
: environmentCatalog.sessionGenerationAtom(environmentId),
181-
() => {
182-
if (AsyncResult.isFailure(appAtomRegistry.get(atom))) appAtomRegistry.refresh(atom);
183-
},
184-
);
180+
: environmentCatalog.sessionGenerationAtom(environmentId);
181+
// A listener alone does not compute the atom, so nothing would follow the connection.
182+
useAtomMount(sessionGeneration);
183+
useAtomSubscribe(sessionGeneration, () => {
184+
if (AsyncResult.isFailure(appAtomRegistry.get(atom))) appAtomRegistry.refresh(atom);
185+
});
185186
return useAtomValue(atom);
186187
}

‎apps/web/src/components/files/useDirectoryEntries.browser.test.tsx‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,14 @@ import { useDirectoryEntries } from "./useDirectoryEntries";
1010

1111
const mocks = vi.hoisted(() => ({
1212
reachable: null as unknown as Atom.Writable<boolean>,
13-
sessionGeneration: null as unknown as Atom.Writable<number>,
13+
connectedSession: null as unknown as Atom.Writable<number>,
1414
}));
1515

1616
vi.mock("~/connection/catalog", () => ({
17-
environmentCatalog: { sessionGenerationAtom: () => mocks.sessionGeneration },
17+
// Derived like the real one, which only follows the connection once something computes it.
18+
environmentCatalog: {
19+
sessionGenerationAtom: () => Atom.make((get) => get(mocks.connectedSession)),
20+
},
1821
}));
1922
vi.mock("~/state/projects", () => ({
2023
projectEnvironment: {
@@ -32,7 +35,7 @@ vi.mock("~/state/projects", () => ({
3235

3336
function setup() {
3437
mocks.reachable = Atom.make(false);
35-
mocks.sessionGeneration = Atom.make(1);
38+
mocks.connectedSession = Atom.make(1);
3639
}
3740

3841
function Probe() {
@@ -56,7 +59,7 @@ describe("useDirectoryEntries", () => {
5659

5760
await act(() => {
5861
appAtomRegistry.set(mocks.reachable, true);
59-
appAtomRegistry.set(mocks.sessionGeneration, 2);
62+
appAtomRegistry.set(mocks.connectedSession, 2);
6063
});
6164
await expect.element(screen.getByText("README.md")).toBeInTheDocument();
6265
});

‎apps/web/src/components/files/useDirectoryEntries.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
2-
import { useAtomSubscribe } from "@effect/atom-react";
2+
import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
33
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
44
import * as Cause from "effect/Cause";
55
import { useEffect, useRef, useState } from "react";
@@ -104,7 +104,10 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
104104

105105
// A folder read fails at once while its environment is unreachable; read it again once a new
106106
// session is up rather than leaving the error until someone retries by hand.
107-
useAtomSubscribe(environmentCatalog.sessionGenerationAtom(environmentId), () => {
107+
const sessionGeneration = environmentCatalog.sessionGenerationAtom(environmentId);
108+
// A listener alone does not compute the atom, so nothing would follow the connection.
109+
useAtomMount(sessionGeneration);
110+
useAtomSubscribe(sessionGeneration, () => {
108111
for (const path of errors.keys()) void load(path);
109112
});
110113

‎packages/client-runtime/src/state/connections.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
22
import { EnvironmentId } from "@t3tools/contracts";
33
import * as Effect from "effect/Effect";
44
import * as Layer from "effect/Layer";
5+
import * as Option from "effect/Option";
56
import * as Stream from "effect/Stream";
67
import * as SubscriptionRef from "effect/SubscriptionRef";
78
import { Atom, AtomRegistry } from "effect/reactivity";
@@ -13,6 +14,7 @@ import {
1314
} from "../connection/model.ts";
1415
import * as EnvironmentRegistry from "../connection/registry.ts";
1516
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
17+
import type * as RpcSession from "../rpc/session.ts";
1618
import { createEnvironmentCatalogAtoms } from "./connections.ts";
1719

1820
const ENVIRONMENT_ID = EnvironmentId.make("catalog-environment");
@@ -33,8 +35,10 @@ describe("environment catalog atoms", () => {
3335
const state = yield* SubscriptionRef.make(
3436
connectionState({ phase: "connected", attempt: 1, generation: 1 }),
3537
);
38+
const session = yield* SubscriptionRef.make(Option.some({} as RpcSession.RpcSession));
3639
const supervisor = {
3740
state,
41+
session,
3842
} as unknown as EnvironmentSupervisor.EnvironmentSupervisor["Service"];
3943
const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
4044
_environmentId,

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

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
import {
1818
createAtomCommandScheduler,
1919
createRuntimeCommand,
20+
environmentSessionGenerationAtom,
2021
followStreamInEnvironment,
2122
} from "./runtime.ts";
2223

@@ -120,22 +121,8 @@ export function createEnvironmentCatalogAtoms<R, E>(
120121
),
121122
);
122123

123-
/**
124-
* The generation of the environment's latest established session, kept while it reconnects.
125-
* It changes only when a new session comes up, so a one-shot read that failed while the
126-
* environment was unreachable can key on it, or watch it, to run again once it is back.
127-
*/
128-
const sessionGenerationAtom = Atom.family((environmentId: EnvironmentIdType) =>
129-
Atom.make((get): number => {
130-
const state = Option.getOrElse(
131-
AsyncResult.value(get(stateAtom(environmentId))),
132-
() => AVAILABLE_CONNECTION_STATE,
133-
);
134-
return state.phase === "connected"
135-
? state.generation
136-
: Option.getOrElse(get.self<number>(), () => 0);
137-
}).pipe(Atom.withLabel(`environment-session-generation:${environmentId}`)),
138-
);
124+
const sessionGenerationAtom = (environmentId: EnvironmentIdType) =>
125+
environmentSessionGenerationAtom(runtime, environmentId);
139126

140127
const register = createRuntimeCommand(runtime, {
141128
label: "environment-catalog:register",

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
selectEnvironmentQueryData,
4343
createEnvironmentSubscriptionAtomFamily,
4444
createRuntimeCommand,
45+
environmentSessionGenerationAtom,
4546
scheduleAtomCommandEffect,
4647
executeAtomQuery,
4748
type QueryAnswerHandler,
@@ -742,6 +743,50 @@ describe("environment query lifecycle", () => {
742743
),
743744
);
744745

746+
it.effect("a read started on a new session generation sees that session", () =>
747+
Effect.scoped(
748+
Effect.gen(function* () {
749+
const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
750+
initialState: queryConnectionState({
751+
phase: "backoff",
752+
stage: null,
753+
lastFailure: OFFLINE_QUERY_FAILURE,
754+
retryAt: 1,
755+
}),
756+
});
757+
const registry = AtomRegistry.make();
758+
const answered = yield* Deferred.make<AsyncResult.AsyncResult<string, unknown>>();
759+
const sessionGeneration = environmentSessionGenerationAtom(
760+
harness.runtime,
761+
QUERY_ENVIRONMENT.environmentId,
762+
);
763+
const unmount = registry.mount(sessionGeneration);
764+
const unsubscribe = registry.subscribe(sessionGeneration, (generation) => {
765+
void executeAtomQuery(registry, harness.atom, { reportFailure: false }).then((result) => {
766+
if (generation === 2) Deferred.doneUnsafe(answered, Effect.succeed(result));
767+
});
768+
});
769+
yield* Effect.addFinalizer(() =>
770+
Effect.sync(() => {
771+
unsubscribe();
772+
unmount();
773+
registry.dispose();
774+
}),
775+
);
776+
yield* Effect.yieldNow;
777+
778+
yield* SubscriptionRef.set(
779+
harness.supervisorState,
780+
queryConnectionState({ generation: 2 }),
781+
);
782+
expect(yield* Deferred.await(answered)).toMatchObject({
783+
_tag: "Success",
784+
value: "connected",
785+
});
786+
}),
787+
),
788+
);
789+
745790
it.effect("keeps a genuine query failure settled while reconnecting", () =>
746791
Effect.scoped(
747792
Effect.gen(function* () {

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

Lines changed: 77 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import * as Stream from "effect/Stream";
1717
import * as SubscriptionRef from "effect/SubscriptionRef";
1818
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
1919

20-
import type { ConnectionAttemptError } from "../connection/model.ts";
20+
import type { ConnectionAttemptError, SupervisorConnectionState } from "../connection/model.ts";
2121
import * as EnvironmentRegistry from "../connection/registry.ts";
2222
import {
2323
type EnvironmentRpcInput,
@@ -560,22 +560,28 @@ const refreshEveryUntilFinal =
560560
export const selectEnvironmentQueryData = <A, E>(result: AsyncResult.AsyncResult<A, E>): A | null =>
561561
Option.getOrNull(AsyncResult.value(result));
562562

563-
export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
563+
type EnvironmentConnection = readonly [
564+
SupervisorConnectionState,
565+
Option.Option<RpcSession.RpcSession>,
566+
];
567+
568+
const connectionAtomsByRuntime = new WeakMap<
569+
object,
570+
(
571+
environmentId: EnvironmentIdType,
572+
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>
573+
>();
574+
575+
/**
576+
* One connection atom per environment for every query on a runtime, so a reader of the session
577+
* generation and a query it re-runs see the same connection change at once.
578+
*/
579+
function environmentConnectionAtoms<R, ER>(
564580
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
565-
options: EnvironmentQueryAtomOptions<
566-
Input,
567-
A,
568-
E,
569-
| EnvironmentSupervisor.EnvironmentSupervisor
570-
| EnvironmentRegistry.EnvironmentRegistry
571-
| AtomRegistry.AtomRegistry
572-
| R
573-
>,
574-
): (target: {
575-
readonly environmentId: EnvironmentIdType;
576-
readonly input: Input;
577-
}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
578-
const connectionAtom = Atom.family((environmentId: EnvironmentIdType) =>
581+
) {
582+
const existing = connectionAtomsByRuntime.get(runtime);
583+
if (existing !== undefined) return existing;
584+
const family = Atom.family((environmentId: EnvironmentIdType) =>
579585
runtime.atom(
580586
followStreamInEnvironment(
581587
environmentId,
@@ -591,7 +597,61 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
591597
),
592598
{ initialValue: null },
593599
),
594-
);
600+
) as (
601+
environmentId: EnvironmentIdType,
602+
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>;
603+
connectionAtomsByRuntime.set(runtime, family);
604+
return family;
605+
}
606+
607+
const sessionGenerationAtomsByRuntime = new WeakMap<
608+
object,
609+
(environmentId: EnvironmentIdType) => Atom.Atom<number>
610+
>();
611+
612+
/**
613+
* The generation of the environment's latest established session, kept while it reconnects.
614+
* It changes only when a new session comes up, so a one-shot read that failed while the
615+
* environment was unreachable can watch it to run again once it is back.
616+
*/
617+
export function environmentSessionGenerationAtom<R, ER>(
618+
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
619+
environmentId: EnvironmentIdType,
620+
): Atom.Atom<number> {
621+
let family = sessionGenerationAtomsByRuntime.get(runtime);
622+
if (family === undefined) {
623+
const connectionAtom = environmentConnectionAtoms(runtime);
624+
family = Atom.family((id: EnvironmentIdType) =>
625+
Atom.make((get): number => {
626+
const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(id))));
627+
return connection !== null &&
628+
connection[0].phase === "connected" &&
629+
Option.isSome(connection[1])
630+
? connection[0].generation
631+
: Option.getOrElse(get.self<number>(), () => 0);
632+
}).pipe(Atom.withLabel(`environment-session-generation:${id}`)),
633+
);
634+
sessionGenerationAtomsByRuntime.set(runtime, family);
635+
}
636+
return family(environmentId);
637+
}
638+
639+
export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
640+
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
641+
options: EnvironmentQueryAtomOptions<
642+
Input,
643+
A,
644+
E,
645+
| EnvironmentSupervisor.EnvironmentSupervisor
646+
| EnvironmentRegistry.EnvironmentRegistry
647+
| AtomRegistry.AtomRegistry
648+
| R
649+
>,
650+
): (target: {
651+
readonly environmentId: EnvironmentIdType;
652+
readonly input: Input;
653+
}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
654+
const connectionAtom = environmentConnectionAtoms(runtime);
595655
const family = Atom.family((key: string) => {
596656
const target = parseEnvironmentRpcKey<Input>(key);
597657
const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;

0 commit comments

Comments
 (0)