Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enforce sensible defaults for react-query #268

Merged
merged 2 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import tailwindPlugin from "eslint-plugin-tailwindcss";

const restrictedSyntax = {
reactQuery: {
useQuery: (v) =>
`CallExpression[callee.name='useQuery'] > ObjectExpression:first-child > Property[key.name='${v}']`,
useQueries: (v) =>
`CallExpression[callee.name='useQueries'] > ObjectExpression:first-child > Property[key.name='queries'] > ArrayExpression > ObjectExpression > Property[key.name='${v}']`,
},
};

export default tseslint.config(
{ ignores: ["dist"] },
{
Expand Down Expand Up @@ -56,6 +65,47 @@ export default tseslint.config(
],
},
],
"no-restricted-syntax": [
"error",
{
selector: [
restrictedSyntax.reactQuery.useQuery("staleTime"),
restrictedSyntax.reactQuery.useQuery("gcTime"),
restrictedSyntax.reactQuery.useQueries("staleTime"),
restrictedSyntax.reactQuery.useQueries("gcTime"),
].join(", "),
message:
"`staleTime` & `gcTime` should be managed via the `getQueryCacheConfig` util instead.",
},
{
selector: [
restrictedSyntax.reactQuery.useQuery("queryKey"),
restrictedSyntax.reactQuery.useQuery("queryFn"),
restrictedSyntax.reactQuery.useQueries("queryKey"),
restrictedSyntax.reactQuery.useQueries("queryFn"),
].join(", "),
message:
"'queryKey' & 'queryFn' should be managed by openapi-ts react-query integration instead. This allows standardized management of query keys & cache invalidation.",
},
{
selector: [
restrictedSyntax.reactQuery.useQuery("refetchOnMount"),
restrictedSyntax.reactQuery.useQuery("refetchOnReconnect"),
restrictedSyntax.reactQuery.useQuery("refetchOnWindowFocus"),
restrictedSyntax.reactQuery.useQueries("refetchOnMount"),
restrictedSyntax.reactQuery.useQueries("refetchOnReconnect"),
restrictedSyntax.reactQuery.useQueries("refetchOnWindowFocus"),
].join(", "),
message:
"`refetchOnMount`, `refetchOnReconnect` & `refetchOnWindowFocus` should be managed centrally in the react-query provider",
},
{
selector:
"CallExpression > MemberExpression[property.name='invalidateQueries']",
message:
"Do not directly call `invalidateQueries`. Instead, use the `invalidateQueries` helper function.",
},
],
"no-restricted-imports": [
"error",
{
Expand Down
4 changes: 2 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Header } from "./features/header/components/header";
import { PromptList } from "./components/PromptList";
import { usePromptsData } from "./hooks/usePromptsData";
import { useQueryGetWorkspaceMessages } from "./hooks/use-query-get-workspace-messages";
import { Sidebar } from "./components/Sidebar";
import { useSse } from "./hooks/useSse";
import Page from "./Page";

function App() {
const { data: prompts, isLoading } = usePromptsData();
const { data: prompts, isLoading } = useQueryGetWorkspaceMessages();
useSse();

return (
Expand Down
6 changes: 5 additions & 1 deletion src/components/react-query-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ export function QueryClientProvider({ children }: { children: ReactNode }) {
new QueryClient({
defaultOptions: {
queries: {
...getQueryCacheConfig("short"),
...getQueryCacheConfig("no-cache"),
refetchOnMount: true,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
},
},
}),
Expand All @@ -65,6 +68,7 @@ export function QueryClientProvider({ children }: { children: ReactNode }) {

setActiveWorkspaceName(newWorkspaceName);

// eslint-disable-next-line no-restricted-syntax
void queryClient.invalidateQueries({
refetchType: "all",
// Avoid a continuous loop
Expand Down
5 changes: 2 additions & 3 deletions src/features/alerts/hooks/use-query-get-workspace-alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
} from "@/api/generated";
import { v1GetWorkspaceAlertsOptions } from "@/api/generated/@tanstack/react-query.gen";
import { useActiveWorkspaceName } from "@/features/workspace/hooks/use-active-workspace-name";
import { getQueryCacheConfig } from "@/lib/react-query-utils";
import { useQuery } from "@tanstack/react-query";

export function useQueryGetWorkspaceAlerts<T = V1GetWorkspaceAlertsResponse>({
Expand Down Expand Up @@ -33,9 +34,7 @@ export function useQueryGetWorkspaceAlerts<T = V1GetWorkspaceAlertsResponse>({
...rest
} = useQuery({
...v1GetWorkspaceAlertsOptions(options),
refetchOnMount: true,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
...getQueryCacheConfig("5s"),
select,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@ export function useQueryGetWorkspaceTokenUsage<

return useQuery({
...v1GetWorkspaceTokenUsageOptions(options),
refetchOnMount: true,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
select,
});
}
21 changes: 10 additions & 11 deletions src/features/header/components/header-status-menu.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useCodeGateStatus } from "../hooks/use-codegate-status";
import { HealthStatus } from "../types";
import { useQueriesCodegateStatus } from "../hooks/use-queries-codegate-status";
import {
Button,
DialogTrigger,
Expand Down Expand Up @@ -40,27 +39,27 @@ type CodeGateHealthCheckStatus =
| "error_checking_health";

function deriveOverallStatus(
data: ReturnType<typeof useCodeGateStatus>["data"],
data: ReturnType<typeof useQueriesCodegateStatus>["data"],
isPending: boolean,
isError: boolean,
): CodeGateStatus {
if (isPending) return "loading";
if (isError) return "error_checking_status";

if (
data?.health === HealthStatus.HEALTHY &&
data?.health?.status === "healthy" &&
data.version?.error === null &&
data.version?.is_latest === false
)
return "update_available";

if (data?.health === HealthStatus.HEALTHY) return "healthy";
if (data?.health?.status === "healthy") return "healthy";

return "unhealthy";
}

function deriveVersionStatus(
data: ReturnType<typeof useCodeGateStatus>["data"],
data: ReturnType<typeof useQueriesCodegateStatus>["data"],
isPending: boolean,
isError: boolean,
): CodeGateVersionStatus {
Expand All @@ -72,14 +71,14 @@ function deriveVersionStatus(
}

function deriveHealthCheckStatus(
data: ReturnType<typeof useCodeGateStatus>["data"],
data: ReturnType<typeof useQueriesCodegateStatus>["data"],
isPending: boolean,
isError: boolean,
): CodeGateHealthCheckStatus {
if (isPending) return "loading";
if (isError) return "error_checking_health";

if (data?.health == HealthStatus.HEALTHY) return "healthy";
if (data?.health?.status === "healthy") return "healthy";
return "unhealthy";
}

Expand All @@ -102,7 +101,7 @@ function getButtonText(status: CodeGateStatus): string {

function getVersionText(
status: CodeGateVersionStatus,
data: ReturnType<typeof useCodeGateStatus>["data"],
data: ReturnType<typeof useQueriesCodegateStatus>["data"],
): ReactNode {
switch (status) {
case "error_checking_version":
Expand Down Expand Up @@ -262,7 +261,7 @@ function StatusPopover({
}: {
versionStatus: CodeGateVersionStatus;
healthCheckStatus: CodeGateHealthCheckStatus;
data: ReturnType<typeof useCodeGateStatus>["data"];
data: ReturnType<typeof useQueriesCodegateStatus>["data"];
}) {
return (
<Popover className="px-3 py-2 min-w-64" placement="bottom end">
Expand Down Expand Up @@ -290,7 +289,7 @@ function StatusPopover({
}

export function HeaderStatusMenu() {
const { data, isPending, isError } = useCodeGateStatus();
const { data, isPending, isError } = useQueriesCodegateStatus();

const status = deriveOverallStatus(data, isPending, isError);
const versionStatus = deriveVersionStatus(data, isPending, isError);
Expand Down
49 changes: 0 additions & 49 deletions src/features/header/hooks/use-codegate-status.ts

This file was deleted.

56 changes: 56 additions & 0 deletions src/features/header/hooks/use-queries-codegate-status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { useQueries } from "@tanstack/react-query";

import {
HealthCheckHealthGetResponse,
V1VersionCheckResponse,
} from "@/api/generated";
import { VersionResponse } from "../types";
import { getQueryCacheConfig } from "@/lib/react-query-utils";
import {
healthCheckHealthGetOptions,
v1VersionCheckOptions,
} from "@/api/generated/@tanstack/react-query.gen";
import { QueryResult } from "@/types/react-query";

type UseQueryReturn = [
QueryResult<HealthCheckHealthGetResponse>,
QueryResult<V1VersionCheckResponse>,
];

const combine = (results: UseQueryReturn) => {
const [health, version] = results;

return {
data: {
health: health.data as { status: "healthy" } | null,
version: version.data as VersionResponse | null,
},
isError: results.some((r) => r.isError),
isPending: results.some((r) => r.isPending),
isFetching: results.some((r) => r.isFetching),
isLoading: results.some((r) => r.isLoading),
isRefetching: results.some((r) => r.isRefetching),
};
};

export const useQueriesCodegateStatus = () => {
return useQueries({
combine,
queries: [
{
...healthCheckHealthGetOptions(),
refetchInterval: 60_000,
refetchIntervalInBackground: true,
retry: false,
...getQueryCacheConfig("indefinite"),
},
{
...v1VersionCheckOptions(),
refetchInterval: 60_000,
refetchIntervalInBackground: true,
retry: false,
...getQueryCacheConfig("indefinite"),
},
],
});
};
5 changes: 0 additions & 5 deletions src/features/header/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
export enum HealthStatus {
HEALTHY = "Healthy",
UNHEALTHY = "Unhealthy",
}

export type VersionResponse = {
current_version: string;
latest_version: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { v1ListProviderEndpointsQueryKey } from "@/api/generated/@tanstack/react-query.gen";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
import { invalidateQueries } from "../../../lib/react-query-utils";

export function useInvalidateProvidersQueries() {
const queryClient = useQueryClient();

const invalidate = useCallback(async () => {
await queryClient.invalidateQueries({
queryKey: v1ListProviderEndpointsQueryKey(),
refetchType: "all",
});
invalidateQueries(queryClient, [v1ListProviderEndpointsQueryKey]);
}, [queryClient]);

return invalidate;
Expand Down
3 changes: 0 additions & 3 deletions src/features/providers/hooks/use-providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,5 @@ import { v1ListProviderEndpointsOptions } from "@/api/generated/@tanstack/react-
export function useProviders() {
return useQuery({
...v1ListProviderEndpointsOptions(),
refetchOnMount: true,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { useMutationSetWorkspaceCustomInstructions } from "../hooks/use-mutation
import Fuse from "fuse.js";
import systemPrompts from "../constants/built-in-system-prompts.json";
import { MessageTextSquare02, SearchMd } from "@untitled-ui/icons-react";
import { invalidateQueries } from "@/lib/react-query-utils";

type DarkModeContextValue = {
preference: "dark" | "light" | null;
Expand Down Expand Up @@ -290,12 +291,10 @@ export function WorkspaceCustomInstructions({
mutateAsync(
{ ...options, body: { prompt: value } },
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: v1GetWorkspaceCustomInstructionsQueryKey(options),
refetchType: "all",
});
},
onSuccess: () =>
invalidateQueries(queryClient, [
v1GetWorkspaceCustomInstructionsQueryKey,
]),
},
);
},
Expand Down
3 changes: 2 additions & 1 deletion src/features/workspace/components/workspaces-selection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ export function WorkspacesSelection() {

const handleWorkspaceClick = (name: string) => {
activateWorkspace({ body: { name } }).then(() => {
queryClient.invalidateQueries({ refetchType: "all" });
// eslint-disable-next-line no-restricted-syntax
queryClient.invalidateQueries({ refetchType: "all" }); // Global setting, refetch **everything**
setIsOpen(false);
});
};
Expand Down
3 changes: 0 additions & 3 deletions src/features/workspace/hooks/use-active-workspaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@ export function useActiveWorkspaces<T = ListActiveWorkspacesResponse>({
...v1ListActiveWorkspacesOptions(),
refetchInterval: 5_000,
refetchIntervalInBackground: true,
refetchOnMount: true,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
retry: false,
select,
});
Expand Down
Loading
Loading