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

useLoadBalancedEnvironment.ts

69 lines2.7 KB

1import { RegistryContext, useAtomValue } from "@effect/atom-react";
2import { chooseLoadBalancedEnvironment } from "@t3tools/client-runtime/load-balancing";
3import type { EnvironmentId } from "@t3tools/contracts";
4import { Atom } from "effect/reactivity";
5import { useContext } from "react";
6​
7import { serverEnvironment } from "../state/server";
8​
9// Mirrors the freshness window in chooseLoadBalancedEnvironment.
10const HOST_RESOURCES_FRESH_MS = 15_000;
11​
12// Keyed by content: callers derive the list every render.
13const hostResourcesAtom = Atom.family((environmentIdsKey: string) =>
14 Atom.make((get) => {
15 // Staleness is judged when a snapshot is read, which keeps render pure.
16 const evaluatedAt = Date.now();
17 const resources = (
18 environmentIdsKey === "" ? [] : (environmentIdsKey.split("\n") as EnvironmentId[])
19 ).map((environmentId) => {
20 const result = get(serverEnvironment.hostResources({ environmentId, input: {} }));
21 return {
22 environmentId,
23 resources: result._tag === "Success" ? result.value : null,
24 receivedAt: result._tag === "Success" ? result.timestamp : 0,
25 pending: result._tag === "Initial" || result.waiting,
26 failed: result._tag === "Failure",
27 };
28 });
29 // Re-read when the next fresh snapshot ages out, so a frozen evaluatedAt never selects it.
30 const nextExpiry = Math.min(
31 ...resources
32 .map((resource) => resource.receivedAt + HOST_RESOURCES_FRESH_MS)
33 .filter((expiresAt) => expiresAt >= evaluatedAt),
34 );
35 if (Number.isFinite(nextExpiry)) {
36 const timer = setTimeout(() => get.refreshSelf(), nextExpiry - evaluatedAt + 1);
37 get.addFinalizer(() => clearTimeout(timer));
38 }
39 return { evaluatedAt, resources };
40 }),
41);
42​
43/** Only mounted for unresolved automatic drafts, so idle clients do not poll hosts. */
44export function useLoadBalancedEnvironment(
45 environmentIds: readonly EnvironmentId[],
46 weights: Readonly<Record<string, number>>,
47) {
48 const registry = useContext(RegistryContext);
49 const refresh = (ids: readonly EnvironmentId[]) => {
50 for (const environmentId of ids) {
51 registry.refresh(serverEnvironment.hostResources({ environmentId, input: {} }));
52 }
53 };
54 const { evaluatedAt, resources } = useAtomValue(hostResourcesAtom(environmentIds.join("\n")));
55 const pending = resources.some((resource) => resource.pending);
56 const environmentId = chooseLoadBalancedEnvironment(
57 resources.map((resource) => ({
58 ...resource,
59 weight: weights[resource.environmentId] ?? 50,
60 })),
61 evaluatedAt,
62 ) as EnvironmentId | null;
63 return {
64 refresh,
65 pending,
66 environmentId,
67 failed: !pending && environmentId === null && resources.some((resource) => resource.failed),
68 };