Skip to content
TypeScript

fix(client-runtime): searches and refreshes no longer wait on an unreachable environment (#25703)

Julius Marminge8e86eb2b4d63
diff --git a/apps/mobile/src/features/files/useFileTreeEntries.ts b/apps/mobile/src/features/files/useFileTreeEntries.ts
index 3c728d48ad0..d171f80e602 100644
--- a/apps/mobile/src/features/files/useFileTreeEntries.ts
+++ b/apps/mobile/src/features/files/useFileTreeEntries.ts
@@ -1,13 +1,18 @@
+import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
+import { Atom } from "effect/reactivity";
import { useEffect, useReducer, useRef, useState } from "react";
+import { environmentCatalog } from "../../connection/catalog";
import { appAtomRegistry } from "../../state/atom-registry";
import { projectEnvironment } from "../../state/projects";
import { useDebouncedValue } from "../../state/queries";
import { useEnvironmentQuery } from "../../state/query";
+const noSessionGeneration = Atom.make(0);
+
export function useFileTreeEntries(input: {
readonly cwd: string | null;
readonly environmentId: EnvironmentId | null;
@@ -94,6 +99,17 @@ export function useFileTreeEntries(input: {
render();
});
};
+ // A folder read fails at once while its environment is unreachable; read it again once a new
+ // session is up rather than leaving the error until someone refreshes.
+ const sessionGeneration =
+ environmentId === null
+ ? noSessionGeneration
+ : environmentCatalog.sessionGenerationAtom(environmentId);
+ // A listener alone does not compute the atom, so nothing would follow the connection.
+ useAtomMount(sessionGeneration);
+ useAtomSubscribe(sessionGeneration, () => {
+ for (const path of directories.errors.keys()) void loadDirectory(path);
+ });
const { refresh: refreshRoot, data: rootData } = root;
const { refresh: refreshSearch, data: searchData } = search;
const snapshot = (() => {
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
index fdb2093a0b3..caea7afb850 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
@@ -1,4 +1,4 @@
-import { RegistryContext, useAtomValue } from "@effect/atom-react";
+import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
import { use, useCallback, useMemo, useState } from "react";
+import { environmentCatalog } from "../../connection/catalog";
import {
composerPullRequests,
pullRequestListPagesFamily,
@@ -142,6 +143,15 @@ const refreshLoadFamily = Atom.family((scopeKey: string) =>
),
);
+// Changes when any of the scope's environments brings up a new session.
+const sessionsFamily = Atom.family((scopeKey: string) =>
+ Atom.make((get) =>
+ (JSON.parse(scopeKey) as readonly ListTarget[])
+ .map(({ environmentId }) => get(environmentCatalog.sessionGenerationAtom(environmentId)))
+ .join(),
+ ),
+);
+
const settledError = (result: AsyncResult.AsyncResult<string | null, never>) =>
AsyncResult.isSuccess(result) && !result.waiting ? result.value : null;
@@ -156,6 +166,19 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
// Starting one kind of load clears the other, so at most one holds an error.
const loadError = settledError(refresh) ?? settledError(page);
+ // A page or refresh asked for while an environment was unreachable fails at once, and its
+ // error stops loading on scroll. Once it is back, ask for the page again; a refresh's error is
+ // stale by then because the list queries re-run on reconnect.
+ // A listener alone does not compute the atom, so nothing would follow the connections.
+ useAtomMount(sessionsFamily(scopeKey));
+ useAtomSubscribe(sessionsFamily(scopeKey), () => {
+ const pageResult = registry.get(pageAtom);
+ const refreshResult = registry.get(refreshAtom);
+ if (settledError(refreshResult) !== null) registry.set(refreshAtom, Atom.Reset);
+ else if (settledError(pageResult) !== null && !refreshResult.waiting)
+ registry.set(pageAtom, true);
+ });
+
// Read from the registry, not the render: a second onEndReached before React re-renders must
// see the load the first one started.
const loadMore = (retry = false) => {
diff --git a/apps/mobile/src/state/assets.test.ts b/apps/mobile/src/state/assets.test.ts
index c1f8df94eb5..e4ab077c3fc 100644
--- a/apps/mobile/src/state/assets.test.ts
+++ b/apps/mobile/src/state/assets.test.ts
@@ -19,6 +19,8 @@ const state = vi.hoisted(() => ({
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
vi.mock("@effect/atom-react", () => ({
+ useAtomMount: () => undefined,
+ useAtomSubscribe: () => undefined,
useAtomValue: (atom: unknown) =>
atom === state.assetAtom
? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })
@@ -39,6 +41,9 @@ vi.mock("./query", () => ({
}));
vi.mock("./projectClones", () => ({ environmentProjectCloneListAtom: () => null }));
vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} }));
+vi.mock("../connection/catalog", () => ({
+ environmentCatalog: { sessionGenerationAtom: () => null },
+}));
vi.mock("@t3tools/client-runtime/state/assets", async (importOriginal) => ({
...(await importOriginal<typeof import("@t3tools/client-runtime/state/assets")>()),
createAssetEnvironmentAtoms: () => ({ createUrl: state.assetQuery }),
diff --git a/apps/mobile/src/state/assets.ts b/apps/mobile/src/state/assets.ts
index 3eb0d2fe718..c33ef728436 100644
--- a/apps/mobile/src/state/assets.ts
+++ b/apps/mobile/src/state/assets.ts
@@ -1,4 +1,4 @@
-import { useAtomValue } from "@effect/atom-react";
+import { useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import {
assetUrlStateFromResult,
@@ -13,6 +13,7 @@ import * as Effect from "effect/Effect";
import { Atom, AsyncResult } from "effect/reactivity";
import { useCallback } from "react";
+import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
import { projectFaviconDatabaseCache } from "../lib/projectFaviconDatabaseCache";
import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
@@ -112,7 +113,7 @@ export async function refreshAssetUrl(
reportFailure: false,
...(signal ? { signal } : {}),
});
- // The query can wait through a reconnect; resolve against the connection that answered it.
+ // A route can change while the query runs; resolve against the connection now current.
const connection = appAtomRegistry.get(connectionAtom);
if (connection._tag === "None") return null;
const state = assetUrlStateFromResult(result, connection.value.httpBaseUrl);
@@ -154,6 +155,7 @@ const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) =>
const noFreshAssetUrl = Atom.make(AsyncResult.initial<AuthorizedAssetUrl, Error>()).pipe(
Atom.withLabel("fresh-asset-url:none"),
);
+const noSessionGeneration = Atom.make(0);
/**
* A signed URL minted when the reader mounts, not a cached one: cached links can
@@ -166,9 +168,20 @@ export function useFreshAssetUrl(
): AsyncResult.AsyncResult<AuthorizedAssetUrl, Error> {
const connection = usePreparedConnection(environmentId);
const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
- return useAtomValue(
+ const atom =
resource === null
? noFreshAssetUrl
- : freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision }),
- );
+ : freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision });
+ // Minting fails at once while the environment is unreachable; mint again once a new session is
+ // up instead of keeping the error until Retry.
+ const sessionGeneration =
+ environmentId === null
+ ? noSessionGeneration
+ : environmentCatalog.sessionGenerationAtom(environmentId);
+ // A listener alone does not compute the atom, so nothing would follow the connection.
+ useAtomMount(sessionGeneration);
+ useAtomSubscribe(sessionGeneration, () => {
+ if (AsyncResult.isFailure(appAtomRegistry.get(atom))) appAtomRegistry.refresh(atom);
+ });
+ return useAtomValue(atom);
}
diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts
index da38e753ecc..5b560b06017 100644
--- a/apps/web/src/components/chat/useComposerContextImport.ts
+++ b/apps/web/src/components/chat/useComposerContextImport.ts
@@ -1,3 +1,10 @@
+import {
+ ConnectionBlockedError,
+ ConnectionTransientError,
+} from "@t3tools/client-runtime/connection";
+import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
+import * as Cause from "effect/Cause";
+import * as Schema from "effect/Schema";
import type { RefObject } from "react";
import type { ChatComposerProps } from "./ChatComposer";
import {
@@ -49,6 +56,10 @@ import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
import { useStableCallback } from "../../hooks/useStableCallback";
import { countPreparingComposerImages } from "./preparingComposerImages";
+const isUnreachable = Schema.is(
+ Schema.Union([ConnectionTransientError, ConnectionBlockedError, EnvironmentRpcUnavailableError]),
+);
+
async function downloadAttachmentBlob(url: string): Promise<Blob | null> {
try {
const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
@@ -162,7 +173,12 @@ export function useComposerContextImport(input: {
? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
: null;
if (!url) {
- fail("The original attachment is no longer available.");
+ const cause = result._tag === "Failure" ? Cause.squash(result.cause) : null;
+ fail(
+ isUnreachable(cause)
+ ? "The environment it came from is not reachable right now."
+ : "The original attachment is no longer available.",
+ );
return;
}
const blob = await downloadAttachmentBlob(url);
diff --git a/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx b/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx
new file mode 100644
index 00000000000..735448ef496
--- /dev/null
+++ b/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx
@@ -0,0 +1,66 @@
+import { RegistryContext } from "@effect/atom-react";
+import { EnvironmentId } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import { AsyncResult, Atom } from "effect/reactivity";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { appAtomRegistry } from "~/rpc/atomRegistry";
+import { act, render } from "../../../test/render";
+import { useDirectoryEntries } from "./useDirectoryEntries";
+
+const mocks = vi.hoisted(() => ({
+ reachable: null as unknown as Atom.Writable<boolean>,
+ connectedSession: null as unknown as Atom.Writable<number>,
+}));
+
+vi.mock("~/connection/catalog", () => ({
+ // Derived like the real one, which only follows the connection once something computes it.
+ environmentCatalog: {
+ sessionGenerationAtom: () => Atom.make((get) => get(mocks.connectedSession)),
+ },
+}));
+vi.mock("~/state/projects", () => ({
+ projectEnvironment: {
+ listEntries: () =>
+ Atom.make((get) =>
+ get(mocks.reachable)
+ ? AsyncResult.success({
+ entries: [{ path: "README.md", kind: "file" }],
+ truncated: false,
+ })
+ : AsyncResult.failure(Cause.fail(new Error("Environment is reconnecting."))),
+ ),
+ },
+}));
+
+function setup() {
+ mocks.reachable = Atom.make(false);
+ mocks.connectedSession = Atom.make(1);
+}
+
+function Probe() {
+ const directory = useDirectoryEntries(EnvironmentId.make("env-files"), "/repo");
+ return (
+ <output>{directory.error ?? directory.entries.map((entry) => entry.path).join(",")}</output>
+ );
+}
+
+describe("useDirectoryEntries", () => {
+ it("reads a folder that failed while unreachable again once a new session is up", async () => {
+ setup();
+ await using screen = await render(
+ <RegistryContext.Provider value={appAtomRegistry}>
+ <Probe />
+ </RegistryContext.Provider>,
+ // A bare hook probe; nothing here navigates.
+ { router: false },
+ );
+ await expect.element(screen.getByText("Environment is reconnecting.")).toBeInTheDocument();
+
+ await act(() => {
+ appAtomRegistry.set(mocks.reachable, true);
+ appAtomRegistry.set(mocks.connectedSession, 2);
+ });
+ await expect.element(screen.getByText("README.md")).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/files/useDirectoryEntries.ts b/apps/web/src/components/files/useDirectoryEntries.ts
index 7aab3d4cf7a..30327e6f71f 100644
--- a/apps/web/src/components/files/useDirectoryEntries.ts
+++ b/apps/web/src/components/files/useDirectoryEntries.ts
@@ -1,8 +1,10 @@
import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";
+import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import { useEffect, useRef, useState } from "react";
+import { environmentCatalog } from "~/connection/catalog";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { projectEnvironment } from "~/state/projects";
@@ -100,6 +102,15 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
};
}, [startRequest]);
+ // A folder read fails at once while its environment is unreachable; read it again once a new
+ // session is up rather than leaving the error until someone retries by hand.
+ const sessionGeneration = environmentCatalog.sessionGenerationAtom(environmentId);
+ // A listener alone does not compute the atom, so nothing would follow the connection.
+ useAtomMount(sessionGeneration);
+ useAtomSubscribe(sessionGeneration, () => {
+ for (const path of errors.keys()) void load(path);
+ });
+
const entries: ProjectEntry[] = [];
const visit = (path: string) => {
for (const entry of directories.get(path) ?? []) {
diff --git a/packages/client-runtime/src/state/connections.test.ts b/packages/client-runtime/src/state/connections.test.ts
new file mode 100644
index 00000000000..dac91b6cac3
--- /dev/null
+++ b/packages/client-runtime/src/state/connections.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from "@effect/vitest";
+import { EnvironmentId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Stream from "effect/Stream";
+import * as SubscriptionRef from "effect/SubscriptionRef";
+import { Atom, AtomRegistry } from "effect/reactivity";
+
+import {
+ AVAILABLE_CONNECTION_STATE,
+ ConnectionTransientError,
+ type SupervisorConnectionState,
+} from "../connection/model.ts";
+import * as EnvironmentRegistry from "../connection/registry.ts";
+import * as EnvironmentSupervisor from "../connection/supervisor.ts";
+import type * as RpcSession from "../rpc/session.ts";
+import { createEnvironmentCatalogAtoms } from "./connections.ts";
+
+const ENVIRONMENT_ID = EnvironmentId.make("catalog-environment");
+
+const connectionState = (
+ overrides: Partial<SupervisorConnectionState>,
+): SupervisorConnectionState => ({
+ ...AVAILABLE_CONNECTION_STATE,
+ desired: true,
+ network: "online",
+ ...overrides,
+});
+
+const makeCatalogHarness = Effect.fn("TestCatalog.makeHarness")(function* () {
+ const state = yield* SubscriptionRef.make(
+ connectionState({ phase: "connected", attempt: 1, generation: 1 }),
+ );
+ const session = yield* SubscriptionRef.make(Option.some({} as RpcSession.RpcSession));
+ const supervisor = {
+ state,
+ session,
+ } as unknown as EnvironmentSupervisor.EnvironmentSupervisor["Service"];
+ const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
+ _environmentId,
+ stream,
+ ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
+ const registry = EnvironmentRegistry.EnvironmentRegistry.of({
+ followStream,
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
+ const catalog = createEnvironmentCatalogAtoms(
+ Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry)),
+ );
+ const atom = catalog.sessionGenerationAtom(ENVIRONMENT_ID);
+ const atoms = AtomRegistry.make();
+ const unmount = atoms.mount(atom);
+ yield* Effect.addFinalizer(() =>
+ Effect.sync(() => {
+ unmount();
+ atoms.dispose();
+ }),
+ );
+ yield* Effect.yieldNow;
+ /** Moves the supervisor to `next`, with a new session object when one is established. */
+ const generationAfter = (
+ next: SupervisorConnectionState,
+ nextSession: Option.Option<RpcSession.RpcSession> = Option.none(),
+ ) =>
+ SubscriptionRef.set(session, nextSession).pipe(
+ Effect.andThen(SubscriptionRef.set(state, next)),
+ Effect.andThen(Effect.yieldNow),
+ Effect.map(() => atoms.get(atom)),
+ );
+ return { generation: () => atoms.get(atom), generationAfter };
+});
+
+const lastFailure = new ConnectionTransientError({ reason: "transport", detail: "Down." });
+const newSession = () => Option.some({} as RpcSession.RpcSession);
+
+describe("environment catalog atoms", () => {
+ it.effect("changes the session generation only when a new session comes up", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { generation, generationAfter } = yield* makeCatalogHarness();
+ const first = generation();
+ // A retry reports the generation it is attempting before it is established.
+ expect(
+ yield* generationAfter(
+ connectionState({ phase: "connecting", stage: "opening", generation: 2, lastFailure }),
+ ),
+ ).toBe(first);
+ expect(
+ yield* generationAfter(
+ connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
+ ),
+ ).toBe(first);
+ expect(
+ yield* generationAfter(
+ connectionState({ phase: "connected", attempt: 2, generation: 2 }),
+ newSession(),
+ ),
+ ).not.toBe(first);
+ }),
+ ),
+ );
+
+ it.effect("changes when a replaced supervisor's first session reuses an old generation", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { generation, generationAfter } = yield* makeCatalogHarness();
+ const first = generation();
+ yield* generationAfter(
+ connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
+ );
+ // Re-pairing or editing a route installs a new supervisor, whose counter starts over.
+ yield* generationAfter(connectionState({ phase: "available", generation: 0 }));
+ expect(
+ yield* generationAfter(
+ connectionState({ phase: "connected", attempt: 1, generation: 1 }),
+ newSession(),
+ ),
+ ).not.toBe(first);
+ }),
+ ),
+ );
+});
diff --git a/packages/client-runtime/src/state/connections.ts b/packages/client-runtime/src/state/connections.ts
index 779bbd054ad..82afc19c69a 100644
--- a/packages/client-runtime/src/state/connections.ts
+++ b/packages/client-runtime/src/state/connections.ts
@@ -17,6 +17,7 @@ import {
import {
createAtomCommandScheduler,
createRuntimeCommand,
+ environmentSessionGenerationAtom,
followStreamInEnvironment,
} from "./runtime.ts";
@@ -120,6 +121,9 @@ export function createEnvironmentCatalogAtoms<R, E>(
),
);
+ const sessionGenerationAtom = (environmentId: EnvironmentIdType) =>
+ environmentSessionGenerationAtom(runtime, environmentId);
+
const register = createRuntimeCommand(runtime, {
label: "environment-catalog:register",
scheduler: commandScheduler,
@@ -197,6 +201,7 @@ export function createEnvironmentCatalogAtoms<R, E>(
networkStatusAtom,
networkStatusValueAtom,
stateAtom,
+ sessionGenerationAtom,
register,
remove,
removeRoute,
diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts
index 5b348d01202..bb69334bc78 100644
--- a/packages/client-runtime/src/state/runtime.test.ts
+++ b/packages/client-runtime/src/state/runtime.test.ts
@@ -42,6 +42,7 @@ import {
selectEnvironmentQueryData,
createEnvironmentSubscriptionAtomFamily,
createRuntimeCommand,
+ environmentSessionGenerationAtom,
scheduleAtomCommandEffect,
executeAtomQuery,
type QueryAnswerHandler,
@@ -476,7 +477,7 @@ describe("environment query lifecycle", () => {
);
it.effect(
- "retries an interrupted query without exposing a failure during session replacement",
+ "hides a session replacement, reports the relay backoff, and recovers on reconnect",
() =>
Effect.scoped(
Effect.gen(function* () {
@@ -534,25 +535,33 @@ describe("environment query lifecycle", () => {
queryConnectionState({ phase: "connecting", stage: "preparing" }),
);
yield* Effect.yieldNow;
+ const relayFailure = new ConnectionTransientError({
+ reason: "transport",
+ detail: "Relay session is reconnecting.",
+ });
yield* SubscriptionRef.set(
harness.supervisorState,
queryConnectionState({
phase: "backoff",
stage: null,
- lastFailure: new ConnectionTransientError({
- reason: "transport",
- detail: "Relay session is reconnecting.",
- }),
+ lastFailure: relayFailure,
retryAt: 1,
}),
);
yield* Effect.yieldNow;
+ // The query has never answered, so it reports why the environment is retrying.
+ const backingOff = registry.get(harness.atom);
+ expect(backingOff.waiting).toBe(false);
+ expect(AsyncResult.isFailure(backingOff) && Cause.squash(backingOff.cause)).toBe(
+ relayFailure,
+ );
yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
yield* SubscriptionRef.set(
harness.supervisorState,
queryConnectionState({ generation: 2 }),
);
+ yield* Effect.yieldNow;
expect(
yield* AtomRegistry.getResult(registry, harness.atom, {
suspendOnWaiting: true,
@@ -707,6 +716,87 @@ describe("environment query lifecycle", () => {
),
);
+ it.effect.each([
+ { phase: "backoff", stage: null, retryAt: 1 },
+ { phase: "connecting", stage: "opening", retryAt: null },
+ ] as const)(
+ "settles a query it never answered while its environment retries ($phase)",
+ (retrying) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
+ initialState: queryConnectionState({ ...retrying, lastFailure: OFFLINE_QUERY_FAILURE }),
+ });
+ const registry = yield* mountEnvironmentQuery(harness.atom);
+ yield* Effect.yieldNow;
+
+ const result = registry.get(harness.atom);
+ expect(result.waiting).toBe(false);
+ expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toBe(
+ OFFLINE_QUERY_FAILURE,
+ );
+
+ yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
+ yield* Effect.yieldNow;
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("connected");
+ }),
+ ),
+ );
+
+ it.effect("a refresh started on a new session generation answers from that session", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
+ initialState: queryConnectionState({
+ phase: "backoff",
+ stage: null,
+ lastFailure: OFFLINE_QUERY_FAILURE,
+ retryAt: 1,
+ }),
+ });
+ const registry = yield* mountEnvironmentQuery(harness.atom);
+ // Callers hold the failure a read got while the environment was retrying.
+ const failed = yield* Effect.promise(() =>
+ executeAtomQuery(registry, harness.atom, { reportFailure: false }),
+ );
+ expect(AsyncResult.isFailure(failed)).toBe(true);
+
+ const answered = yield* Deferred.make<AsyncResult.AsyncResult<string, unknown>>();
+ const sessionGeneration = environmentSessionGenerationAtom(
+ harness.runtime,
+ QUERY_ENVIRONMENT.environmentId,
+ );
+ const unmount = registry.mount(sessionGeneration);
+ const unsubscribe = registry.subscribe(sessionGeneration, () => {
+ void executeAtomQuery(registry, harness.atom, {
+ refresh: true,
+ reportFailure: false,
+ }).then((result) => Deferred.doneUnsafe(answered, Effect.succeed(result)));
+ });
+ yield* Effect.addFinalizer(() =>
+ Effect.sync(() => {
+ unsubscribe();
+ unmount();
+ }),
+ );
+ yield* Effect.yieldNow;
+
+ yield* SubscriptionRef.set(
+ harness.supervisorSession,
+ Option.some({} as RpcSession.RpcSession),
+ );
+ yield* SubscriptionRef.set(
+ harness.supervisorState,
+ queryConnectionState({ generation: 2 }),
+ );
+ expect(yield* Deferred.await(answered)).toMatchObject({
+ _tag: "Success",
+ value: "connected",
+ });
+ }),
+ ),
+ );
+
it.effect("keeps a genuine query failure settled while reconnecting", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts
index 79b1ec4ac5e..fbc4fde625c 100644
--- a/packages/client-runtime/src/state/runtime.ts
+++ b/packages/client-runtime/src/state/runtime.ts
@@ -17,7 +17,7 @@ import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
-import type { ConnectionAttemptError } from "../connection/model.ts";
+import type { ConnectionAttemptError, SupervisorConnectionState } from "../connection/model.ts";
import * as EnvironmentRegistry from "../connection/registry.ts";
import {
type EnvironmentRpcInput,
@@ -560,22 +560,28 @@ const refreshEveryUntilFinal =
export const selectEnvironmentQueryData = <A, E>(result: AsyncResult.AsyncResult<A, E>): A | null =>
Option.getOrNull(AsyncResult.value(result));
-export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
+type EnvironmentConnection = readonly [
+ SupervisorConnectionState,
+ Option.Option<RpcSession.RpcSession>,
+];
+
+const connectionAtomsByRuntime = new WeakMap<
+ object,
+ (
+ environmentId: EnvironmentIdType,
+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>
+>();
+
+/**
+ * One connection atom per environment for every query on a runtime, so a reader of the session
+ * generation and a query it re-runs see the same connection change at once.
+ */
+function environmentConnectionAtoms<R, ER>(
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
- options: EnvironmentQueryAtomOptions<
- Input,
- A,
- E,
- | EnvironmentSupervisor.EnvironmentSupervisor
- | EnvironmentRegistry.EnvironmentRegistry
- | AtomRegistry.AtomRegistry
- | R
- >,
-): (target: {
- readonly environmentId: EnvironmentIdType;
- readonly input: Input;
-}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
- const connectionAtom = Atom.family((environmentId: EnvironmentIdType) =>
+) {
+ const existing = connectionAtomsByRuntime.get(runtime);
+ if (existing !== undefined) return existing;
+ const family = Atom.family((environmentId: EnvironmentIdType) =>
runtime.atom(
followStreamInEnvironment(
environmentId,
@@ -591,7 +597,72 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
),
{ initialValue: null },
),
- );
+ ) as (
+ environmentId: EnvironmentIdType,
+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>;
+ connectionAtomsByRuntime.set(runtime, family);
+ return family;
+}
+
+const sessionGenerationAtomsByRuntime = new WeakMap<
+ object,
+ (environmentId: EnvironmentIdType) => Atom.Atom<number>
+>();
+
+/**
+ * Counts established sessions; it changes only when a new one comes up, so failed one-shot reads
+ * can watch it to run again. Keyed on the session object because the supervisor's `generation`
+ * restarts when the registry installs a new supervisor (re-pairing, route edits).
+ */
+export function environmentSessionGenerationAtom<R, ER>(
+ runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
+ environmentId: EnvironmentIdType,
+): Atom.Atom<number> {
+ let family = sessionGenerationAtomsByRuntime.get(runtime);
+ if (family === undefined) {
+ const connectionAtom = environmentConnectionAtoms(runtime);
+ const sessionsSeen = Atom.family((id: EnvironmentIdType) =>
+ Atom.make(
+ (get): { readonly session: RpcSession.RpcSession | null; readonly count: number } => {
+ const previous = Option.getOrElse(
+ get.self<{ readonly session: RpcSession.RpcSession | null; readonly count: number }>(),
+ () => ({ session: null, count: 0 }),
+ );
+ const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(id))));
+ if (connection === null || connection[0].phase !== "connected") return previous;
+ const session = Option.getOrNull(connection[1]);
+ return session === null || session === previous.session
+ ? previous
+ : { session, count: previous.count + 1 };
+ },
+ ),
+ );
+ family = Atom.family((id: EnvironmentIdType) =>
+ Atom.make((get) => get(sessionsSeen(id)).count).pipe(
+ Atom.withLabel(`environment-session-generation:${id}`),
+ ),
+ );
+ sessionGenerationAtomsByRuntime.set(runtime, family);
+ }
+ return family(environmentId);
+}
+
+export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
+ runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
+ options: EnvironmentQueryAtomOptions<
+ Input,
+ A,
+ E,
+ | EnvironmentSupervisor.EnvironmentSupervisor
+ | EnvironmentRegistry.EnvironmentRegistry
+ | AtomRegistry.AtomRegistry
+ | R
+ >,
+): (target: {
+ readonly environmentId: EnvironmentIdType;
+ readonly input: Input;
+}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
+ const connectionAtom = environmentConnectionAtoms(runtime);
const family = Atom.family((key: string) => {
const target = parseEnvironmentRpcKey<Input>(key);
const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
@@ -647,7 +718,18 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
: Effect.never;
case "connecting":
case "backoff":
- return Effect.never;
+ // A retry can take minutes. A query with an answer keeps showing it while it
+ // waits; one with nothing to show reports the failure the retry is recovering
+ // from, so its reader stops loading, and re-runs when the connection settles.
+ return connectionState.lastFailure !== null &&
+ Option.isNone(
+ Option.flatMap(
+ get.self<AsyncResult.AsyncResult<A, unknown>>(),
+ AsyncResult.value,
+ ),
+ )
+ ? Effect.fail(connectionState.lastFailure)
+ : Effect.never;
case "available":
case "offline":
case "blocked":