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

usage.ts

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