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 { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
20import * as Option from "effect/Option";
21import { AsyncResult, Atom } from "effect/unstable/reactivity";
22import { useCallback, useMemo } from "react";
23
24import { appAtomRegistry } from "./atom-registry";
25import { environmentPresentations } from "./presentation";
26import { serverEnvironment } from "./server";
27
28export interface EnvironmentUsageStatus {
29 readonly environmentId: EnvironmentId;
30 readonly label: string;
31 readonly isPending: boolean;
32 readonly error: string | null;
33 readonly summary: UsageSummary | null;
34}
35
36/**
37 * Reads every environment's summary for one window.
38 *
39 * Keyed by the serialised window so switching ranges does not thrash the atom
40 * cache, and so each environment's query is shared with any other reader of the
41 * same window.
42 */
43const usageByWindowAtom = Atom.family((windowKey: string) =>
44 Atom.make((get): readonly EnvironmentUsageStatus[] => {
45 const input = JSON.parse(windowKey) as UsageSummaryInput;
46 const presentations = get(environmentPresentations.presentationsAtom);
47
48 const statuses: EnvironmentUsageStatus[] = [];
49 for (const [environmentId, presentation] of presentations) {
50 const result = get(serverEnvironment.usageSummary({ environmentId, input }));
51 statuses.push({
52 environmentId,
53 label: presentation.entry.target.label,
54 isPending: result.waiting,
55 error: result._tag === "Failure" ? "This environment could not report usage." : null,
56 summary: Option.getOrNull(AsyncResult.value(result)),
57 });
58 }
59 return statuses;
60 }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
61);
62
63export interface UsageView {
64 readonly merged: MergedUsage;
65 readonly environments: readonly EnvironmentUsageStatus[];
66 /** True until at least one environment has answered. */
67 readonly isPending: boolean;
68 /**
69 * True while environments that have not failed are still answering. Failed
70 * environments are reported through their own error rows: totals will not
71 * improve by waiting on them, so they must not read as "still reporting".
72 */
73 readonly isPartial: boolean;
74 readonly refresh: () => void;
75}
76
77export function useUsage(input: UsageSummaryInput): UsageView {
78 const windowKey = useMemo(
79 () =>
80 JSON.stringify({
81 sinceDay: input.sinceDay,
82 untilDay: input.untilDay,
83 timeZone: input.timeZone,
84 }),
85 [input.sinceDay, input.untilDay, input.timeZone],
86 );
87 const atom = usageByWindowAtom(windowKey);
88 const environments = useAtomValue(atom);
89
90 // Refreshing only the derived atom would re-read the per-environment SWR
91 // queries within their stale window and change nothing. Refresh each
92 // environment's query so pull-to-refresh always rescans.
93 const refresh = useCallback(() => {
94 const input = JSON.parse(windowKey) as UsageSummaryInput;
95 for (const environment of environments) {
96 appAtomRegistry.refresh(
97 serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
98 );
99 }
100 }, [environments, windowKey]);
101
102 const merged = useMemo(() => {
103 const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
104 environment.summary === null
105 ? []
106 : [
107 {
108 environmentId: environment.environmentId,
109 label: environment.label,
110 summary: environment.summary,
111 },
112 ],
113 );
114 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
115 }, [environments]);
116
117 const answeredCount = environments.filter((environment) => environment.summary !== null).length;
118 const stillReporting = environments.filter(
119 (environment) => environment.summary === null && environment.error === null,
120 ).length;
121
122 return {
123 merged,
124 environments,
125 isPending: answeredCount === 0 && stillReporting > 0,
126 isPartial: answeredCount > 0 && stillReporting > 0,
127 refresh,
128 };
129}