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

usage.ts

119 lines4.5 KB

1import type { EnvironmentId, UsageModelFilter, UsageSummaryInput } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Schema from "effect/Schema";
4import type { AtomRegistry } from "effect/reactivity";
5import { mFallback, msg } from "gt-i18n";
6import type { M } from "gt-i18n";
7​
8import { errorDisplayMessage } from "../errors/translatable.ts";
9import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
10import type { createEnvironmentPresentationAtoms } from "./presentation.ts";
11import { executeAtomQuery, runAtomCommand, squashAtomCommandFailure } from "./runtime.ts";
12import type { createServerEnvironmentAtoms } from "./server.ts";
13​
14const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
15​
16/** The Usage tab asks each environment with that environment's configured model filter. */
17export function usageSummaryInput(
18 input: UsageSummaryInput,
19 modelFilter: UsageModelFilter | undefined,
20): UsageSummaryInput {
21 return modelFilter === undefined ? input : { ...input, modelFilter };
23​
24/** The server's reason a reset credit could not be used, or a generic line when it gave none. */
25export function resetCreditFailureText(
26 result: { readonly cause: Cause.Cause<unknown> },
27 resolve: M = mFallback,
28): string {
29 // Squashing an interrupt-only cause invents Effect's own "All fibers interrupted" text.
30 const failed = Cause.hasFails(result.cause) || Cause.hasDies(result.cause);
31 return (
32 (failed ? errorDisplayMessage(squashAtomCommandFailure(result), resolve) : null) ??
33 resolve(msg("Could not use the reset credit."))
34 );
36​
37/** One key per environment selection; JSON keeps an id containing a comma whole. */
38export function environmentIdsKey(environmentIds: Iterable<EnvironmentId>): string {
39 const sorted = [...environmentIds].sort();
40 return sorted.length === 0 ? "" : JSON.stringify(sorted);
42​
43const limitsRefreshAfter = new Map<EnvironmentId, number>();
44const limitsRefreshes = new Map<EnvironmentId, Promise<unknown>>();
45​
46export async function refreshUsageLimits<A>(
47 environmentId: EnvironmentId,
48 refresh: () => Promise<A>,
49 automatic = false,
50): Promise<A | undefined> {
51 const pending = limitsRefreshes.get(environmentId);
52 if (pending !== undefined) {
53 return automatic ? undefined : ((await pending) as A);
54 }
55 const refreshAfter = limitsRefreshAfter.get(environmentId) ?? 0;
56 // @effect-diagnostics-next-line globalDate:off
57 if (automatic && Date.now() < refreshAfter) return;
58 const current = Promise.resolve()
59 .then(refresh)
60 .finally(() => {
61 limitsRefreshes.delete(environmentId);
62 // @effect-diagnostics-next-line globalDate:off
63 limitsRefreshAfter.set(environmentId, Date.now() + 5 * 60_000);
64 });
65 limitsRefreshes.set(environmentId, current);
66 return await current;
68​
69export async function refreshUsage({
70 registry,
71 server,
72 presentations,
73 environmentIds,
74 input,
75}: {
76 registry: AtomRegistry.AtomRegistry;
77 server: Pick<
78 ReturnType<typeof createServerEnvironmentAtoms>,
79 "usageSummary" | "refreshUsageRates" | "usageModelFilterAtom"
80 >;
81 presentations: Pick<ReturnType<typeof createEnvironmentPresentationAtoms>, "presentationAtom">;
82 environmentIds: readonly EnvironmentId[];
83 input: UsageSummaryInput;
84}): Promise<void> {
85 await Promise.all(
86 environmentIds.map(async (environmentId) => {
87 const query = server.usageSummary({
88 environmentId,
89 input: usageSummaryInput(input, registry.get(server.usageModelFilterAtom(environmentId))),
90 });
91 const presentation = presentations.presentationAtom(environmentId);
92 const controller = new AbortController();
93 const abortWhenDisconnected = () => {
94 if (registry.get(presentation)?.connection.phase !== "connected") controller.abort();
95 };
96 const unsubscribe = registry.subscribe(presentation, abortWhenDisconnected);
97 abortWhenDisconnected();
98 try {
99 const ratesResult = await runAtomCommand(
100 registry,
101 server.refreshUsageRates,
102 { environmentId, input: {} },
103 { reportFailure: false },
104 );
105 const sessionUnavailable =
106 ratesResult._tag === "Failure" &&
107 isEnvironmentRpcUnavailable(squashAtomCommandFailure(ratesResult));
108 registry.refresh(query);
109 if (sessionUnavailable || controller.signal.aborted) return;
110 await executeAtomQuery(registry, query, {
111 reportFailure: false,
112 signal: controller.signal,
113 });
114 } finally {
115 unsubscribe();
116 }
117 }),
118 );