Open History to see the last commit
1import type { EnvironmentId, UsageSummaryInput } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import type { AtomRegistry } from "effect/unstable/reactivity";
4
5import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
6import type { createEnvironmentPresentationAtoms } from "./presentation.ts";
7import { executeAtomQuery, runAtomCommand, squashAtomCommandFailure } from "./runtime.ts";
8import type { createServerEnvironmentAtoms } from "./server.ts";
9
10const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
11
12const limitsRefreshAfter = new Map<EnvironmentId, number>();
13const limitsRefreshes = new Map<EnvironmentId, Promise<unknown>>();
14
15export async function refreshUsageLimits<A>(
16 environmentId: EnvironmentId,
17 refresh: () => Promise<A>,
18 automatic = false,
19 afterPending = false,
20): Promise<A | undefined> {
21 const pending = limitsRefreshes.get(environmentId);
22 if (pending !== undefined) {
23 if (afterPending) {
24 try {
25 await pending;
26 } catch {
27 // The new check still needs to run if the earlier one failed.
28 }
29 return refreshUsageLimits(environmentId, refresh, false, true);
30 }
31 // Manual refresh waits for the current check; automatic refresh does not repeat it.
32 return automatic ? undefined : ((await pending) as A);
33 }
34 const refreshAfter = limitsRefreshAfter.get(environmentId) ?? 0;
35 // @effect-diagnostics-next-line globalDate:off
36 if (automatic && Date.now() < refreshAfter) return;
37 const current = Promise.resolve()
38 .then(refresh)
39 .finally(() => {
40 limitsRefreshes.delete(environmentId);
41 // @effect-diagnostics-next-line globalDate:off
42 limitsRefreshAfter.set(environmentId, Date.now() + 5 * 60_000);
43 });
44 limitsRefreshes.set(environmentId, current);
45 return await current;
46}
47
48/** Refresh pricing, then await each selected environment's rescan while it remains connected. */
49export async function refreshUsage({
50 registry,
51 server,
52 presentations,
53 environmentIds,
54 input,
55}: {
56 registry: AtomRegistry.AtomRegistry;
57 server: Pick<
58 ReturnType<typeof createServerEnvironmentAtoms>,
59 "usageSummary" | "refreshUsageRates"
60 >;
61 presentations: Pick<ReturnType<typeof createEnvironmentPresentationAtoms>, "presentationAtom">;
62 environmentIds: readonly EnvironmentId[];
63 input: UsageSummaryInput;
64}): Promise<void> {
65 await Promise.all(
66 environmentIds.map(async (environmentId) => {
67 const query = server.usageSummary({ environmentId, input });
68 const presentation = presentations.presentationAtom(environmentId);
69 const controller = new AbortController();
70 const abortWhenDisconnected = () => {
71 if (registry.get(presentation)?.connection.phase !== "connected") controller.abort();
72 };
73 const unsubscribe = registry.subscribe(presentation, abortWhenDisconnected);
74 abortWhenDisconnected();
75 try {
76 const ratesResult = await runAtomCommand(
77 registry,
78 server.refreshUsageRates,
79 { environmentId, input: {} },
80 { reportFailure: false },
81 );
82 const sessionUnavailable =
83 ratesResult._tag === "Failure" &&
84 isEnvironmentRpcUnavailable(squashAtomCommandFailure(ratesResult));
85 // Invalidate even on failure so reconnects cannot reuse the old summary.
86 registry.refresh(query);
87 if (sessionUnavailable || controller.signal.aborted) return;
88 await executeAtomQuery(registry, query, {
89 reportFailure: false,
90 signal: controller.signal,
91 });
92 } finally {
93 unsubscribe();
94 }
95 }),
96 );
97}