Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Free-tier ledger: stop re-rendering for a poll that found nothing (#8160)

ConnorYohdeaad25775c5
diff --git a/frontend/editor/src/core/services/accountLinkBlock.ts b/frontend/editor/src/core/services/accountLinkBlock.ts
index ad65edb717..9ec6ada8ad 100644
--- a/frontend/editor/src/core/services/accountLinkBlock.ts
+++ b/frontend/editor/src/core/services/accountLinkBlock.ts
@@ -65,6 +65,19 @@ export function clearAccountLinkBlock(): void {
}
/** Coalesces failures across navigation and reloads; blocked storage falls back to this app lifetime. */
+/**
+ * Lifts the block on a ledger read that shows room left. Called from the read
+ * itself, so it runs once per read that lands, unchanged or not, without a
+ * component watching for it. A read the block overtook is skipped: invalidating
+ * cancels it, and its answer was taken before the block.
+ */
+export function clearBlockIfAllowanceRemains(
+ balance: { remainingUnits: number },
+ signal: AbortSignal,
+): void {
+ if (!signal.aborted && balance.remainingUnits > 0) clearAccountLinkBlock();
+}
+
export function acknowledgeAccountLinkPrompt(): void {
shownInMemory = true;
try {
diff --git a/frontend/editor/src/portal/hooks/useFreeTierBalance.test.tsx b/frontend/editor/src/portal/hooks/useFreeTierBalance.test.tsx
index 788de03d35..b648511903 100644
--- a/frontend/editor/src/portal/hooks/useFreeTierBalance.test.tsx
+++ b/frontend/editor/src/portal/hooks/useFreeTierBalance.test.tsx
@@ -1,5 +1,14 @@
-import { act, renderHook, waitFor } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { Profiler, type ReactNode } from "react";
+import {
+ act,
+ cleanup,
+ render,
+ renderHook,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { baseQueryOptions } from "@app/query/queryClient";
import { TestQueryProvider } from "@portal/test/TestQueryProvider";
import { useFreeTierBalance } from "@portal/hooks/useFreeTierBalance";
import {
@@ -104,4 +113,106 @@ describe("local allowance refresh", () => {
probe.rerender();
expect(probe.result.current.data).toBeUndefined();
});
+
+ describe("render cost", () => {
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ /** The app's own defaults: the poll cadence and sharing are what is measured. */
+ function appClient() {
+ return new QueryClient({ defaultOptions: { queries: baseQueryOptions } });
+ }
+
+ async function settle() {
+ for (let i = 0; i < 4; i += 1) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ }
+ }
+
+ /**
+ * The connect rail reads only the balance, and a poll that found the same one
+ * is the common case. It used to re-render the rail twice per poll, because the
+ * hook spread the whole query result and so subscribed it to isFetching.
+ */
+ it("does not re-render a reader for a poll that found the same balance", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ let commits = 0;
+ function Rail() {
+ const { data } = useFreeTierBalance();
+ return <span>{data?.remainingUnits ?? "-"}</span>;
+ }
+ const client = appClient();
+ render(
+ <QueryClientProvider client={client}>
+ <Profiler
+ id="rail"
+ onRender={() => {
+ commits += 1;
+ }}
+ >
+ <Rail />
+ </Profiler>
+ </QueryClientProvider>,
+ );
+ await settle();
+ const reads = mocks.fetchFreeTier.mock.calls.length;
+ commits = 0;
+
+ for (let i = 0; i < 10; i += 1) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ await settle();
+ }
+
+ expect(mocks.fetchFreeTier.mock.calls.length).toBe(reads + 10);
+ expect(commits).toBe(0);
+ });
+ });
+
+ /**
+ * A poll can be mid-flight when a request reports the allowance exhausted. The
+ * report invalidates the balance, which cancels that poll - but its answer was
+ * taken before the block, so it must not be what lifts it.
+ */
+ it("does not let a poll overtaken by a block lift it", async () => {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <TestQueryProvider>{children}</TestQueryProvider>
+ );
+ const probe = renderHook(
+ () => ({ ledger: useFreeTierBalance(), block: useAccountLinkBlock() }),
+ { wrapper },
+ );
+ await waitFor(() =>
+ expect(probe.result.current.ledger.data?.remainingUnits).toBe(500),
+ );
+
+ let answerStalePoll: (value: ReturnType<typeof balance>) => void = () => {};
+ mocks.fetchFreeTier
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ answerStalePoll = resolve;
+ }),
+ )
+ .mockResolvedValue(balance(0));
+ act(() => {
+ void probe.result.current.ledger.refetch();
+ });
+
+ act(() => reportFreeTierExhausted());
+ await waitFor(() =>
+ expect(probe.result.current.ledger.data?.remainingUnits).toBe(0),
+ );
+
+ // The overtaken poll lands late, with the positive answer it was sent for.
+ await act(async () => {
+ answerStalePoll(balance(500));
+ });
+
+ expect(probe.result.current.block.exhausted).toBe(true);
+ });
});
diff --git a/frontend/editor/src/portal/hooks/useFreeTierBalance.ts b/frontend/editor/src/portal/hooks/useFreeTierBalance.ts
index ace9a6ac19..d0c46383bd 100644
--- a/frontend/editor/src/portal/hooks/useFreeTierBalance.ts
+++ b/frontend/editor/src/portal/hooks/useFreeTierBalance.ts
@@ -6,7 +6,7 @@ import { useConnectGate } from "@portal/hooks/useConnectGate";
import { qk } from "@portal/queries/keys";
import {
FREE_TIER_EXHAUSTED_EVENT,
- clearAccountLinkBlock,
+ clearBlockIfAllowanceRemains,
} from "@app/services/accountLinkBlock";
/** Admin-only local ledger; refreshes after a block and at rollover without reading a cloud wallet. */
@@ -17,7 +17,11 @@ export function useFreeTierBalance() {
const enabled = isAdmin && gated && !loading;
const query = useQuery({
queryKey: qk.freeTier(),
- queryFn: fetchFreeTier,
+ queryFn: async ({ signal }) => {
+ const balance = await fetchFreeTier();
+ clearBlockIfAllowanceRemains(balance, signal);
+ return balance;
+ },
enabled,
refetchInterval: 60_000,
retry: false,
@@ -32,26 +36,12 @@ export function useFreeTierBalance() {
return () => window.removeEventListener(FREE_TIER_EXHAUSTED_EVENT, refresh);
}, [client, enabled]);
- useEffect(() => {
- if (
- enabled &&
- query.isSuccess &&
- query.data &&
- !query.isFetching &&
- query.data.remainingUnits > 0
- ) {
- clearAccountLinkBlock();
- }
- }, [
- enabled,
- query.data,
- query.dataUpdatedAt,
- query.isFetching,
- query.isSuccess,
- ]);
-
+ // Named rather than spread: reading every field subscribes the caller to
+ // isFetching too, which flips twice a poll and re-rendered the connect rail
+ // for polls that found the same balance.
return {
- ...query,
data: enabled ? query.data : undefined,
+ isError: query.isError,
+ refetch: query.refetch,
};
}
diff --git a/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx b/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx
index 5222f7ee36..355f06c948 100644
--- a/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx
+++ b/frontend/editor/src/proprietary/components/AccountLinkNotice.test.tsx
@@ -1,12 +1,21 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { act, fireEvent, render, screen } from "@testing-library/react";
+import { Profiler } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MantineProvider } from "@mantine/core";
import { AccountLinkNotice } from "@app/components/AccountLinkNotice";
+import { baseQueryOptions } from "@app/query/queryClient";
import {
clearAccountLinkBlock,
reportFreeTierExhausted,
+ useAccountLinkBlock,
} from "@app/services/accountLinkBlock";
const { alert, begin, auth, get } = vi.hoisted(() => ({
@@ -189,4 +198,131 @@ describe("editor shared account-link modal", () => {
).toBeNull();
expect(get).not.toHaveBeenCalled();
});
+
+ describe("administrator ledger", () => {
+ afterEach(() => vi.useRealTimers());
+
+ const ledger = (remainingUnits: number) => ({
+ data: {
+ grantUnits: 500,
+ remainingUnits,
+ periodEnd: "2026-10-01T00:00:00",
+ },
+ });
+
+ function BlockProbe() {
+ const { exhausted } = useAccountLinkBlock();
+ return (
+ <output data-testid="block">{exhausted ? "blocked" : "clear"}</output>
+ );
+ }
+
+ /** The app's own defaults: staleTime decides what a newly shown block trusts. */
+ function mountOver(client: QueryClient, onRender?: () => void) {
+ const notice = <AccountLinkNotice />;
+ return render(
+ <QueryClientProvider client={client}>
+ <MantineProvider>
+ <MemoryRouter initialEntries={["/editor"]}>
+ {onRender ? (
+ <Profiler id="notice" onRender={onRender}>
+ {notice}
+ </Profiler>
+ ) : (
+ notice
+ )}
+ <BlockProbe />
+ </MemoryRouter>
+ </MantineProvider>
+ </QueryClientProvider>,
+ );
+ }
+
+ const appClient = () =>
+ new QueryClient({ defaultOptions: { queries: baseQueryOptions } });
+
+ async function settle() {
+ for (let i = 0; i < 4; i += 1) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ }
+ }
+
+ it("lifts the block once the ledger shows room again", async () => {
+ get.mockResolvedValue(ledger(120));
+ mountOver(appClient());
+
+ await act(async () => reportFreeTierExhausted());
+
+ await waitFor(() =>
+ expect(screen.getByTestId("block")).toHaveTextContent("clear"),
+ );
+ });
+
+ it("keeps the block while the ledger shows nothing left", async () => {
+ mountOver(appClient());
+
+ await act(async () => reportFreeTierExhausted());
+ await waitFor(() => expect(get).toHaveBeenCalled());
+ await act(async () => {});
+
+ expect(screen.getByTestId("block")).toHaveTextContent("blocked");
+ });
+
+ /**
+ * The modal stays open while the administrator is blocked, and polls the
+ * ledger every minute to notice the allowance coming back. A poll that found
+ * the same balance used to re-render the whole modal twice.
+ */
+ it("does not re-render the open modal for a poll that found the same balance", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ let commits = 0;
+ mountOver(appClient(), () => {
+ commits += 1;
+ });
+ await act(async () => reportFreeTierExhausted());
+ await settle();
+ const reads = get.mock.calls.length;
+ commits = 0;
+
+ for (let i = 0; i < 10; i += 1) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ await settle();
+ }
+
+ expect(get.mock.calls.length).toBe(reads + 10);
+ expect(commits).toBe(0);
+ });
+
+ /**
+ * The ledger only runs while a block is up, so when one appears, whatever it
+ * has cached was read before it. Lifting on that would override the server's
+ * newer answer with an older one.
+ */
+ it("does not lift a new block with a balance read before it", async () => {
+ const client = appClient();
+ mountOver(client);
+
+ // First block, then the allowance comes back: the ledger last read 120.
+ get.mockResolvedValue(ledger(120));
+ await act(async () => reportFreeTierExhausted());
+ await waitFor(() =>
+ expect(screen.getByTestId("block")).toHaveTextContent("clear"),
+ );
+
+ // Moments later a request is refused again, and this time it holds.
+ get.mockResolvedValue(ledger(0));
+ await act(async () => reportFreeTierExhausted());
+ await act(async () => {});
+ expect(screen.getByTestId("block")).toHaveTextContent("blocked");
+
+ // And it rests on a read taken after the block, not on the cached one.
+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ await act(async () => {});
+ expect(screen.getByTestId("block")).toHaveTextContent("blocked");
+ });
+ });
});
diff --git a/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx b/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx
index a4d0f018d4..a357bbeabb 100644
--- a/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx
+++ b/frontend/editor/src/proprietary/components/AccountLinkNotice.tsx
@@ -10,7 +10,7 @@ import type { FreeTierBalance } from "@app/components/account-link/FreeTierBalan
import {
acknowledgeAccountLinkPrompt,
- clearAccountLinkBlock,
+ clearBlockIfAllowanceRemains,
useAccountLinkBlock,
} from "@app/services/accountLinkBlock";
@@ -42,29 +42,23 @@ export function AccountLinkNotice({
!onShowOptions && !hasLinkDialog && isAdmin && !loading && exhausted;
const ledger = useQuery({
queryKey: ["accountLink", "editorFreeTier"],
- queryFn: async () =>
- (
- await apiClient.get<FreeTierBalance>("/api/v1/account-link/free-tier", {
- suppressErrorToast: true,
- skipAuthRedirect: true,
- })
- ).data,
+ queryFn: async ({ signal }) => {
+ const { data } = await apiClient.get<FreeTierBalance>(
+ "/api/v1/account-link/free-tier",
+ { suppressErrorToast: true, skipAuthRedirect: true },
+ );
+ clearBlockIfAllowanceRemains(data, signal);
+ return data;
+ },
enabled: readsBalance,
+ // This only runs while a block is up, so anything cached when one appears was
+ // read before it; the first read has to be fresh or it lifts the block on an
+ // older answer than the one that raised it.
+ staleTime: 0,
retry: false,
refetchInterval: 60_000,
});
- useEffect(() => {
- if (
- readsBalance &&
- ledger.isSuccess &&
- !ledger.isFetching &&
- ledger.data.remainingUnits > 0
- ) {
- clearAccountLinkBlock();
- }
- }, [readsBalance, ledger.isSuccess, ledger.isFetching, ledger.data]);
-
useEffect(() => {
if (!exhausted || hasLinkDialog) setOpen(false);
}, [exhausted, hasLinkDialog]);