Skip to content
TypeScript

fix(client-runtime): queries stay pending while a connection hands off (#18155)

Tristan Knightddcde11be826
diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts
index 419dd08c546..279d39ecd70 100644
--- a/packages/client-runtime/src/connection/registry.test.ts
+++ b/packages/client-runtime/src/connection/registry.test.ts
@@ -630,6 +630,28 @@ describe("EnvironmentRegistry", () => {
}),
);
+ it.effect("does not expose a persisted environment as disconnected while it starts", () =>
+ Effect.gen(function* () {
+ const connectionStarted = yield* Deferred.make<void>();
+ const finishConnection = yield* Deferred.make<void>();
+ const harness = yield* makeHarness([TARGET], [], [], {
+ beforeSessionConnect: () =>
+ Deferred.succeed(connectionStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(finishConnection)),
+ ),
+ });
+
+ yield* Effect.gen(function* () {
+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
+ expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connecting");
+
+ yield* Deferred.await(connectionStarted);
+ expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connecting");
+ yield* Deferred.succeed(finishConnection, undefined);
+ }).pipe(Effect.provide(harness.layer), Effect.scoped);
+ }),
+ );
+
it.effect("exposes the current RPC generation to late query subscribers", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([TARGET]);
diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.ts
index 19bed9d7526..c3ad705e3d2 100644
--- a/packages/client-runtime/src/connection/registry.ts
+++ b/packages/client-runtime/src/connection/registry.ts
@@ -356,7 +356,10 @@ export const make = Effect.gen(function* () {
const environmentId = entry.target.environmentId;
const scope = yield* Scope.fork(registryScope);
const supervisor = yield* EnvironmentSupervisor.make(entry, {
- initiallyDesired: false,
+ // An enabled environment starts out connecting. Starting it idle and
+ // then asking it to connect would first publish the state of an
+ // environment the user switched off.
+ initiallyDesired: entry.enabled,
learnRoutes: (input) => learnRoutes({ environmentId, ...input }),
}).pipe(
Effect.provideService(Connectivity.Connectivity, connectivity),
@@ -365,9 +368,6 @@ export const make = Effect.gen(function* () {
Scope.provide(scope),
Effect.onError(() => Scope.close(scope, Exit.void)),
);
- if (entry.enabled) {
- yield* supervisor.connect;
- }
yield* SubscriptionRef.update(serviceScopes, (current) => {
const next = new Map(current);
next.set(environmentId, { entry, supervisor, scope });
diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts
index 7263c94c45a..c36bcaf3bd3 100644
--- a/packages/client-runtime/src/state/runtime.test.ts
+++ b/packages/client-runtime/src/state/runtime.test.ts
@@ -517,6 +517,96 @@ describe("environment query lifecycle", () => {
),
);
+ it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const firstStarted = Latch.makeUnsafe();
+ const failFirst = Latch.makeUnsafe();
+ const firstSettled = Latch.makeUnsafe();
+ let executions = 0;
+ const execute = Effect.suspend(() => {
+ executions += 1;
+ if (executions > 1) {
+ return Effect.succeed("recovered");
+ }
+ firstStarted.openUnsafe();
+ return failFirst.await.pipe(
+ Effect.andThen(
+ Effect.fail(
+ new EnvironmentRpcUnavailableError({
+ environmentId: QUERY_ENVIRONMENT.environmentId,
+ message: "Query environment is not connected.",
+ }),
+ ),
+ ),
+ Effect.ensuring(
+ Effect.sync(() => {
+ firstSettled.openUnsafe();
+ }),
+ ),
+ );
+ });
+ const harness = yield* makeEnvironmentQueryHarness(execute);
+ const registry = AtomRegistry.make();
+ const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
+ const unsubscribe = registry.subscribe(
+ harness.atom,
+ (result) => {
+ observed.push(result);
+ },
+ { immediate: true },
+ );
+ yield* Effect.addFinalizer(() =>
+ Effect.sync(() => {
+ unsubscribe();
+ registry.dispose();
+ }),
+ );
+
+ yield* firstStarted.await;
+ // No yield before the failure: the request finds its session gone
+ // before the atom has processed the session change.
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
+ failFirst.openUnsafe();
+ yield* firstSettled.await;
+ yield* Effect.yieldNow;
+
+ expect(observed.some(AsyncResult.isFailure)).toBe(false);
+
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
+ yield* SubscriptionRef.set(
+ harness.supervisorState,
+ queryConnectionState({ generation: 2 }),
+ );
+ expect(
+ yield* AtomRegistry.getResult(registry, harness.atom, {
+ suspendOnWaiting: true,
+ }),
+ ).toBe("recovered");
+ expect(observed.some(AsyncResult.isFailure)).toBe(false);
+ }),
+ ),
+ );
+
+ it.effect("fails a query that reports unavailable while its session is still live", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const unavailable = new EnvironmentRpcUnavailableError({
+ environmentId: QUERY_ENVIRONMENT.environmentId,
+ message: "The environment did not respond to the request.",
+ });
+ const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
+ const registry = yield* mountEnvironmentQuery(harness.atom);
+
+ const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
+ suspendOnWaiting: true,
+ }).pipe(Effect.exit);
+
+ expect(exit).toStrictEqual(Exit.fail(unavailable));
+ }),
+ ),
+ );
+
it.effect.each([
{
condition: "after a manual disconnect",
diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts
index c715a177745..155a709e786 100644
--- a/packages/client-runtime/src/state/runtime.ts
+++ b/packages/client-runtime/src/state/runtime.ts
@@ -12,6 +12,7 @@ import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -33,6 +34,30 @@ import {
subscribe,
} from "../rpc/client.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
+import type * as RpcSession from "../rpc/session.ts";
+
+const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
+
+/**
+ * Holds back the unavailable failure of a query whose session went away. The
+ * query atom reruns when it sees that session change, so settling first would
+ * show a failure for a query that is about to retry. While `session` is still
+ * current no rerun is coming, and the failure stands.
+ */
+const pendingOnceSessionReplaced =
+ (session: RpcSession.RpcSession) =>
+ <A, E, R>(effect: Effect.Effect<A, E, R>) =>
+ effect.pipe(
+ // The query's error type is generic, so its tags are unknown to `catchTags`.
+ Effect.catchIf(isEnvironmentRpcUnavailable, (error) =>
+ EnvironmentSupervisor.EnvironmentSupervisor.pipe(
+ Effect.flatMap((supervisor) => SubscriptionRef.get(supervisor.session)),
+ Effect.flatMap((current) =>
+ Option.isSome(current) && current.value === session ? Effect.fail(error) : Effect.never,
+ ),
+ ),
+ ),
+ );
interface EnvironmentAtomOptions<Input, A, E, R> {
readonly label: string;
@@ -601,7 +626,12 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
switch (connectionState.phase) {
case "connected":
return Option.isSome(session)
- ? runInEnvironment(target.environmentId, options.execute(target.input, emit))
+ ? runInEnvironment(
+ target.environmentId,
+ options
+ .execute(target.input, emit)
+ .pipe(pendingOnceSessionReplaced(session.value)),
+ )
: Effect.never;
case "connecting":
case "backoff":