Skip to content
TypeScript

perf(web): the load-balancing hook compiles with the React Compiler (#20565)

Julius Marminge33672c47e3c4
diff --git a/apps/web/src/hooks/useLoadBalancedEnvironment.ts b/apps/web/src/hooks/useLoadBalancedEnvironment.ts
index 84e3c22210f..ad219945925 100644
--- a/apps/web/src/hooks/useLoadBalancedEnvironment.ts
+++ b/apps/web/src/hooks/useLoadBalancedEnvironment.ts
@@ -2,52 +2,63 @@ import { RegistryContext, useAtomValue } from "@effect/atom-react";
import { chooseLoadBalancedEnvironment } from "@t3tools/client-runtime/load-balancing";
import type { EnvironmentId } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
-import { useCallback, useContext, useMemo } from "react";
+import { useContext } from "react";
import { serverEnvironment } from "../state/server";
+// Mirrors the freshness window in chooseLoadBalancedEnvironment.
+const HOST_RESOURCES_FRESH_MS = 15_000;
+
+// Keyed by content: callers derive the list every render.
+const hostResourcesAtom = Atom.family((environmentIdsKey: string) =>
+ Atom.make((get) => {
+ // Staleness is judged when a snapshot is read, which keeps render pure.
+ const evaluatedAt = Date.now();
+ const resources = (
+ environmentIdsKey === "" ? [] : (environmentIdsKey.split("\n") as EnvironmentId[])
+ ).map((environmentId) => {
+ const result = get(serverEnvironment.hostResources({ environmentId, input: {} }));
+ return {
+ environmentId,
+ resources: result._tag === "Success" ? result.value : null,
+ receivedAt: result._tag === "Success" ? result.timestamp : 0,
+ pending: result._tag === "Initial" || result.waiting,
+ failed: result._tag === "Failure",
+ };
+ });
+ // Re-read when the next fresh snapshot ages out, so a frozen evaluatedAt never selects it.
+ const nextExpiry = Math.min(
+ ...resources
+ .map((resource) => resource.receivedAt + HOST_RESOURCES_FRESH_MS)
+ .filter((expiresAt) => expiresAt >= evaluatedAt),
+ );
+ if (Number.isFinite(nextExpiry)) {
+ const timer = setTimeout(() => get.refreshSelf(), nextExpiry - evaluatedAt + 1);
+ get.addFinalizer(() => clearTimeout(timer));
+ }
+ return { evaluatedAt, resources };
+ }),
+);
+
/** Only mounted for unresolved automatic drafts, so idle clients do not poll hosts. */
export function useLoadBalancedEnvironment(
environmentIds: readonly EnvironmentId[],
weights: Readonly<Record<string, number>>,
) {
const registry = useContext(RegistryContext);
- const refresh = useCallback(
- (ids: readonly EnvironmentId[]) => {
- for (const environmentId of ids) {
- registry.refresh(serverEnvironment.hostResources({ environmentId, input: {} }));
- }
- },
- [registry],
- );
- // Keyed by content: callers derive the list every render.
- const environmentIdsKey = environmentIds.join("\n");
- const resourcesAtom = useMemo(
- () =>
- Atom.make((get) =>
- (environmentIdsKey === "" ? [] : (environmentIdsKey.split("\n") as EnvironmentId[])).map(
- (environmentId) => {
- const result = get(serverEnvironment.hostResources({ environmentId, input: {} }));
- return {
- environmentId,
- resources: result._tag === "Success" ? result.value : null,
- receivedAt: result._tag === "Success" ? result.timestamp : 0,
- pending: result._tag === "Initial" || result.waiting,
- failed: result._tag === "Failure",
- };
- },
- ),
- ),
- [environmentIdsKey],
- );
- const resources = useAtomValue(resourcesAtom);
+ const refresh = (ids: readonly EnvironmentId[]) => {
+ for (const environmentId of ids) {
+ registry.refresh(serverEnvironment.hostResources({ environmentId, input: {} }));
+ }
+ };
+ const { evaluatedAt, resources } = useAtomValue(hostResourcesAtom(environmentIds.join("\n")));
const pending = resources.some((resource) => resource.pending);
const environmentId = chooseLoadBalancedEnvironment(
resources.map((resource) => ({
...resource,
weight: weights[resource.environmentId] ?? 50,
})),
- Date.now(),
+ evaluatedAt,
) as EnvironmentId | null;
return {
refresh,