Skip to content

Commit 241c3f0

Browse files
fix(web): cloud account service attaches in an effect, not during render
ManagedRelayAuthProvider called managedRelayAccountService.attach(clerk) during render, which subscribed to Clerk from render. attach now returns a detach function, and the provider attaches from an effect keyed on the Clerk instance whose cleanup detaches. ClerkProvider creates that instance, so the provider's mount is its lifetime. Adds a test that a failed device listing logs once with two readers mounted; it fails on main, where the query manager does not log. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 01318e0 commit 241c3f0

4 files changed

Lines changed: 83 additions & 19 deletions

File tree

‎apps/web/src/cloud/managedAuth.tsx‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
settleAsyncResult,
1111
} from "@t3tools/client-runtime/state/runtime";
1212
import * as Effect from "effect/Effect";
13-
import type { ReactNode } from "react";
13+
import { useEffect, type ReactNode } from "react";
1414

1515
import { environmentCatalog } from "../connection/catalog";
1616
import { runtime } from "../lib/runtime";
@@ -62,11 +62,9 @@ const managedRelayAccountService = createCloudAccountService<ClerkInstance>({
6262
});
6363

6464
export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
65-
// Render-time attach: ClerkProvider lazy-loads clerk-js, so its context is the
66-
// earliest place the instance exists. attach is idempotent, and IsomorphicClerk
67-
// queues listeners until load, so emissions and their atom writes arrive after
68-
// render.
65+
// ClerkProvider creates the Clerk instance and owns its lifetime, so the
66+
// account service observes it for as long as this provider is mounted.
6967
const clerk = useClerk();
70-
managedRelayAccountService.attach(clerk);
68+
useEffect(() => managedRelayAccountService.attach(clerk), [clerk]);
7169
return children;
7270
}

‎packages/client-runtime/src/relay/cloudAccountService.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,6 @@ describe("createCloudAccountService", () => {
102102
const { service, log, nextActivation } = makeService();
103103
const { source, emit } = makeSource();
104104
service.attach(source);
105-
service.attach(source);
106105

107106
emit(undefined);
108107
expect(service.getState()).toEqual({ _tag: "Unobserved" });
@@ -228,4 +227,18 @@ describe("createCloudAccountService", () => {
228227
expect(second.isSubscribed()).toBe(true);
229228
expect(log).toEqual(["detach"]);
230229
});
230+
231+
it("releases credentials and stops observing when detached", async () => {
232+
const { service, log, nextActivation } = makeService();
233+
const { source, emit, isSubscribed } = makeSource();
234+
const detach = service.attach(source);
235+
const activation = nextActivation();
236+
emit({ id: "a" });
237+
await activation;
238+
239+
detach();
240+
expect(isSubscribed()).toBe(false);
241+
expect(service.getState()).toEqual({ _tag: "Unobserved" });
242+
expect(log).toEqual(["prepare:a", "activate:a:false", "detach"]);
243+
});
231244
});

‎packages/client-runtime/src/relay/cloudAccountService.ts‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,10 @@ export type CloudAccountState =
9595

9696
export interface CloudAccountService<S extends CloudAccountSource> {
9797
/**
98-
* Observes `source` for the rest of its lifetime. Attaching a different
99-
* source detaches the previous one; re-attaching the same source is a no-op.
98+
* Observes `source` until the returned function runs. Attaching while another
99+
* source is attached detaches that one first.
100100
*/
101-
readonly attach: (source: S) => void;
101+
readonly attach: (source: S) => () => void;
102102
readonly getState: () => CloudAccountState;
103103
}
104104

@@ -182,16 +182,19 @@ export function createCloudAccountService<S extends CloudAccountSource>(
182182
activate(source, step, wasActive);
183183
};
184184

185+
const detach = () => {
186+
if (!attached) return;
187+
attached.unsubscribe();
188+
attached = null;
189+
generation += 1;
190+
state = { _tag: "Unobserved" };
191+
handlers.detach();
192+
};
193+
185194
return {
186195
attach(source) {
187-
if (attached?.source === source) return;
188-
if (attached) {
189-
attached.unsubscribe();
190-
generation += 1;
191-
state = { _tag: "Unobserved" };
192-
handlers.detach();
193-
}
194-
attached = {
196+
detach();
197+
const current = {
195198
source,
196199
unsubscribe: source.addListener((resources) => {
197200
// Clerk reports `user: undefined` until it loads; pending sessions
@@ -200,6 +203,10 @@ export function createCloudAccountService<S extends CloudAccountSource>(
200203
observe(source, resources.user?.id ?? null);
201204
}),
202205
};
206+
attached = current;
207+
return () => {
208+
if (attached === current) detach();
209+
};
203210
},
204211
getState: () => state,
205212
};

‎packages/client-runtime/src/relay/managedRelayState.test.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@ import {
66
import { describe, expect, it } from "@effect/vitest";
77
import * as Effect from "effect/Effect";
88
import * as Fiber from "effect/Fiber";
9-
import { AtomRegistry } from "effect/reactivity";
9+
import * as Layer from "effect/Layer";
10+
import * as Logger from "effect/Logger";
11+
import { Atom, AtomRegistry } from "effect/reactivity";
1012
import { afterEach, vi } from "vite-plus/test";
1113

1214
import * as ManagedRelay from "./managedRelay.ts";
1315
import {
16+
createManagedRelayQueryManager,
1417
createManagedRelaySession,
1518
deregisterManagedRelayEnvironment,
1619
ManagedRelaySessionError,
@@ -96,6 +99,49 @@ function clerkToken(expiresAtSeconds: number): string {
9699
describe("createManagedRelayQueryManager", () => {
97100
afterEach(resetRegistry);
98101

102+
it.effect("logs a failed device listing once however many readers mount it", () =>
103+
Effect.gen(function* () {
104+
const logs: Array<unknown> = [];
105+
const runtime = Atom.runtime(
106+
Layer.mergeAll(
107+
Layer.succeed(
108+
ManagedRelay.ManagedRelayClient,
109+
createClient({
110+
listDevices: () =>
111+
Effect.fail(
112+
new ManagedRelay.ManagedRelayRequestFailedError({
113+
action: "list relay client devices",
114+
cause: new Error("relay down"),
115+
}),
116+
),
117+
}),
118+
),
119+
Logger.layer([Logger.make(({ message }) => logs.push(message))], {
120+
mergeWithExisting: false,
121+
}),
122+
),
123+
);
124+
const manager = createManagedRelayQueryManager(runtime);
125+
setSession();
126+
const atom = manager.devicesAtom("account-1");
127+
128+
const failed = Promise.withResolvers<void>();
129+
const readers = [0, 1].map(() =>
130+
registry.subscribe(
131+
atom,
132+
(result) => {
133+
if (result._tag === "Failure") failed.resolve();
134+
},
135+
{ immediate: true },
136+
),
137+
);
138+
yield* Effect.promise(() => failed.promise);
139+
for (const unsubscribe of readers) unsubscribe();
140+
141+
expect(logs).toEqual([["[t3-cloud] Relay device listing failed"]]);
142+
}),
143+
);
144+
99145
it.effect("rejects deregistration after the account changes", () =>
100146
Effect.gen(function* () {
101147
const unlinkEnvironment = vi.fn(() => Effect.succeed({ ok: true }));

0 commit comments

Comments
 (0)