Skip to content

Commit ddcde11

Browse files
authored
fix(client-runtime): queries stay pending while a connection hands off (pingdotgg#18155)
1 parent d608709 commit ddcde11

4 files changed

Lines changed: 147 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
@@ -630,6 +630,28 @@ describe("EnvironmentRegistry", () => {
630630
}),
631631
);
632632

633+
it.effect("does not expose a persisted environment as disconnected while it starts", () =>
634+
Effect.gen(function* () {
635+
const connectionStarted = yield* Deferred.make<void>();
636+
const finishConnection = yield* Deferred.make<void>();
637+
const harness = yield* makeHarness([TARGET], [], [], {
638+
beforeSessionConnect: () =>
639+
Deferred.succeed(connectionStarted, undefined).pipe(
640+
Effect.andThen(Deferred.await(finishConnection)),
641+
),
642+
});
643+
644+
yield* Effect.gen(function* () {
645+
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
646+
expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connecting");
647+
648+
yield* Deferred.await(connectionStarted);
649+
expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connecting");
650+
yield* Deferred.succeed(finishConnection, undefined);
651+
}).pipe(Effect.provide(harness.layer), Effect.scoped);
652+
}),
653+
);
654+
633655
it.effect("exposes the current RPC generation to late query subscribers", () =>
634656
Effect.gen(function* () {
635657
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
@@ -356,7 +356,10 @@ export const make = Effect.gen(function* () {
356356
const environmentId = entry.target.environmentId;
357357
const scope = yield* Scope.fork(registryScope);
358358
const supervisor = yield* EnvironmentSupervisor.make(entry, {
359-
initiallyDesired: false,
359+
// An enabled environment starts out connecting. Starting it idle and
360+
// then asking it to connect would first publish the state of an
361+
// environment the user switched off.
362+
initiallyDesired: entry.enabled,
360363
learnRoutes: (input) => learnRoutes({ environmentId, ...input }),
361364
}).pipe(
362365
Effect.provideService(Connectivity.Connectivity, connectivity),
@@ -365,9 +368,6 @@ export const make = Effect.gen(function* () {
365368
Scope.provide(scope),
366369
Effect.onError(() => Scope.close(scope, Exit.void)),
367370
);
368-
if (entry.enabled) {
369-
yield* supervisor.connect;
370-
}
371371
yield* SubscriptionRef.update(serviceScopes, (current) => {
372372
const next = new Map(current);
373373
next.set(environmentId, { entry, supervisor, scope });

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

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,96 @@ describe("environment query lifecycle", () => {
517517
),
518518
);
519519

520+
it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
521+
Effect.scoped(
522+
Effect.gen(function* () {
523+
const firstStarted = Latch.makeUnsafe();
524+
const failFirst = Latch.makeUnsafe();
525+
const firstSettled = Latch.makeUnsafe();
526+
let executions = 0;
527+
const execute = Effect.suspend(() => {
528+
executions += 1;
529+
if (executions > 1) {
530+
return Effect.succeed("recovered");
531+
}
532+
firstStarted.openUnsafe();
533+
return failFirst.await.pipe(
534+
Effect.andThen(
535+
Effect.fail(
536+
new EnvironmentRpcUnavailableError({
537+
environmentId: QUERY_ENVIRONMENT.environmentId,
538+
message: "Query environment is not connected.",
539+
}),
540+
),
541+
),
542+
Effect.ensuring(
543+
Effect.sync(() => {
544+
firstSettled.openUnsafe();
545+
}),
546+
),
547+
);
548+
});
549+
const harness = yield* makeEnvironmentQueryHarness(execute);
550+
const registry = AtomRegistry.make();
551+
const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
552+
const unsubscribe = registry.subscribe(
553+
harness.atom,
554+
(result) => {
555+
observed.push(result);
556+
},
557+
{ immediate: true },
558+
);
559+
yield* Effect.addFinalizer(() =>
560+
Effect.sync(() => {
561+
unsubscribe();
562+
registry.dispose();
563+
}),
564+
);
565+
566+
yield* firstStarted.await;
567+
// No yield before the failure: the request finds its session gone
568+
// before the atom has processed the session change.
569+
yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
570+
failFirst.openUnsafe();
571+
yield* firstSettled.await;
572+
yield* Effect.yieldNow;
573+
574+
expect(observed.some(AsyncResult.isFailure)).toBe(false);
575+
576+
yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
577+
yield* SubscriptionRef.set(
578+
harness.supervisorState,
579+
queryConnectionState({ generation: 2 }),
580+
);
581+
expect(
582+
yield* AtomRegistry.getResult(registry, harness.atom, {
583+
suspendOnWaiting: true,
584+
}),
585+
).toBe("recovered");
586+
expect(observed.some(AsyncResult.isFailure)).toBe(false);
587+
}),
588+
),
589+
);
590+
591+
it.effect("fails a query that reports unavailable while its session is still live", () =>
592+
Effect.scoped(
593+
Effect.gen(function* () {
594+
const unavailable = new EnvironmentRpcUnavailableError({
595+
environmentId: QUERY_ENVIRONMENT.environmentId,
596+
message: "The environment did not respond to the request.",
597+
});
598+
const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
599+
const registry = yield* mountEnvironmentQuery(harness.atom);
600+
601+
const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
602+
suspendOnWaiting: true,
603+
}).pipe(Effect.exit);
604+
605+
expect(exit).toStrictEqual(Exit.fail(unavailable));
606+
}),
607+
),
608+
);
609+
520610
it.effect.each([
521611
{
522612
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
@@ -12,6 +12,7 @@ import * as Cause from "effect/Cause";
1212
import * as Effect from "effect/Effect";
1313
import * as Exit from "effect/Exit";
1414
import * as Option from "effect/Option";
15+
import * as Schema from "effect/Schema";
1516
import * as Stream from "effect/Stream";
1617
import * as SubscriptionRef from "effect/SubscriptionRef";
1718
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -33,6 +34,30 @@ import {
3334
subscribe,
3435
} from "../rpc/client.ts";
3536
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
37+
import type * as RpcSession from "../rpc/session.ts";
38+
39+
const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
40+
41+
/**
42+
* Holds back the unavailable failure of a query whose session went away. The
43+
* query atom reruns when it sees that session change, so settling first would
44+
* show a failure for a query that is about to retry. While `session` is still
45+
* current no rerun is coming, and the failure stands.
46+
*/
47+
const pendingOnceSessionReplaced =
48+
(session: RpcSession.RpcSession) =>
49+
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
50+
effect.pipe(
51+
// The query's error type is generic, so its tags are unknown to `catchTags`.
52+
Effect.catchIf(isEnvironmentRpcUnavailable, (error) =>
53+
EnvironmentSupervisor.EnvironmentSupervisor.pipe(
54+
Effect.flatMap((supervisor) => SubscriptionRef.get(supervisor.session)),
55+
Effect.flatMap((current) =>
56+
Option.isSome(current) && current.value === session ? Effect.fail(error) : Effect.never,
57+
),
58+
),
59+
),
60+
);
3661

3762
interface EnvironmentAtomOptions<Input, A, E, R> {
3863
readonly label: string;
@@ -601,7 +626,12 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
601626
switch (connectionState.phase) {
602627
case "connected":
603628
return Option.isSome(session)
604-
? runInEnvironment(target.environmentId, options.execute(target.input, emit))
629+
? runInEnvironment(
630+
target.environmentId,
631+
options
632+
.execute(target.input, emit)
633+
.pipe(pendingOnceSessionReplaced(session.value)),
634+
)
605635
: Effect.never;
606636
case "connecting":
607637
case "backoff":

0 commit comments

Comments
 (0)