Open History to see the last commit
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 const evaluatedAt = Date.now();
16 const resources = (
17 environmentIdsKey === "" ? [] : (environmentIdsKey.split("\n") as EnvironmentId[])
18 ).map((environmentId) => {
19 const result = get(serverEnvironment.hostResources({ environmentId, input: {} }));
20 return {
21 environmentId,
22 resources: result._tag === "Success" ? result.value : null,
23 receivedAt: result._tag === "Success" ? result.timestamp : 0,
24 pending: result._tag === "Initial" || result.waiting,
25 failed: result._tag === "Failure",
26 };
27 });
28 // Re-read when the next fresh snapshot ages out, so a frozen evaluatedAt never selects it.
29 const nextExpiry = Math.min(
30 ...resources
31 .map((resource) => resource.receivedAt + HOST_RESOURCES_FRESH_MS)
32 .filter((expiresAt) => expiresAt >= evaluatedAt),
33 );
34 if (Number.isFinite(nextExpiry)) {
35 const timer = setTimeout(() => get.refreshSelf(), nextExpiry - evaluatedAt + 1);
36 get.addFinalizer(() => clearTimeout(timer));
37 }
38 return { evaluatedAt, resources };
39 }),
40);
41
42/** Only mounted for unresolved automatic drafts, so idle clients do not poll hosts. */
43export function useLoadBalancedEnvironment(
44 environmentIds: readonly EnvironmentId[],
45 weights: Readonly<Record<string, number>>,
46) {
47 const registry = useContext(RegistryContext);
48 const refresh = (ids: readonly EnvironmentId[]) => {
49 for (const environmentId of ids) {
50 registry.refresh(serverEnvironment.hostResources({ environmentId, input: {} }));
51 }
52 };
53 const { evaluatedAt, resources } = useAtomValue(hostResourcesAtom(environmentIds.join("\n")));
54 const pending = resources.some((resource) => resource.pending);
55 const environmentId = chooseLoadBalancedEnvironment(
56 resources.map((resource) => ({
57 ...resource,
58 weight: weights[resource.environmentId] ?? 50,
59 })),
60 evaluatedAt,
61 ) as EnvironmentId | null;
62 return {
63 refresh,
64 pending,
65 environmentId,
66 failed: !pending && environmentId === null && resources.some((resource) => resource.failed),
67 };
68}