@devries-cameron20 / t3code Mirror · read-only / commits / 6016969887
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 17:00 UTC

refactor(client): cloud account transitions run in one service (#24974)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 15:27 UTC 60169698879d771ea10b32fe59da151b36eeb758
9 files changed +582 -121
apps/mobile/src/features/cloud/managedRelayState.ts
+1 -9
@@ -12,7 +12,7 @@ import {
12 import type { EnvironmentId } from "@t3tools/contracts";
13 import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
14 import { AsyncResult, Atom } from "effect/reactivity";
15 -import { useCallback, useEffect } from "react";
15 +import { useCallback } from "react";
16
17 import * as Runtime from "../../lib/runtime";
18 import { appAtomRegistry } from "../../state/atom-registry";
@@ -53,14 +53,6 @@ export function useManagedRelayEnvironments() {
53 : EMPTY_ENVIRONMENTS_ATOM;
54 const result = useAtomValue(atom);
55 const snapshot = readManagedRelaySnapshotState(result);
56 - useEffect(() => {
57 - if (snapshot.error) {
58 - console.error("[t3-cloud] Relay environment listing failed", {
59 - message: snapshot.error,
60 - traceId: snapshot.errorTraceId,
61 - });
62 - }
63 - }, [snapshot.error, snapshot.errorTraceId]);
56 const refresh = useCallback(() => {
57 if (accountId) {
58 managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
apps/web/src/cloud/managedAuth.test.ts
+1 -1
@@ -9,7 +9,7 @@ import {
9 } from "./managedAuth";
10
11 vi.mock("@clerk/react", () => ({
12 - useAuth: vi.fn(),
12 + useClerk: vi.fn(),
13 }));
14
15 vi.mock("../lib/runtime", () => ({
apps/web/src/cloud/managedAuth.tsx
+39 -77
@@ -1,17 +1,20 @@
1 -import { useAuth } from "@clerk/react";
2 -import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
1 +import { useClerk } from "@clerk/react";
2 +import {
3 + createCloudAccountService,
4 + ManagedRelay,
5 + setManagedRelaySession,
6 +} from "@t3tools/client-runtime/relay";
7 import {
8 reportAtomCommandResult,
9 + runAtomCommand,
10 settleAsyncResult,
6 - settlePromise,
11 } from "@t3tools/client-runtime/state/runtime";
12 import * as Effect from "effect/Effect";
9 -import { useEffect, useRef, type ReactNode } from "react";
13 +import { useEffect, type ReactNode } from "react";
14
15 import { environmentCatalog } from "../connection/catalog";
16 import { runtime } from "../lib/runtime";
17 import { appAtomRegistry } from "../rpc/atomRegistry";
14 -import { useAtomCommand } from "../state/use-atom-command";
18 import { resolveRelayClerkTokenOptions } from "./publicConfig";
19
20 export function deactivateManagedRelayAuthentication(): void {
@@ -28,81 +31,40 @@ export function activateManagedRelayAuthentication(
31 });
32 }
33
31 -export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
32 - const { getToken, isLoaded, isSignedIn, userId } = useAuth({
33 - treatPendingAsSignedOut: false,
34 - });
35 - const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
36 - reportFailure: false,
37 - reportDefect: false,
38 - });
39 - const observedAccountRef = useRef<string | null | undefined>(undefined);
40 - const accountTransitionRef = useRef<Promise<void> | null>(null);
41 -
42 - useEffect(() => {
43 - if (!isLoaded) {
44 - return;
45 - }
46 -
47 - let cancelled = false;
48 - const previousAccount = observedAccountRef.current;
49 - const nextAccount = isSignedIn && userId ? userId : null;
50 - observedAccountRef.current = nextAccount;
34 +type ClerkInstance = ReturnType<typeof useClerk>;
35
52 - const queueAccountCleanup = () => {
53 - const previousTransition = accountTransitionRef.current ?? Promise.resolve();
54 - accountTransitionRef.current = previousTransition.then(async () => {
55 - const results = await Promise.all([
56 - removeRelayEnvironments(),
57 - settleAsyncResult(() =>
58 - runtime.runPromiseExit(
59 - ManagedRelay.ManagedRelayClient.pipe(
60 - Effect.flatMap((client) => client.resetTokenCache),
61 - ),
62 - ),
63 - ),
64 - ]);
65 - for (const result of results) {
66 - reportAtomCommandResult(result, { label: "cloud account cleanup" });
67 - }
68 - });
69 - return accountTransitionRef.current;
70 - };
36 +function clerkTokenReader(clerk: ClerkInstance): () => Promise<string | null> {
37 + return async () =>
38 + clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null;
39 +}
40
72 - if (!isSignedIn || !userId) {
73 - deactivateManagedRelayAuthentication();
74 - if (previousAccount !== null) {
75 - void queueAccountCleanup();
76 - }
77 - } else {
78 - const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
79 - const activateSession = () => {
80 - if (!cancelled) {
81 - activateManagedRelayAuthentication(userId, tokenProvider);
82 - }
83 - };
84 - const activateAfterTransition = (transition: Promise<void>) => {
85 - void (async () => {
86 - const result = await settlePromise(async () => {
87 - await transition;
88 - activateSession();
89 - });
90 - reportAtomCommandResult(result, { label: "cloud account activation" });
91 - })();
92 - };
93 - if (previousAccount !== undefined && previousAccount !== null && previousAccount !== userId) {
94 - deactivateManagedRelayAuthentication();
95 - activateAfterTransition(queueAccountCleanup());
96 - } else {
97 - activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
98 - }
41 +const managedRelayAccountService = createCloudAccountService<ClerkInstance>({
42 + deactivate: deactivateManagedRelayAuthentication,
43 + detach: deactivateManagedRelayAuthentication,
44 + cleanUp: async () => {
45 + const results = await Promise.all([
46 + runAtomCommand(appAtomRegistry, environmentCatalog.removeRelayEnvironments, undefined, {
47 + reportFailure: false,
48 + reportDefect: false,
49 + }),
50 + settleAsyncResult(() =>
51 + runtime.runPromiseExit(
52 + ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
53 + ),
54 + ),
55 + ]);
56 + for (const result of results) {
57 + reportAtomCommandResult(result, { label: "cloud account cleanup" });
58 }
100 - return () => {
101 - cancelled = true;
102 - };
103 - }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
104 -
105 - useEffect(() => () => deactivateManagedRelayAuthentication(), []);
59 + },
60 + activate: ({ source, accountId }) =>
61 + activateManagedRelayAuthentication(accountId, clerkTokenReader(source)),
62 +});
63
64 +export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
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.
67 + const clerk = useClerk();
68 + useEffect(() => managedRelayAccountService.attach(clerk), [clerk]);
69 return children;
70 }
apps/web/src/cloud/managedRelayState.ts
-17
@@ -19,7 +19,6 @@ import * as Context from "effect/Context";
19 import * as Effect from "effect/Effect";
20 import * as Layer from "effect/Layer";
21 import { AsyncResult, Atom } from "effect/reactivity";
22 -import { useEffect } from "react";
22
23 import { runtime } from "../lib/runtime";
24 import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -67,14 +66,6 @@ export function useManagedRelayEnvironments() {
66 : EMPTY_ENVIRONMENTS_ATOM;
67 const result = useAtomValue(atom);
68 const snapshot = readManagedRelaySnapshotState(result);
70 - useEffect(() => {
71 - if (snapshot.error) {
72 - console.error("[t3-cloud] Relay environment listing failed", {
73 - message: snapshot.error,
74 - traceId: snapshot.errorTraceId,
75 - });
76 - }
77 - }, [snapshot.error, snapshot.errorTraceId]);
69 const refresh = () => {
70 if (accountId) {
71 managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
@@ -94,14 +85,6 @@ export function useManagedRelayDevices() {
85 const atom = accountId ? managedRelayQueryManager.devicesAtom(accountId) : EMPTY_DEVICES_ATOM;
86 const result = useAtomValue(atom);
87 const snapshot = readManagedRelaySnapshotState(result);
97 - useEffect(() => {
98 - if (snapshot.error) {
99 - console.error("[t3-cloud] Relay device listing failed", {
100 - message: snapshot.error,
101 - traceId: snapshot.errorTraceId,
102 - });
103 - }
104 - }, [snapshot.error, snapshot.errorTraceId]);
88 const refresh = () => {
89 if (accountId) {
90 managedRelayQueryManager.refreshDevices(appAtomRegistry, accountId);
packages/client-runtime/src/relay/cloudAccountService.test.ts new
+244
@@ -0,0 +1,244 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import {
4 + type CloudAccountSource,
5 + createCloudAccountService,
6 + planCloudAccountStep,
7 +} from "./cloudAccountService.ts";
8 +
9 +type Emit = (user: { readonly id: string } | null | undefined) => void;
10 +
11 +function makeSource() {
12 + let listener: Parameters<CloudAccountSource["addListener"]>[0] | null = null;
13 + const source: CloudAccountSource = {
14 + addListener: (next) => {
15 + listener = next;
16 + return () => {
17 + listener = null;
18 + };
19 + },
20 + };
21 + const emit: Emit = (user) => listener?.({ user });
22 + return { source, emit, isSubscribed: () => listener !== null };
23 +}
24 +
25 +function makeService() {
26 + const log: string[] = [];
27 + const activated: Array<PromiseWithResolvers<void>> = [];
28 + const cleanedUp: Array<PromiseWithResolvers<void>> = [];
29 + const gates = new Map<
30 + string,
31 + { readonly started: PromiseWithResolvers<void>; readonly release: PromiseWithResolvers<void> }
32 + >();
33 + const service = createCloudAccountService<CloudAccountSource>({
34 + deactivate: () => log.push("deactivate"),
35 + detach: () => log.push("detach"),
36 + onSignOutTransition: () => log.push("signOutTransition"),
37 + cleanUp: async ({ accountId, wasActive }) => {
38 + log.push(`cleanUp:${accountId}:${wasActive}`);
39 + cleanedUp.shift()?.resolve();
40 + },
41 + prepare: async ({ accountId }) => {
42 + log.push(`prepare:${accountId}`);
43 + const gate = gates.get(accountId);
44 + gate?.started.resolve();
45 + await gate?.release.promise;
46 + },
47 + activate: ({ accountId, isAccountTransition }) => {
48 + log.push(`activate:${accountId}:${isAccountTransition}`);
49 + activated.shift()?.resolve();
50 + },
51 + });
52 + const nextActivation = () => {
53 + const deferred = Promise.withResolvers<void>();
54 + activated.push(deferred);
55 + return deferred.promise;
56 + };
57 + const nextCleanUp = () => {
58 + const deferred = Promise.withResolvers<void>();
59 + cleanedUp.push(deferred);
60 + return deferred.promise;
61 + };
62 + const gate = (accountId: string) => {
63 + const deferred = {
64 + started: Promise.withResolvers<void>(),
65 + release: Promise.withResolvers<void>(),
66 + };
67 + gates.set(accountId, deferred);
68 + return deferred;
69 + };
70 + return { service, log, nextActivation, nextCleanUp, gate };
71 +}
72 +
73 +describe("planCloudAccountStep", () => {
74 + it("treats the first observation as a non-transition", () => {
75 + expect(planCloudAccountStep(undefined, "a")).toEqual({
76 + _tag: "SignIn",
77 + accountId: "a",
78 + switchFromAccountId: null,
79 + isAccountTransition: false,
80 + });
81 + expect(planCloudAccountStep(undefined, null)).toEqual({
82 + _tag: "SignOut",
83 + previousAccountId: null,
84 + isAccountTransition: false,
85 + });
86 + });
87 +
88 + it("ignores repeats and switches from the previous account", () => {
89 + expect(planCloudAccountStep("a", "a")).toEqual({ _tag: "None" });
90 + expect(planCloudAccountStep(null, null)).toEqual({ _tag: "None" });
91 + expect(planCloudAccountStep("a", "b")).toEqual({
92 + _tag: "SignIn",
93 + accountId: "b",
94 + switchFromAccountId: "a",
95 + isAccountTransition: true,
96 + });
97 + });
98 +});
99 +
100 +describe("createCloudAccountService", () => {
101 + it("activates once per account however often Clerk emits", async () => {
102 + const { service, log, nextActivation } = makeService();
103 + const { source, emit } = makeSource();
104 + service.attach(source);
105 +
106 + emit(undefined);
107 + expect(service.getState()).toEqual({ _tag: "Unobserved" });
108 + const activation = nextActivation();
109 + emit({ id: "a" });
110 + emit({ id: "a" });
111 + expect(service.getState()).toEqual({ _tag: "Activating", accountId: "a" });
112 + await activation;
113 +
114 + expect(service.getState()).toEqual({ _tag: "Active", accountId: "a" });
115 + expect(log).toEqual(["prepare:a", "activate:a:false"]);
116 + });
117 +
118 + it("drops credentials synchronously and cleans up before activating the next account", async () => {
119 + const { service, log, nextActivation } = makeService();
120 + const { source, emit } = makeSource();
121 + service.attach(source);
122 + const first = nextActivation();
123 + emit({ id: "a" });
124 + await first;
125 + log.length = 0;
126 +
127 + const second = nextActivation();
128 + emit({ id: "b" });
129 + expect(log).toEqual(["deactivate"]);
130 + await second;
131 +
132 + expect(log).toEqual(["deactivate", "cleanUp:a:true", "prepare:b", "activate:b:true"]);
133 + });
134 +
135 + it("cleans up on sign-out, including a signed-out first observation", async () => {
136 + const { service, log, nextActivation, nextCleanUp } = makeService();
137 + const { source, emit } = makeSource();
138 + service.attach(source);
139 +
140 + const initialCleanUp = nextCleanUp();
141 + emit(null);
142 + await initialCleanUp;
143 + expect(log).toEqual(["deactivate", "cleanUp:null:false"]);
144 +
145 + const activation = nextActivation();
146 + emit({ id: "a" });
147 + await activation;
148 + log.length = 0;
149 +
150 + const cleanUp = nextCleanUp();
151 + emit(null);
152 + await cleanUp;
153 + expect(service.getState()).toEqual({ _tag: "SignedOut" });
154 + expect(log).toEqual(["signOutTransition", "deactivate", "cleanUp:a:true"]);
155 + });
156 +
157 + it("never activates an account that signed out while it was activating", async () => {
158 + const { service, log, nextCleanUp, gate } = makeService();
159 + const { source, emit } = makeSource();
160 + service.attach(source);
161 + const prepared = gate("a");
162 + emit({ id: "a" });
163 + await prepared.started.promise;
164 + const cleanUp = nextCleanUp();
165 + emit(null);
166 + prepared.release.resolve();
167 + await cleanUp;
168 +
169 + expect(service.getState()).toEqual({ _tag: "SignedOut" });
170 + expect(log).toEqual(["prepare:a", "signOutTransition", "deactivate", "cleanUp:a:false"]);
171 + });
172 +
173 + it("retries a rejected activation on the next emission for the same account", async () => {
174 + const log: string[] = [];
175 + const failed = Promise.withResolvers<void>();
176 + const activated = Promise.withResolvers<void>();
177 + let attempts = 0;
178 + const service = createCloudAccountService<CloudAccountSource>({
179 + deactivate: () => log.push("deactivate"),
180 + detach: () => log.push("detach"),
181 + cleanUp: async ({ accountId, wasActive }) => {
182 + log.push(`cleanUp:${accountId}:${wasActive}`);
183 + },
184 + prepare: async ({ accountId }) => {
185 + attempts += 1;
186 + log.push(`prepare:${accountId}`);
187 + if (attempts === 1) {
188 + // Queued before the rejection, so the service's catch runs before
189 + // the test's `await failed.promise` continuation.
190 + queueMicrotask(failed.resolve);
191 + throw new Error("restore failed");
192 + }
193 + },
194 + activate: ({ accountId, isAccountTransition }) => {
195 + log.push(`activate:${accountId}:${isAccountTransition}`);
196 + activated.resolve();
197 + },
198 + });
199 + const { source, emit } = makeSource();
200 + service.attach(source);
201 + emit(null);
202 + emit({ id: "a" });
203 + await failed.promise;
204 + expect(service.getState()).toMatchObject({ _tag: "Failed", accountId: "a" });
205 +
206 + emit({ id: "a" });
207 + await activated.promise;
208 +
209 + expect(service.getState()).toEqual({ _tag: "Active", accountId: "a" });
210 + expect(log).toEqual([
211 + "deactivate",
212 + "cleanUp:null:false",
213 + "prepare:a",
214 + "prepare:a",
215 + "activate:a:true",
216 + ]);
217 + });
218 +
219 + it("detaches from a replaced Clerk instance", () => {
220 + const { service, log } = makeService();
221 + const first = makeSource();
222 + const second = makeSource();
223 + service.attach(first.source);
224 + service.attach(second.source);
225 +
226 + expect(first.isSubscribed()).toBe(false);
227 + expect(second.isSubscribed()).toBe(true);
228 + expect(log).toEqual(["detach"]);
229 + });
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 + });
244 +});
packages/client-runtime/src/relay/cloudAccountService.ts new
+213
@@ -0,0 +1,213 @@
1 +import { reportAtomCommandResult, settlePromise } from "../state/runtime.ts";
2 +
3 +/**
4 + * The slice of a Clerk instance the account service needs. Clerk emits on
5 + * every resource change (token refreshes, profile edits), so the service
6 + * dedupes emissions down to account changes.
7 + */
8 +export interface CloudAccountSource {
9 + readonly addListener: (
10 + listener: (resources: { readonly user?: { readonly id: string } | null | undefined }) => void,
11 + ) => () => void;
12 +}
13 +
14 +interface CloudAccountSignIn {
15 + readonly _tag: "SignIn";
16 + readonly accountId: string;
17 + /** Signed-in account being replaced; its data is removed before activation. */
18 + readonly switchFromAccountId: string | null;
19 + readonly isAccountTransition: boolean;
20 +}
21 +
22 +export type CloudAccountStep =
23 + | { readonly _tag: "None" }
24 + | {
25 + readonly _tag: "SignOut";
26 + /** Account whose data is removed; null removes data of any account. */
27 + readonly previousAccountId: string | null;
28 + readonly isAccountTransition: boolean;
29 + }
30 + | CloudAccountSignIn;
31 +
32 +/**
33 + * `previous` is undefined until Clerk's first emission. A first emission that
34 + * is signed out still cleans up, so data left by an account that signed out
35 + * while the app was closed does not linger.
36 + */
37 +export function planCloudAccountStep(
38 + previous: string | null | undefined,
39 + next: string | null,
40 +): CloudAccountStep {
41 + if (previous === next) return { _tag: "None" };
42 + const isAccountTransition = previous !== undefined;
43 + if (next === null) {
44 + return { _tag: "SignOut", previousAccountId: previous ?? null, isAccountTransition };
45 + }
46 + return {
47 + _tag: "SignIn",
48 + accountId: next,
49 + switchFromAccountId: previous ?? null,
50 + isAccountTransition,
51 + };
52 +}
53 +
54 +export interface CloudAccountHandlers<S extends CloudAccountSource> {
55 + /** Synchronously drops every credential so nothing reads the old account during cleanup. */
56 + readonly deactivate: () => void;
57 + readonly cleanUp: (input: {
58 + readonly source: S;
59 + readonly accountId: string | null;
60 + /** Whether `accountId` finished activating, so per-account registrations exist. */
61 + readonly wasActive: boolean;
62 + }) => Promise<void>;
63 + /** Async work that must finish before the session is visible (draft restore etc.). */
64 + readonly prepare?: (input: {
65 + readonly source: S;
66 + readonly accountId: string;
67 + readonly isCurrent: () => boolean;
68 + }) => Promise<void>;
69 + readonly activate: (input: {
70 + readonly source: S;
71 + readonly accountId: string;
72 + readonly isAccountTransition: boolean;
73 + }) => void;
74 + readonly onSignOutTransition?: () => void;
75 + /** Releases credentials when the service stops observing a Clerk instance. */
76 + readonly detach: () => void;
77 +}
78 +
79 +export type CloudAccountState =
80 + | { readonly _tag: "Unobserved" }
81 + | { readonly _tag: "SignedOut" }
82 + | { readonly _tag: "Activating"; readonly accountId: string }
83 + | { readonly _tag: "Active"; readonly accountId: string }
84 + /**
85 + * Activation rejected. The next emission for the same account retries the
86 + * original step, so a transient failure recovers on Clerk's next resource
87 + * change (token refreshes emit regularly) without re-requesting onboarding.
88 + */
89 + | {
90 + readonly _tag: "Failed";
91 + readonly accountId: string;
92 + readonly step: CloudAccountSignIn;
93 + readonly wasActive: boolean;
94 + };
95 +
96 +export interface CloudAccountService<S extends CloudAccountSource> {
97 + /**
98 + * Observes `source` until the returned function runs. Attaching while another
99 + * source is attached detaches that one first.
100 + */
101 + readonly attach: (source: S) => () => void;
102 + readonly getState: () => CloudAccountState;
103 +}
104 +
105 +export function createCloudAccountService<S extends CloudAccountSource>(
106 + handlers: CloudAccountHandlers<S>,
107 +): CloudAccountService<S> {
108 + let attached: { readonly source: S; readonly unsubscribe: () => void } | null = null;
109 + let state: CloudAccountState = { _tag: "Unobserved" };
110 + // Bumped on every account change so a superseded activation never applies.
111 + let generation = 0;
112 + let tail: Promise<void> = Promise.resolve();
113 +
114 + const enqueue = (label: string, operation: () => Promise<void>) => {
115 + const run = tail.then(operation, operation);
116 + tail = run.then(
117 + () => undefined,
118 + () => undefined,
119 + );
120 + void settlePromise(() => run).then((result) => reportAtomCommandResult(result, { label }));
121 + };
122 +
123 + const observedAccount = (): string | null | undefined => {
124 + switch (state._tag) {
125 + case "Unobserved":
126 + return undefined;
127 + case "SignedOut":
128 + return null;
129 + default:
130 + return state.accountId;
131 + }
132 + };
133 +
134 + const activate = (source: S, step: CloudAccountSignIn, wasActive: boolean) => {
135 + const activation = generation;
136 + const isCurrent = () => activation === generation;
137 + state = { _tag: "Activating", accountId: step.accountId };
138 + if (step.switchFromAccountId !== null) handlers.deactivate();
139 + enqueue("cloud account activation", async () => {
140 + try {
141 + if (step.switchFromAccountId !== null) {
142 + await handlers.cleanUp({ source, accountId: step.switchFromAccountId, wasActive });
143 + }
144 + if (!isCurrent()) return;
145 + await handlers.prepare?.({ source, accountId: step.accountId, isCurrent });
146 + } catch (error) {
147 + if (isCurrent()) state = { _tag: "Failed", accountId: step.accountId, step, wasActive };
148 + throw error;
149 + }
150 + if (!isCurrent()) return;
151 + state = { _tag: "Active", accountId: step.accountId };
152 + handlers.activate({
153 + source,
154 + accountId: step.accountId,
155 + isAccountTransition: step.isAccountTransition,
156 + });
157 + });
158 + };
159 +
160 + const observe = (source: S, next: string | null) => {
161 + const previousState = state;
162 + if (previousState._tag === "Failed" && previousState.accountId === next) {
163 + generation += 1;
164 + activate(source, previousState.step, previousState.wasActive);
165 + return;
166 + }
167 + const step = planCloudAccountStep(observedAccount(), next);
168 + if (step._tag === "None") return;
169 + generation += 1;
170 + const wasActive = previousState._tag === "Active";
171 +
172 + if (step._tag === "SignOut") {
173 + state = { _tag: "SignedOut" };
174 + if (step.isAccountTransition) handlers.onSignOutTransition?.();
175 + handlers.deactivate();
176 + enqueue("cloud account cleanup", () =>
177 + handlers.cleanUp({ source, accountId: step.previousAccountId, wasActive }),
178 + );
179 + return;
180 + }
181 +
182 + activate(source, step, wasActive);
183 + };
184 +
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 +
194 + return {
195 + attach(source) {
196 + detach();
197 + const current = {
198 + source,
199 + unsubscribe: source.addListener((resources) => {
200 + // Clerk reports `user: undefined` until it loads; pending sessions
201 + // still carry a user and count as signed in.
202 + if (resources.user === undefined) return;
203 + observe(source, resources.user?.id ?? null);
204 + }),
205 + };
206 + attached = current;
207 + return () => {
208 + if (attached === current) detach();
209 + };
210 + },
211 + getState: () => state,
212 + };
213 +}
packages/client-runtime/src/relay/index.ts
+1
@@ -1,4 +1,5 @@
1 export * as Discovery from "./discovery.ts";
2 +export * from "./cloudAccountService.ts";
3 export * from "./errorPresentation.ts";
4 export * as ManagedRelay from "./managedRelay.ts";
5 export * from "./managedRelayState.ts";
packages/client-runtime/src/relay/managedRelayState.test.ts
+47 -1
@@ -6,11 +6,14 @@ import {
6 import { describe, expect, it } from "@effect/vitest";
7 import * as Effect from "effect/Effect";
8 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";
12 import { afterEach, vi } from "vite-plus/test";
13
14 import * as ManagedRelay from "./managedRelay.ts";
15 import {
16 + createManagedRelayQueryManager,
17 createManagedRelaySession,
18 deregisterManagedRelayEnvironment,
19 ManagedRelaySessionError,
@@ -96,6 +99,49 @@ function clerkToken(expiresAtSeconds: number): string {
99 describe("createManagedRelayQueryManager", () => {
100 afterEach(resetRegistry);
101
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 +
145 it.effect("rejects deregistration after the account changes", () =>
146 Effect.gen(function* () {
147 const unlinkEnvironment = vi.fn(() => Effect.succeed({ ok: true }));
packages/client-runtime/src/relay/managedRelayState.ts
+36 -16
@@ -278,29 +278,49 @@ function validateEnvironmentStatus(
278 return Effect.succeed(status);
279 }
280
281 +function describeManagedRelayFailure(cause: Cause.Cause<unknown>): {
282 + readonly message: string;
283 + readonly traceId: string | null;
284 +} {
285 + const error = Cause.squash(cause);
286 + return {
287 + message:
288 + isManagedRelayRequestFailedError(error) && error.relayError
289 + ? relayProtectedErrorMessage(error.relayError)
290 + : error instanceof Error
291 + ? error.message
292 + : "Could not load T3 Connect data.",
293 + traceId: findErrorTraceId(error),
294 + };
295 +}
296 +
297 export function readManagedRelaySnapshotState<A>(
298 result: AsyncResult.AsyncResult<A, unknown>,
299 ): ManagedRelaySnapshotState<A> {
284 - let error: string | null = null;
285 - let errorTraceId: string | null = null;
286 - if (result._tag === "Failure") {
287 - const cause = Cause.squash(result.cause);
288 - error =
289 - isManagedRelayRequestFailedError(cause) && cause.relayError
290 - ? relayProtectedErrorMessage(cause.relayError)
291 - : cause instanceof Error
292 - ? cause.message
293 - : "Could not load T3 Connect data.";
294 - errorTraceId = findErrorTraceId(cause);
295 - }
300 + const failure = result._tag === "Failure" ? describeManagedRelayFailure(result.cause) : null;
301 return {
302 data: Option.getOrNull(AsyncResult.value(result)),
298 - error,
299 - errorTraceId,
303 + error: failure?.message ?? null,
304 + errorTraceId: failure?.traceId ?? null,
305 isPending: result.waiting,
306 };
307 }
308
309 +// Logged where the listing runs so each failed fetch reports once, however many
310 +// components read the atom.
311 +const logListingFailure =
312 + (label: string) =>
313 + <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
314 + self.pipe(
315 + Effect.tapCause((cause) => {
316 + if (Cause.hasInterruptsOnly(cause)) return Effect.void;
317 + const { message, traceId } = describeManagedRelayFailure(cause);
318 + return Effect.logError(`[t3-cloud] Relay ${label} listing failed`).pipe(
319 + Effect.annotateLogs({ message, traceId }),
320 + );
321 + }),
322 + );
323 +
324 export function createManagedRelayQueryManager(
325 runtime: Atom.AtomRuntime<ManagedRelay.ManagedRelayClient>,
326 options?: {
@@ -349,7 +369,7 @@ export function createManagedRelayQueryManager(
369 { ...base, stage: "relay-request" },
370 relay.listEnvironments({ clerkToken }),
371 );
352 - }),
372 + }).pipe(logListingFailure("environment")),
373 )
374 .pipe(
375 Atom.swr({ staleTime, revalidateOnMount: true }),
@@ -372,7 +392,7 @@ export function createManagedRelayQueryManager(
392 { ...base, stage: "relay-request" },
393 relay.listDevices({ clerkToken }),
394 );
375 - }),
395 + }).pipe(logListingFailure("device")),
396 )
397 .pipe(
398 Atom.swr({ staleTime, revalidateOnMount: true }),