Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
3import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
4import { Atom, type AtomRegistry } from "effect/reactivity";
5
6import { serverEnvironment } from "../../state/server";
7
8/**
9 * Whether the last finished limits refresh for an environment failed. Not kept
10 * alive: the limits view mounts it, and leaving the view forgets old failures.
11 */
12const limitsRefreshFailedAtom = Atom.family((environmentId: EnvironmentId) =>
13 Atom.make(false).pipe(Atom.withLabel(`mobile:limits-refresh-failed:${environmentId}`)),
14);
15
16export async function refreshEnvironmentLimits(
17 registry: AtomRegistry.AtomRegistry,
18 environmentId: EnvironmentId,
19 options: { readonly automatic?: boolean; readonly afterPending?: boolean } = {},
20): Promise<void> {
21 // One refresh runs per environment at a time, so results land in the order
22 // they were started and the newest outcome always wins.
23 const result = await refreshUsageLimits(
24 environmentId,
25 () =>
26 runAtomCommand(
27 registry,
28 serverEnvironment.refreshProviders,
29 { environmentId, input: {} },
30 { reportFailure: false },
31 ),
32 options.automatic,
33 options.afterPending,
34 );
35 if (result === undefined) return;
36 registry.set(limitsRefreshFailedAtom(environmentId), result._tag === "Failure");
37}
38
39// Mounting starts an automatic refresh, which refreshUsageLimits throttles to
40// one every few minutes per environment.
41const limitsAutoRefreshAtom = Atom.family((environmentId: EnvironmentId) =>
42 Atom.make((get) => {
43 void refreshEnvironmentLimits(get.registry, environmentId, { automatic: true });
44 }).pipe(Atom.withLabel(`mobile:limits-auto-refresh:${environmentId}`)),
45);
46
47export function environmentIdsKey(environmentIds: Iterable<EnvironmentId>): string {
48 return [...environmentIds].sort().join(",");
49}
50
51function splitEnvironmentIds(key: string): EnvironmentId[] {
52 return key === "" ? [] : key.split(",").map((id) => EnvironmentId.make(id));
53}
54
55/** Keyed by a sorted, comma-joined id list so equal selections share one atom. */
56export const limitsAutoRefreshSetAtom = Atom.family((environmentIds: string) =>
57 Atom.make((get) => {
58 for (const environmentId of splitEnvironmentIds(environmentIds)) {
59 get(limitsAutoRefreshAtom(environmentId));
60 }
61 }),
62);
63
64export const limitsRefreshFailuresAtom = Atom.family((environmentIds: string) =>
65 Atom.make((get) =>
66 splitEnvironmentIds(environmentIds).filter((environmentId) =>
67 get(limitsRefreshFailedAtom(environmentId)),
68 ),
69 ),
70);