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

usage.ts

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