Skip to content

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

feat(editor): move endpoint availability onto TanStack Query (#7285)

ConnorYoh35a861f4f80f
diff --git a/frontend/editor/src/core/api/config.ts b/frontend/editor/src/core/api/config.ts
index f0ba730e8c..94caba2c82 100644
--- a/frontend/editor/src/core/api/config.ts
+++ b/frontend/editor/src/core/api/config.ts
@@ -1,6 +1,7 @@
import apiClient from "@app/services/apiClient";
import { getSimulatedAppConfig } from "@app/testing/serverExperienceSimulations";
import type { AppConfig } from "@app/types/appConfig";
+import type { EndpointAvailabilityDetails } from "@app/types/endpointAvailability";
/** Unauthenticated and unreachable both mean "assume login is on". */
export const DEFAULT_APP_CONFIG: AppConfig = { enableLogin: true };
@@ -23,6 +24,35 @@ export async function fetchAppConfig(): Promise<AppConfig> {
}
}
+export type EndpointAvailabilityMap = Record<
+ string,
+ EndpointAvailabilityDetails
+>;
+
+/**
+ * Fires on app load before auth settles, so a 401 must not trigger the global
+ * login redirect. Callers treat a failure as "assume enabled".
+ */
+export async function fetchEndpointsAvailability(): Promise<EndpointAvailabilityMap> {
+ const response = await apiClient.get<EndpointAvailabilityMap>(
+ "/api/v1/config/endpoints-availability",
+ { suppressErrorToast: true, skipAuthRedirect: true },
+ );
+ return Object.fromEntries(
+ Object.entries(response.data).map(([name, detail]) => [
+ name,
+ { enabled: detail?.enabled ?? true, reason: detail?.reason ?? null },
+ ]),
+ );
+}
+
+export async function fetchEndpointEnabled(endpoint: string): Promise<boolean> {
+ const response = await apiClient.get<boolean>(
+ `/api/v1/config/endpoint-enabled?endpoint=${encodeURIComponent(endpoint)}`,
+ );
+ return response.data;
+}
+
export interface FooterInfo {
analyticsEnabled?: boolean;
termsAndConditions?: string;
diff --git a/frontend/editor/src/core/hooks/useEndpointConfig.test.tsx b/frontend/editor/src/core/hooks/useEndpointConfig.test.tsx
new file mode 100644
index 0000000000..59010dacd5
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useEndpointConfig.test.tsx
@@ -0,0 +1,149 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { renderHook, waitFor, act } from "@testing-library/react";
+import { TestQueryProvider } from "@app/tests/utils/TestQueryProvider";
+import {
+ useEndpointEnabled,
+ useMultipleEndpointsEnabled,
+} from "@app/hooks/useEndpointConfig";
+import {
+ fetchEndpointEnabled,
+ fetchEndpointsAvailability,
+} from "@app/api/config";
+
+vi.mock("@app/api/config", () => ({
+ fetchEndpointEnabled: vi.fn(),
+ fetchEndpointsAvailability: vi.fn(),
+}));
+
+const mockOne = vi.mocked(fetchEndpointEnabled);
+const mockAll = vi.mocked(fetchEndpointsAvailability);
+
+describe("useEndpointEnabled", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("reports null while loading, then the server's answer", async () => {
+ mockOne.mockResolvedValue(false);
+
+ const { result } = renderHook(() => useEndpointEnabled("ocr-pdf"), {
+ wrapper: TestQueryProvider,
+ });
+
+ expect(result.current.enabled).toBeNull();
+ await waitFor(() => expect(result.current.enabled).toBe(false));
+ });
+
+ it("stays null on failure rather than claiming disabled", async () => {
+ mockOne.mockRejectedValue(new Error("boom"));
+
+ const { result } = renderHook(() => useEndpointEnabled("ocr-pdf"), {
+ wrapper: TestQueryProvider,
+ });
+
+ await waitFor(() => expect(result.current.error).toBe("boom"));
+ expect(result.current.enabled).toBeNull();
+ });
+
+ it("does not fetch without an endpoint", () => {
+ const { result } = renderHook(() => useEndpointEnabled(""), {
+ wrapper: TestQueryProvider,
+ });
+
+ expect(result.current.loading).toBe(false);
+ expect(mockOne).not.toHaveBeenCalled();
+ });
+});
+
+describe("useMultipleEndpointsEnabled", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("projects the shared map onto the requested endpoints", async () => {
+ mockAll.mockResolvedValue({
+ "ocr-pdf": { enabled: false, reason: "DEPENDENCY" },
+ "add-stamp": { enabled: true, reason: null },
+ });
+
+ const { result } = renderHook(
+ () => useMultipleEndpointsEnabled(["ocr-pdf"]),
+ { wrapper: TestQueryProvider },
+ );
+
+ await waitFor(() =>
+ expect(result.current.endpointStatus).toEqual({ "ocr-pdf": false }),
+ );
+ expect(result.current.endpointDetails["ocr-pdf"].reason).toBe("DEPENDENCY");
+ });
+
+ it("serves every consumer from one request", async () => {
+ mockAll.mockResolvedValue({ "ocr-pdf": { enabled: true, reason: null } });
+
+ const { result } = renderHook(
+ () => ({
+ a: useMultipleEndpointsEnabled(["ocr-pdf"]),
+ b: useMultipleEndpointsEnabled(["ocr-pdf", "add-stamp"]),
+ }),
+ { wrapper: TestQueryProvider },
+ );
+
+ await waitFor(() => expect(result.current.a.loading).toBe(false));
+ expect(mockAll).toHaveBeenCalledTimes(1);
+ });
+
+ it("treats unknown endpoints as enabled", async () => {
+ mockAll.mockResolvedValue({});
+
+ const { result } = renderHook(
+ () => useMultipleEndpointsEnabled(["brand-new-tool"]),
+ { wrapper: TestQueryProvider },
+ );
+
+ await waitFor(() =>
+ expect(result.current.endpointStatus).toEqual({ "brand-new-tool": true }),
+ );
+ });
+
+ it("falls back to enabled when the check fails", async () => {
+ mockAll.mockRejectedValue(
+ Object.assign(new Error("unauthorised"), { response: { status: 401 } }),
+ );
+
+ const { result } = renderHook(
+ () => useMultipleEndpointsEnabled(["ocr-pdf", "add-stamp"]),
+ { wrapper: TestQueryProvider },
+ );
+
+ await waitFor(() =>
+ expect(result.current.endpointStatus).toEqual({
+ "ocr-pdf": true,
+ "add-stamp": true,
+ }),
+ );
+ // The fallback is the answer, so no retry.
+ expect(mockAll).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not fetch for an empty endpoint list", () => {
+ const { result } = renderHook(() => useMultipleEndpointsEnabled([]), {
+ wrapper: TestQueryProvider,
+ });
+
+ expect(result.current.loading).toBe(false);
+ expect(mockAll).not.toHaveBeenCalled();
+ });
+
+ it("refetches when a JWT becomes available", async () => {
+ mockAll.mockResolvedValue({ "ocr-pdf": { enabled: true, reason: null } });
+
+ const { result } = renderHook(
+ () => useMultipleEndpointsEnabled(["ocr-pdf"]),
+ { wrapper: TestQueryProvider },
+ );
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => {
+ window.dispatchEvent(new CustomEvent("jwt-available"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+ await waitFor(() => expect(mockAll).toHaveBeenCalledTimes(2));
+ });
+});
diff --git a/frontend/editor/src/core/hooks/useEndpointConfig.ts b/frontend/editor/src/core/hooks/useEndpointConfig.ts
index 4615164787..488375c853 100644
--- a/frontend/editor/src/core/hooks/useEndpointConfig.ts
+++ b/frontend/editor/src/core/hooks/useEndpointConfig.ts
@@ -1,75 +1,50 @@
-import { useCallback, useEffect, useState } from "react";
-import { isAxiosError } from "axios";
-import apiClient from "@app/services/apiClient";
+import { useCallback, useMemo } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ fetchEndpointEnabled,
+ fetchEndpointsAvailability,
+} from "@app/api/config";
+import { qk } from "@app/query/keys";
+import { CONFIG_STALE_TIME } from "@app/query/staleTime";
import { useJwtConfigSync } from "@app/hooks/useJwtConfigSync";
import type { EndpointAvailabilityDetails } from "@app/types/endpointAvailability";
-// Track whether we've done the global fetch to prevent duplicate requests
-let globalFetchDone = false;
-const globalEndpointCache: Record<string, EndpointAvailabilityDetails> = {};
+const OPTIMISTIC: EndpointAvailabilityDetails = { enabled: true, reason: null };
-function resetGlobalCache() {
- globalFetchDone = false;
- Object.keys(globalEndpointCache).forEach(
- (key) => delete globalEndpointCache[key],
- );
+function message(error: unknown): string | null {
+ if (!error) return null;
+ return error instanceof Error ? error.message : "Unknown error occurred";
}
-/**
- * Hook to check if a specific endpoint is enabled
- * This wraps the context for single endpoint checks
- */
+/** Whether one endpoint is enabled. `null` while loading and on failure. */
export function useEndpointEnabled(endpoint: string): {
enabled: boolean | null;
loading: boolean;
error: string | null;
refetch: () => Promise<void>;
} {
- const [enabled, setEnabled] = useState<boolean | null>(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
-
- const fetchEndpointStatus = async () => {
- if (!endpoint) {
- setEnabled(null);
- setLoading(false);
- return;
- }
-
- try {
- setLoading(true);
- setError(null);
- console.debug("[useEndpointConfig] Fetch endpoint status", { endpoint });
-
- const response = await apiClient.get<boolean>(
- `/api/v1/config/endpoint-enabled?endpoint=${encodeURIComponent(endpoint)}`,
- );
- const isEnabled = response.data;
- setEnabled(isEnabled);
- } catch (err) {
- const errorMessage =
- err instanceof Error ? err.message : "Unknown error occurred";
- setError(errorMessage);
- } finally {
- setLoading(false);
- }
- };
-
- useEffect(() => {
- fetchEndpointStatus();
- }, [endpoint]);
+ const { data, isPending, error, refetch } = useQuery({
+ queryKey: qk.endpointEnabled(endpoint),
+ queryFn: () => fetchEndpointEnabled(endpoint),
+ enabled: Boolean(endpoint),
+ staleTime: CONFIG_STALE_TIME,
+ });
return {
- enabled,
- loading,
- error,
- refetch: fetchEndpointStatus,
+ enabled: data ?? null,
+ loading: Boolean(endpoint) && isPending,
+ error: message(error),
+ refetch: useCallback(async () => {
+ await refetch();
+ }, [refetch]),
};
}
/**
- * Hook to check multiple endpoints at once using batch API
- * Returns a map of endpoint -> enabled status
+ * Availability for a set of endpoints, projected from one shared request for
+ * the whole map. Unknown endpoints and any failure read as enabled — this runs
+ * before auth settles, and disabling every tool on a hiccup is worse than
+ * letting a call fail later.
*/
export function useMultipleEndpointsEnabled(endpoints: string[]): {
endpointStatus: Record<string, boolean>;
@@ -78,174 +53,49 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
error: string | null;
refetch: () => Promise<void>;
} {
- const [endpointStatus, setEndpointStatus] = useState<Record<string, boolean>>(
- {},
- );
- const [endpointDetails, setEndpointDetails] = useState<
- Record<string, EndpointAvailabilityDetails>
- >({});
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
-
- const fetchAllEndpointStatuses = useCallback(
- async (force = false) => {
- // Skip if already fetched globally and not forced
- if (!force && globalFetchDone) {
- console.debug("[useEndpointConfig] Using global cache");
- const cached = endpoints.reduce(
- (acc, endpoint) => {
- const cachedDetails = globalEndpointCache[endpoint];
- if (cachedDetails) {
- acc.status[endpoint] = cachedDetails.enabled;
- acc.details[endpoint] = cachedDetails;
- } else {
- acc.status[endpoint] = true;
- }
- return acc;
- },
- {
- status: {} as Record<string, boolean>,
- details: {} as Record<string, EndpointAvailabilityDetails>,
- },
- );
- setEndpointStatus(cached.status);
- setEndpointDetails((prev) => ({ ...prev, ...cached.details }));
- setLoading(false);
- return;
- }
-
- if (!endpoints || endpoints.length === 0) {
- setEndpointStatus({});
- setEndpointDetails({});
- setLoading(false);
- return;
- }
-
- try {
- setLoading(true);
- setError(null);
- console.debug(
- "[useEndpointConfig] Fetching all endpoint statuses from server",
- );
-
- // Fetch all endpoints at once; auto-fires on app load, so a 401 must
- // fail silently instead of triggering the global login redirect.
- const response = await apiClient.get<
- Record<string, EndpointAvailabilityDetails>
- >(`/api/v1/config/endpoints-availability`, {
- suppressErrorToast: true,
- skipAuthRedirect: true,
- });
-
- // Populate global cache with all results
- Object.entries(response.data).forEach(([endpoint, details]) => {
- globalEndpointCache[endpoint] = {
- enabled: details?.enabled ?? true,
- reason: details?.reason ?? null,
- };
- });
- globalFetchDone = true;
-
- // Return status for the requested endpoints
- const fullStatus = endpoints.reduce(
- (acc, endpoint) => {
- const cachedDetails = globalEndpointCache[endpoint];
- if (cachedDetails) {
- acc.status[endpoint] = cachedDetails.enabled;
- acc.details[endpoint] = cachedDetails;
- } else {
- acc.status[endpoint] = true;
- }
- return acc;
- },
- {
- status: {} as Record<string, boolean>,
- details: {} as Record<string, EndpointAvailabilityDetails>,
- },
- );
-
- setEndpointStatus(fullStatus.status);
- setEndpointDetails((prev) => ({ ...prev, ...fullStatus.details }));
- } catch (err: unknown) {
- // On 401 (auth error), use optimistic fallback instead of disabling
- if (isAxiosError(err) && err.response?.status === 401) {
- console.warn(
- "[useEndpointConfig] 401 error - using optimistic fallback",
- );
- endpoints.forEach((endpoint) => {
- globalEndpointCache[endpoint] = { enabled: true, reason: null };
- });
- const optimisticStatus = endpoints.reduce(
- (acc, endpoint) => {
- acc.status[endpoint] = true;
- acc.details[endpoint] = { enabled: true, reason: null };
- return acc;
- },
- {
- status: {} as Record<string, boolean>,
- details: {} as Record<string, EndpointAvailabilityDetails>,
- },
- );
- setEndpointStatus(optimisticStatus.status);
- setEndpointDetails((prev) => ({
- ...prev,
- ...optimisticStatus.details,
- }));
- setLoading(false);
- return;
- }
-
- const errorMessage =
- err instanceof Error ? err.message : "Unknown error occurred";
- setError(errorMessage);
- console.error("[EndpointConfig] Failed to check endpoints:", err);
-
- // Fallback: assume all endpoints are enabled on error (optimistic)
- const optimisticStatus = endpoints.reduce(
- (acc, endpoint) => {
- acc.status[endpoint] = true;
- acc.details[endpoint] = { enabled: true, reason: null };
- return acc;
- },
- {
- status: {} as Record<string, boolean>,
- details: {} as Record<string, EndpointAvailabilityDetails>,
- },
- );
- setEndpointStatus(optimisticStatus.status);
- setEndpointDetails((prev) => ({
- ...prev,
- ...optimisticStatus.details,
- }));
- } finally {
- setLoading(false);
- }
- },
- [endpoints.join(",")],
+ const queryClient = useQueryClient();
+ const wanted = endpoints ?? [];
+
+ const { data, isPending, error, refetch } = useQuery({
+ queryKey: qk.endpointsAvailability(),
+ queryFn: fetchEndpointsAvailability,
+ enabled: wanted.length > 0,
+ staleTime: CONFIG_STALE_TIME,
+ // A failure already falls back to enabled, so a retry buys nothing and
+ // doubles a request that fires on load for every logged-out visitor.
+ retry: false,
+ });
+
+ const reload = useCallback(async () => {
+ await refetch();
+ }, [refetch]);
+
+ useJwtConfigSync(
+ useCallback(() => {
+ void queryClient.invalidateQueries({
+ queryKey: qk.endpointsAvailability(),
+ });
+ }, [queryClient]),
);
- useEffect(() => {
- fetchAllEndpointStatuses();
- }, [fetchAllEndpointStatuses]);
-
- // Re-fetch when auth state changes. Core implementation listens for the
- // proprietary `jwt-available` event; the SaaS no-op override means the
- // cache simply isn't invalidated on Supabase auth changes (today's behavior).
- // If SaaS later needs that, wire it up inside saas/hooks/useJwtConfigSync.ts.
- const handleAuthChange = useCallback(() => {
- console.debug(
- "[useEndpointConfig] Auth changed - clearing cache for refetch",
- );
- resetGlobalCache();
- fetchAllEndpointStatuses(true);
- }, [fetchAllEndpointStatuses]);
- useJwtConfigSync(handleAuthChange);
+ const key = wanted.join(",");
+ const projected = useMemo(() => {
+ const status: Record<string, boolean> = {};
+ const details: Record<string, EndpointAvailabilityDetails> = {};
+ if (!data && !error) return { status, details };
+ for (const endpoint of key ? key.split(",") : []) {
+ const detail = data?.[endpoint] ?? OPTIMISTIC;
+ status[endpoint] = detail.enabled;
+ details[endpoint] = detail;
+ }
+ return { status, details };
+ }, [data, error, key]);
return {
- endpointStatus,
- endpointDetails,
- loading,
- error,
- refetch: () => fetchAllEndpointStatuses(true),
+ endpointStatus: projected.status,
+ endpointDetails: projected.details,
+ loading: wanted.length > 0 && isPending,
+ error: message(error),
+ refetch: reload,
};
}
diff --git a/frontend/editor/src/core/query/keys.ts b/frontend/editor/src/core/query/keys.ts
index 6c6bacd552..a7a68ea256 100644
--- a/frontend/editor/src/core/query/keys.ts
+++ b/frontend/editor/src/core/query/keys.ts
@@ -1,6 +1,9 @@
/** Editor query keys: ["editor", <resource>, ...params]. */
export const qk = {
appConfig: () => ["editor", "appConfig"] as const,
+ endpointsAvailability: () => ["editor", "endpointsAvailability"] as const,
+ endpointEnabled: (endpoint: string) =>
+ ["editor", "endpointEnabled", endpoint] as const,
footerInfo: () => ["editor", "footerInfo"] as const,
groupEnabled: (group: string) => ["editor", "groupEnabled", group] as const,
users: () => ["editor", "users"] as const,