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