Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usage.ts

149 lines5.2 KB

1/**
2 * Multi-environment usage state.
3 *
4 * Every connected environment answers the same typed query; the client merges
5 * the results. Raw transcripts never leave the machine that produced them.
6 *
7 * Mirror of `apps/web/src/state/usage.ts` over mobile's atom wiring; the merge
8 * rules themselves live in `@t3tools/shared/usageMerge`.
9 *
10 * @module state/usage
11 */
12import { useAtomValue } from "@effect/atom-react";
13import {
14 USAGE_CONTRACT_VERSION,
15 type EnvironmentId,
16 type UsageSummary,
17 type UsageSummaryInput,
18} from "@t3tools/contracts";
19import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
20import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
21import * as Option from "effect/Option";
22import { AsyncResult, Atom } from "effect/unstable/reactivity";
23import { useCallback, useMemo } from "react";
24​
25import { appAtomRegistry } from "./atom-registry";
26import { environmentPresentations } from "./presentation";
27import { serverEnvironment } from "./server";
28​
29export interface EnvironmentUsageStatus {
30 readonly environmentId: EnvironmentId;
31 readonly label: string;
32 readonly isPending: boolean;
33 readonly error: string | null;
34 readonly summary: UsageSummary | null;
36​
37/**
38 * Reads every environment's summary for one window.
39 *
40 * Keyed by the serialised window so switching ranges does not thrash the atom
41 * cache, and so each environment's query is shared with any other reader of the
42 * same window.
43 */
44const usageByWindowAtom = Atom.family((windowKey: string) =>
45 Atom.make((get): readonly EnvironmentUsageStatus[] => {
46 const input = JSON.parse(windowKey) as UsageSummaryInput;
47 const presentations = get(environmentPresentations.presentationsAtom);
48​
49 const statuses: EnvironmentUsageStatus[] = [];
50 for (const [environmentId, presentation] of presentations) {
51 const result = get(serverEnvironment.usageSummary({ environmentId, input }));
52 statuses.push({
53 environmentId,
54 label: presentation.entry.target.label,
55 isPending: result.waiting,
56 error: result._tag === "Failure" ? "This environment could not report usage." : null,
57 summary: Option.getOrNull(AsyncResult.value(result)),
58 });
59 }
60 return statuses;
61 }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
62);
63​
64export interface UsageView {
65 readonly merged: MergedUsage;
66 readonly environments: readonly EnvironmentUsageStatus[];
67 /** True until at least one environment has answered. */
68 readonly isPending: boolean;
69 /**
70 * True while environments that have not failed are still answering. Failed
71 * environments are reported through their own error rows: totals will not
72 * improve by waiting on them, so they must not read as "still reporting".
73 */
74 readonly isPartial: boolean;
75 readonly refresh: () => void;
77​
78export function useUsage(input: UsageSummaryInput): UsageView {
79 const windowKey = useMemo(
80 () =>
81 JSON.stringify({
82 sinceDay: input.sinceDay,
83 untilDay: input.untilDay,
84 timeZone: input.timeZone,
85 resolution: input.resolution,
86 sinceTime: input.sinceTime,
87 untilTime: input.untilTime,
88 }),
89 [
90 input.sinceDay,
91 input.untilDay,
92 input.timeZone,
93 input.resolution,
94 input.sinceTime,
95 input.untilTime,
96 ],
97 );
98 const atom = usageByWindowAtom(windowKey);
99 const environments = useAtomValue(atom);
100​
101 // Refreshing only the derived atom would re-read the per-environment SWR
102 // queries within their stale window and change nothing. Refresh each
103 // environment's query so pull-to-refresh always rescans.
104 //
105 // Each environment refetches model pricing first, so a model released since
106 // its last daily fetch gets priced by the rescan. The rescan runs whether or
107 // not the refetch succeeds: an offline environment still recounts tokens.
108 const refresh = useCallback(() => {
109 const input = JSON.parse(windowKey) as UsageSummaryInput;
110 for (const environment of environments) {
111 const { environmentId } = environment;
112 const query = serverEnvironment.usageSummary({ environmentId, input });
113 void runAtomCommand(
114 appAtomRegistry,
115 serverEnvironment.refreshUsageRates,
116 { environmentId, input: {} },
117 { reportFailure: false },
118 ).finally(() => appAtomRegistry.refresh(query));
119 }
120 }, [environments, windowKey]);
121​
122 const merged = useMemo(() => {
123 const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
124 environment.summary === null
125 ? []
126 : [
127 {
128 environmentId: environment.environmentId,
129 label: environment.label,
130 summary: environment.summary,
131 },
132 ],
133 );
134 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
135 }, [environments]);
136​
137 const answeredCount = environments.filter((environment) => environment.summary !== null).length;
138 const stillReporting = environments.filter(
139 (environment) => environment.summary === null && environment.error === null,
140 ).length;
141​
142 return {
143 merged,
144 environments,
145 isPending: answeredCount === 0 && stillReporting > 0,
146 isPartial: answeredCount > 0 && stillReporting > 0,
147 refresh,
148 };