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

usage.ts

61 lines2.3 KB

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​
12/** Refresh pricing, then await each selected environment's rescan while it remains connected. */
13export async function refreshUsage({
14 registry,
15 server,
16 presentations,
17 environmentIds,
18 input,
19}: {
20 registry: AtomRegistry.AtomRegistry;
21 server: Pick<
22 ReturnType<typeof createServerEnvironmentAtoms>,
23 "usageSummary" | "refreshUsageRates"
24 >;
25 presentations: Pick<ReturnType<typeof createEnvironmentPresentationAtoms>, "presentationAtom">;
26 environmentIds: readonly EnvironmentId[];
27 input: UsageSummaryInput;
28}): Promise<void> {
29 await Promise.all(
30 environmentIds.map(async (environmentId) => {
31 const query = server.usageSummary({ environmentId, input });
32 const presentation = presentations.presentationAtom(environmentId);
33 const controller = new AbortController();
34 const abortWhenDisconnected = () => {
35 if (registry.get(presentation)?.connection.phase !== "connected") controller.abort();
36 };
37 const unsubscribe = registry.subscribe(presentation, abortWhenDisconnected);
38 abortWhenDisconnected();
39 try {
40 const ratesResult = await runAtomCommand(
41 registry,
42 server.refreshUsageRates,
43 { environmentId, input: {} },
44 { reportFailure: false },
45 );
46 const sessionUnavailable =
47 ratesResult._tag === "Failure" &&
48 isEnvironmentRpcUnavailable(squashAtomCommandFailure(ratesResult));
49 // Invalidate even on failure so reconnects cannot reuse the old summary.
50 registry.refresh(query);
51 if (sessionUnavailable || controller.signal.aborted) return;
52 await executeAtomQuery(registry, query, {
53 reportFailure: false,
54 signal: controller.signal,
55 });
56 } finally {
57 unsubscribe();
58 }
59 }),
60 );