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

usage.ts

139 lines4.6 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 { 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;
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;
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 resolution: input.resolution,
85 sinceTime: input.sinceTime,
86 untilTime: input.untilTime,
87 }),
88 [
89 input.sinceDay,
90 input.untilDay,
91 input.timeZone,
92 input.resolution,
93 input.sinceTime,
94 input.untilTime,
95 ],
96 );
97 const atom = usageByWindowAtom(windowKey);
98 const environments = useAtomValue(atom);
99​
100 // Refreshing only the derived atom would re-read the per-environment SWR
101 // queries within their stale window and change nothing. Refresh each
102 // environment's query so pull-to-refresh always rescans.
103 const refresh = useCallback(() => {
104 const input = JSON.parse(windowKey) as UsageSummaryInput;
105 for (const environment of environments) {
106 appAtomRegistry.refresh(
107 serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
108 );
109 }
110 }, [environments, windowKey]);
111​
112 const merged = useMemo(() => {
113 const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
114 environment.summary === null
115 ? []
116 : [
117 {
118 environmentId: environment.environmentId,
119 label: environment.label,
120 summary: environment.summary,
121 },
122 ],
123 );
124 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
125 }, [environments]);
126​
127 const answeredCount = environments.filter((environment) => environment.summary !== null).length;
128 const stillReporting = environments.filter(
129 (environment) => environment.summary === null && environment.error === null,
130 ).length;
131​
132 return {
133 merged,
134 environments,
135 isPending: answeredCount === 0 && stillReporting > 0,
136 isPartial: answeredCount > 0 && stillReporting > 0,
137 refresh,
138 };