@@ -13,8 +13,14 @@ import {
1313 type UsageSummary ,
1414 type UsageSummaryInput ,
1515} from "@t3tools/contracts" ;
16- import { runAtomCommand } from "@t3tools/client-runtime/state/runtime" ;
16+ import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc" ;
17+ import {
18+ executeAtomQuery ,
19+ runAtomCommand ,
20+ squashAtomCommandFailure ,
21+ } from "@t3tools/client-runtime/state/runtime" ;
1722import * as Option from "effect/Option" ;
23+ import * as Schema from "effect/Schema" ;
1824import { AsyncResult , Atom } from "effect/unstable/reactivity" ;
1925import { useCallback , useMemo } from "react" ;
2026
@@ -23,6 +29,8 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
2329import { environmentPresentations } from "./presentation" ;
2430import { serverEnvironment } from "./server" ;
2531
32+ const isEnvironmentRpcUnavailable = Schema . is ( EnvironmentRpcUnavailableError ) ;
33+
2634export interface EnvironmentUsageStatus {
2735 readonly environmentId : EnvironmentId ;
2836 readonly label : string ;
@@ -121,12 +129,38 @@ export function useUsage(
121129 await Promise . all (
122130 selectedEnvironments . map ( async ( { environmentId } ) => {
123131 const query = serverEnvironment . usageSummary ( { environmentId, input } ) ;
124- await runAtomCommand (
125- appAtomRegistry ,
126- serverEnvironment . refreshUsageRates ,
127- { environmentId, input : { } } ,
128- { reportFailure : false } ,
129- ) . finally ( ( ) => appAtomRegistry . refresh ( query ) ) ;
132+ const presentationAtom = environmentPresentations . presentationAtom ( environmentId ) ;
133+ const controller = new AbortController ( ) ;
134+ const abortWhenDisconnected = ( ) => {
135+ if ( appAtomRegistry . get ( presentationAtom ) ?. connection . phase !== "connected" ) {
136+ controller . abort ( ) ;
137+ }
138+ } ;
139+ const unsubscribe = appAtomRegistry . subscribe ( presentationAtom , abortWhenDisconnected ) ;
140+ abortWhenDisconnected ( ) ;
141+
142+ try {
143+ const ratesResult = await runAtomCommand (
144+ appAtomRegistry ,
145+ serverEnvironment . refreshUsageRates ,
146+ { environmentId, input : { } } ,
147+ { reportFailure : false } ,
148+ ) ;
149+ const sessionUnavailable =
150+ ratesResult . _tag === "Failure" &&
151+ isEnvironmentRpcUnavailable ( squashAtomCommandFailure ( ratesResult ) ) ;
152+ if ( sessionUnavailable || controller . signal . aborted ) {
153+ appAtomRegistry . refresh ( query ) ;
154+ return ;
155+ }
156+ await executeAtomQuery ( appAtomRegistry , query , {
157+ refresh : true ,
158+ reportFailure : false ,
159+ signal : controller . signal ,
160+ } ) ;
161+ } finally {
162+ unsubscribe ( ) ;
163+ }
130164 } ) ,
131165 ) ;
132166 } ,
0 commit comments