#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
perf(policies): fetch the policy list once per session state (#8357)
briose506a15f6959
diff --git a/frontend/src/editor/core/tests/stubbed/startup-single-policies-fetch.spec.ts b/frontend/src/editor/core/tests/stubbed/startup-single-policies-fetch.spec.tsnew file mode 100644index 0000000000..a06fd6bec1--- /dev/null+++ b/frontend/src/editor/core/tests/stubbed/startup-single-policies-fetch.spec.ts@@ -0,0 +1,21 @@+import { test, expect } from "@editor/tests/helpers/stub-test-base";++test.use({ autoGoto: false });++test("cold load fetches the policy list exactly once", async ({ page }) => {+ const policyUrls: string[] = [];+ page.on("response", (r) => {+ if (new URL(r.url()).pathname === "/api/v1/policies") {+ policyUrls.push(r.url());+ }+ });++ await page.goto("/editor", { waitUntil: "networkidle" });+ await page.locator(".workspace-frame").first().waitFor({+ state: "visible",+ timeout: 15000,+ });+ await page.waitForTimeout(2000);++ expect(policyUrls).toHaveLength(1);+});diff --git a/frontend/src/editor/proprietary/hooks/usePolicies.test.ts b/frontend/src/editor/proprietary/hooks/usePolicies.test.tsindex 18fde42fd4..ab040944d7 100644--- a/frontend/src/editor/proprietary/hooks/usePolicies.test.ts+++ b/frontend/src/editor/proprietary/hooks/usePolicies.test.ts@@ -177,4 +177,27 @@ describe("usePolicies", () => {rerender();await waitFor(() => expect(api.listPolicies).toHaveBeenCalledTimes(2));});++ it("does not let a sign-in join the outgoing session's in-flight read", async () => {+ api.userId = "user-1";+ let releaseSignedOutRead: (() => void) | undefined;+ api.listPolicies.mockImplementationOnce(async () => {+ await new Promise<void>((resolve) => {+ releaseSignedOutRead = resolve;+ });+ return [];+ });++ const { rerender } = renderHook(() => usePolicies());+ await waitFor(() => expect(api.listPolicies).toHaveBeenCalledTimes(1));++ // Signing in while user-1's read is still open must not reuse it: the read+ // was issued for the old session, so its rows are user-1's policies.+ api.userId = "user-2";+ rerender();+ expect(api.listPolicies).toHaveBeenCalledTimes(2);++ releaseSignedOutRead?.();+ await waitFor(() => expect(api.listPolicies).toHaveBeenCalledTimes(2));+ });});diff --git a/frontend/src/editor/proprietary/hooks/usePolicies.ts b/frontend/src/editor/proprietary/hooks/usePolicies.tsindex ac8e565b12..4e2736029b 100644--- a/frontend/src/editor/proprietary/hooks/usePolicies.ts+++ b/frontend/src/editor/proprietary/hooks/usePolicies.ts@@ -29,12 +29,41 @@ const RECONCILE_MAX_ATTEMPTS = 15;const reconcileRetryDelay = (attempt: number) =>Math.min(500 * 2 ** attempt, 5000);+// One in-flight reconcile read shared across mounts. A remount (or StrictMode+// double-invoke) would otherwise fire an identical fetch; the entry clears on+// settle so retries and later sessions still refetch. Keyed by session so a+// sign-in mid-flight cannot join the outgoing session's read and reconcile its+// team policies into the new one.+let reconcileInFlight: {+ sessionKey: string | null;+ promise: ReturnType<typeof fetchPoliciesByCategory>;+} | null = null;++function fetchPoliciesShared(+ sessionKey: string | null,+): ReturnType<typeof fetchPoliciesByCategory> {+ if (reconcileInFlight?.sessionKey === sessionKey) {+ return reconcileInFlight.promise;+ }+ const entry = {+ sessionKey,+ promise: fetchPoliciesByCategory().finally(() => {+ // Identity check: a newer session's entry must survive this settle.+ if (reconcileInFlight === entry) reconcileInFlight = null;+ }),+ };+ reconcileInFlight = entry;+ return entry.promise;+}+export function usePolicies() {const [policies, setPolicies] = useState<PoliciesByKey>(loadPolicies);const { refetch: refetchAppConfig } = useAppConfig();// Reconciling only on mount leaves the cache in its unconfigured default when the fetch ran// before there was a session, and every consumer reads that default as "no policy".- const { user } = useAuth();+ // The session is unknown until auth settles; reconciling earlier fetches for+ // nobody and re-fires once the user resolves.+ const { user, loading: authLoading } = useAuth();const sessionKey = user?.id ?? null;useEffect(() => onPoliciesChange(() => setPolicies(loadPolicies())), []);@@ -46,6 +75,7 @@ export function usePolicies() {// Retry with backoff since the backend may not be up yet.// On recovery, also re-resolve app config in case its admin/team-leader flags settled false while down.useEffect(() => {+ if (authLoading) return;let cancelled = false;let attempt = 0;let timer: ReturnType<typeof setTimeout> | undefined;@@ -53,7 +83,7 @@ export function usePolicies() {const reconcile = async () => {let byCategory;try {- byCategory = await fetchPoliciesByCategory();+ byCategory = await fetchPoliciesShared(sessionKey);} catch {if (cancelled || attempt >= RECONCILE_MAX_ATTEMPTS) return;timer = setTimeout(reconcile, reconcileRetryDelay(attempt++));@@ -99,7 +129,7 @@ export function usePolicies() {cancelled = true;if (timer) clearTimeout(timer);};- }, [sessionKey]);+ }, [sessionKey, authLoading]);return { policies };}