Skip to content

Commit 42a410d

Browse files
committed
fix(client-runtime): queries stay pending while a connection hands off
A query whose request found its session gone settled as unavailable before the query atom saw the session change and reran it, and an enabled environment published a switched-off state before its first connection attempt. Both showed a failure for an environment that was only connecting.
1 parent 8d199b4 commit 42a410d

4 files changed

Lines changed: 146 additions & 5 deletions

File tree

‎packages/client-runtime/src/connection/registry.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,28 @@ describe("EnvironmentRegistry", () => {
637637
}),
638638
);
639639

640+
it.effect("does not expose a persisted environment as disconnected while it starts", () =>
641+
Effect.gen(function* () {
642+
const connectionStarted = yield* Deferred.make<void>();
643+
const finishConnection = yield* Deferred.make<void>();
644+
const harness = yield* makeHarness([TARGET], [], [], {
645+
beforeSessionConnect: () =>
646+
Deferred.succeed(connectionStarted, undefined).pipe(
647+
Effect.andThen(Deferred.await(finishConnection)),
648+
),
649+
});
650+
651+
yield* Effect.gen(function* () {
652+
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
653+
const state = yield* registry.state(TARGET.environmentId);
654+
655+
yield* Deferred.await(connectionStarted);
656+
expect(state.phase).toBe("connecting");
657+
yield* Deferred.succeed(finishConnection, undefined);
658+
}).pipe(Effect.provide(harness.layer), Effect.scoped);
659+
}),
660+
);
661+
640662
it.effect("exposes the current RPC generation to late query subscribers", () =>
641663
Effect.gen(function* () {
642664
const harness = yield* makeHarness([TARGET]);

‎packages/client-runtime/src/connection/registry.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,10 @@ export const make = Effect.gen(function* () {
364364
const environmentId = entry.target.environmentId;
365365
const scope = yield* Scope.fork(registryScope);
366366
const supervisor = yield* EnvironmentSupervisor.make(entry, {
367-
initiallyDesired: false,
367+
// An enabled environment starts out connecting. Starting it idle and
368+
// then asking it to connect would first publish the state of an
369+
// environment the user switched off.
370+
initiallyDesired: entry.enabled,
368371
learnRoutes: (input) => learnRoutes({ environmentId, ...input }),
369372
}).pipe(
370373
Effect.provideService(Connectivity.Connectivity, connectivity),
@@ -373,9 +376,6 @@ export const make = Effect.gen(function* () {
373376
Scope.provide(scope),
374377
Effect.onError(() => Scope.close(scope, Exit.void)),
375378
);
376-
if (entry.enabled) {
377-
yield* supervisor.connect;
378-
}
379379
yield* SubscriptionRef.update(serviceScopes, (current) => {
380380
const next = new Map(current);
381381
next.set(environmentId, { entry, supervisor, scope });

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

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,95 @@ describe("environment query lifecycle", () => {
449449
),
450450
);
451451

452+
it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
453+
Effect.scoped(
454+
Effect.gen(function* () {
455+
const firstStarted = Latch.makeUnsafe();
456+
const failFirst = Latch.makeUnsafe();
457+
const firstSettled = Latch.makeUnsafe();
458+
let executions = 0;
459+
const execute = Effect.suspend(() => {
460+
executions += 1;
461+
if (executions > 1) {
462+
return Effect.succeed("recovered");
463+
}
464+
firstStarted.openUnsafe();
465+
return failFirst.await.pipe(
466+
Effect.andThen(
467+
Effect.fail(
468+
new EnvironmentRpcUnavailableError({
469+
environmentId: QUERY_ENVIRONMENT.environmentId,
470+
message: "Query environment is not connected.",
471+
}),
472+
),
473+
),
474+
Effect.ensuring(
475+
Effect.sync(() => {
476+
firstSettled.openUnsafe();
477+
}),
478+
),
479+
);
480+
});
481+
const harness = yield* makeEnvironmentQueryHarness(execute);
482+
const registry = AtomRegistry.make();
483+
const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
484+
const unsubscribe = registry.subscribe(
485+
harness.atom,
486+
(result) => {
487+
observed.push(result);
488+
},
489+
{ immediate: true },
490+
);
491+
yield* Effect.addFinalizer(() =>
492+
Effect.sync(() => {
493+
unsubscribe();
494+
registry.dispose();
495+
}),
496+
);
497+
498+
yield* firstStarted.await;
499+
// No yield before the failure: the request finds its session gone
500+
// before the atom has processed the session change.
501+
yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
502+
failFirst.openUnsafe();
503+
yield* firstSettled.await;
504+
yield* Effect.yieldNow;
505+
506+
expect(observed.some(AsyncResult.isFailure)).toBe(false);
507+
508+
yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
509+
yield* SubscriptionRef.set(
510+
harness.supervisorState,
511+
queryConnectionState({ generation: 2 }),
512+
);
513+
expect(
514+
yield* AtomRegistry.getResult(registry, harness.atom, {
515+
suspendOnWaiting: true,
516+
}),
517+
).toBe("recovered");
518+
}),
519+
),
520+
);
521+
522+
it.effect("fails a query that reports unavailable while its session is still live", () =>
523+
Effect.scoped(
524+
Effect.gen(function* () {
525+
const unavailable = new EnvironmentRpcUnavailableError({
526+
environmentId: QUERY_ENVIRONMENT.environmentId,
527+
message: "The environment did not respond to the request.",
528+
});
529+
const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
530+
const registry = yield* mountEnvironmentQuery(harness.atom);
531+
532+
const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
533+
suspendOnWaiting: true,
534+
}).pipe(Effect.exit);
535+
536+
expect(exit).toStrictEqual(Exit.fail(unavailable));
537+
}),
538+
),
539+
);
540+
452541
it.effect.each([
453542
{
454543
condition: "after a manual disconnect",

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

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import * as Cause from "effect/Cause";
1010
import * as Effect from "effect/Effect";
1111
import * as Exit from "effect/Exit";
1212
import * as Option from "effect/Option";
13+
import * as Schema from "effect/Schema";
1314
import * as Stream from "effect/Stream";
1415
import * as SubscriptionRef from "effect/SubscriptionRef";
1516
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -31,6 +32,30 @@ import {
3132
subscribe,
3233
} from "../rpc/client.ts";
3334
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
35+
import type * as RpcSession from "../rpc/session.ts";
36+
37+
const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
38+
39+
/**
40+
* Holds back the unavailable failure of a query whose session went away. The
41+
* query atom reruns when it sees that session change, so settling first would
42+
* show a failure for a query that is about to retry. While `session` is still
43+
* current no rerun is coming, and the failure stands.
44+
*/
45+
const pendingOnceSessionReplaced =
46+
(session: RpcSession.RpcSession) =>
47+
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
48+
effect.pipe(
49+
// The query's error type is generic, so its tags are unknown to `catchTags`.
50+
Effect.catchIf(isEnvironmentRpcUnavailable, (error) =>
51+
EnvironmentSupervisor.EnvironmentSupervisor.pipe(
52+
Effect.flatMap((supervisor) => SubscriptionRef.get(supervisor.session)),
53+
Effect.flatMap((current) =>
54+
Option.isSome(current) && current.value === session ? Effect.fail(error) : Effect.never,
55+
),
56+
),
57+
),
58+
);
3459

3560
interface EnvironmentAtomOptions<Input, A, E, R> {
3661
readonly label: string;
@@ -565,7 +590,12 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
565590
switch (connectionState.phase) {
566591
case "connected":
567592
return Option.isSome(session)
568-
? runInEnvironment(target.environmentId, options.execute(target.input, emit))
593+
? runInEnvironment(
594+
target.environmentId,
595+
options
596+
.execute(target.input, emit)
597+
.pipe(pendingOnceSessionReplaced(session.value)),
598+
)
569599
: Effect.never;
570600
case "connecting":
571601
case "backoff":

0 commit comments

Comments
 (0)