Open History to see the last commit
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 { refreshUsage } from "@t3tools/client-runtime/state/usage";
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 isConnected: boolean;
34 readonly error: string | null;
35 readonly summary: UsageSummary | null;
36}
37
38/**
39 * Reads every environment's summary for one window.
40 *
41 * Keyed by the serialised window so switching ranges does not thrash the atom
42 * cache, and so each environment's query is shared with any other reader of the
43 * same window.
44 */
45const usageByWindowAtom = Atom.family((windowKey: string) =>
46 Atom.make((get): readonly EnvironmentUsageStatus[] => {
47 const input = JSON.parse(windowKey) as UsageSummaryInput;
48 const presentations = get(environmentPresentations.presentationsAtom);
49
50 const statuses: EnvironmentUsageStatus[] = [];
51 for (const [environmentId, presentation] of presentations) {
52 const result = get(serverEnvironment.usageSummary({ environmentId, input }));
53 statuses.push({
54 environmentId,
55 label: presentation.entry.target.label,
56 isPending: result.waiting,
57 isConnected: presentation.connection.phase === "connected",
58 error: result._tag === "Failure" ? "This environment could not report usage." : null,
59 summary: Option.getOrNull(AsyncResult.value(result)),
60 });
61 }
62 return statuses;
63 }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
64);
65
66export interface UsageView {
67 readonly merged: MergedUsage;
68 readonly environments: readonly EnvironmentUsageStatus[];
69 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
70 /** True until at least one environment has answered. */
71 readonly isPending: boolean;
72 /**
73 * True while environments that have not failed are still answering. Failed
74 * environments are reported in the environment menu: totals will not
75 * improve by waiting on them, so they must not read as "still reporting".
76 */
77 readonly isPartial: boolean;
78 readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
79}
80
81export function useUsage(
82 input: UsageSummaryInput,
83 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
84): UsageView {
85 const windowKey = useMemo(
86 () =>
87 JSON.stringify({
88 sinceDay: input.sinceDay,
89 untilDay: input.untilDay,
90 timeZone: input.timeZone,
91 resolution: input.resolution,
92 sinceTime: input.sinceTime,
93 untilTime: input.untilTime,
94 }),
95 [
96 input.sinceDay,
97 input.untilDay,
98 input.timeZone,
99 input.resolution,
100 input.sinceTime,
101 input.untilTime,
102 ],
103 );
104 const atom = usageByWindowAtom(windowKey);
105 const environments = useAtomValue(atom);
106 const selectedEnvironments = useMemo(
107 () =>
108 selectedEnvironmentIds === null
109 ? environments
110 : environments.filter(({ environmentId }) => selectedEnvironmentIds.has(environmentId)),
111 [environments, selectedEnvironmentIds],
112 );
113
114 const refresh = useCallback(
115 (nextInput?: UsageSummaryInput) =>
116 refreshUsage({
117 registry: appAtomRegistry,
118 server: serverEnvironment,
119 presentations: environmentPresentations,
120 environmentIds: selectedEnvironments.map(({ environmentId }) => environmentId),
121 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
122 }),
123 [selectedEnvironments, windowKey],
124 );
125
126 const merged = useMemo(() => {
127 const answered: EnvironmentUsage[] = selectedEnvironments.flatMap((environment) =>
128 environment.summary === null
129 ? []
130 : [
131 {
132 environmentId: environment.environmentId,
133 label: environment.label,
134 summary: environment.summary,
135 },
136 ],
137 );
138 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
139 }, [selectedEnvironments]);
140
141 const answeredCount = selectedEnvironments.filter(
142 (environment) => environment.summary !== null,
143 ).length;
144 const stillReporting = selectedEnvironments.filter(
145 (environment) => environment.summary === null && environment.error === null,
146 ).length;
147
148 return {
149 merged,
150 environments,
151 selectedEnvironments,
152 isPending: answeredCount === 0 && stillReporting > 0,
153 isPartial: answeredCount > 0 && stillReporting > 0,
154 refresh,
155 };
156}