-
Notifications
You must be signed in to change notification settings - Fork 936
fix: ensure signing out cannot cause any runtime render errors #13137
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
Changes from 19 commits
4da94ef
9986024
7004c9c
ebfaec5
1192eb3
bbe2ae0
1c41937
79e9c45
81f2cd9
390418f
486f292
b77af73
e072f7a
2a58322
b55abb7
c45e1b7
2a63c1d
4d3b155
8067e77
5e6e974
772b96f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,13 @@ | ||
import type { UseQueryOptions } from "react-query"; | ||
import * as API from "api/api"; | ||
import type { Experiments } from "api/typesGenerated"; | ||
import { getMetadataAsJSON } from "utils/metadata"; | ||
import type { MetadataState } from "hooks/useEmbeddedMetadata"; | ||
import { cachedQuery } from "./util"; | ||
|
||
const initialExperimentsData = getMetadataAsJSON<Experiments>("experiments"); | ||
const experimentsKey = ["experiments"] as const; | ||
|
||
export const experiments = (): UseQueryOptions<Experiments> => { | ||
export const experiments = (metadata: MetadataState<Experiments>) => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I do want to go back and add explicit return types, but I was on a tight deadline, and didn't have time to figure it out These functions are still type-safe and will let you know if you wire things wrong. They're just not "add explicit type parameter"-safe, because of TypeScript type parameter shenanigans |
||
return cachedQuery({ | ||
initialData: initialExperimentsData, | ||
metadata, | ||
queryKey: experimentsKey, | ||
queryFn: () => API.getExperiments(), | ||
}); | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,5 @@ | ||
import type { | ||
QueryClient, | ||
QueryKey, | ||
UseMutationOptions, | ||
UseQueryOptions, | ||
} from "react-query"; | ||
|
@@ -15,9 +14,12 @@ import type { | |
User, | ||
GenerateAPIKeyResponse, | ||
} from "api/typesGenerated"; | ||
import { | ||
defaultMetadataManager, | ||
type MetadataState, | ||
} from "hooks/useEmbeddedMetadata"; | ||
import type { UsePaginatedQueryOptions } from "hooks/usePaginatedQuery"; | ||
import { prepareQuery } from "utils/filters"; | ||
import { getMetadataAsJSON } from "utils/metadata"; | ||
import { getAuthorizationKey } from "./authCheck"; | ||
import { cachedQuery } from "./util"; | ||
|
||
|
@@ -113,8 +115,6 @@ export const updateRoles = (queryClient: QueryClient) => { | |
}; | ||
}; | ||
|
||
const initialUserData = getMetadataAsJSON<User>("user"); | ||
|
||
export const authMethods = () => { | ||
return { | ||
// Even the endpoint being /users/authmethods we don't want to revalidate it | ||
|
@@ -126,11 +126,9 @@ export const authMethods = () => { | |
|
||
const meKey = ["me"]; | ||
|
||
export const me = (): UseQueryOptions<User> & { | ||
queryKey: QueryKey; | ||
} => { | ||
export const me = (metadata: MetadataState<User>) => { | ||
return cachedQuery({ | ||
initialData: initialUserData, | ||
metadata, | ||
queryKey: meKey, | ||
queryFn: API.getAuthenticatedUser, | ||
}); | ||
|
@@ -143,10 +141,9 @@ export function apiKey(): UseQueryOptions<GenerateAPIKeyResponse> { | |
}; | ||
} | ||
|
||
export const hasFirstUser = (): UseQueryOptions<boolean> => { | ||
export const hasFirstUser = (userMetadata: MetadataState<User>) => { | ||
return cachedQuery({ | ||
// This cannot be false otherwise it will not fetch! | ||
initialData: Boolean(initialUserData) || undefined, | ||
metadata: userMetadata, | ||
queryKey: ["hasFirstUser"], | ||
queryFn: API.hasFirstUser, | ||
}); | ||
|
@@ -193,6 +190,22 @@ export const logout = (queryClient: QueryClient) => { | |
return { | ||
mutationFn: API.logout, | ||
onSuccess: () => { | ||
/** | ||
* 2024-05-02 - If we persist any form of user data after the user logs | ||
* out, that will continue to seed the React Query cache, creating | ||
* "impossible" states where we'll have data we're not supposed to have. | ||
* | ||
* This has caused issues where logging out will instantly throw a | ||
* completely uncaught runtime rendering error. Worse yet, the error only | ||
* exists when serving the site from the Go backend (the JS environment | ||
* has zero issues because it doesn't have access to the metadata). These | ||
* errors can only be caught with E2E tests. | ||
* | ||
* Deleting the user data will mean that all future requests have to take | ||
* a full roundtrip, but this still felt like the best way to ensure that | ||
* manually logging out doesn't blow the entire app up. | ||
*/ | ||
defaultMetadataManager.clearMetadataByKey("user"); | ||
Comment on lines
+193
to
+208
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is the main part of the fix |
||
queryClient.removeQueries(); | ||
}, | ||
}; | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,74 @@ | ||
import type { UseQueryOptions } from "react-query"; | ||
import type { UseQueryOptions, QueryKey } from "react-query"; | ||
import type { MetadataState, MetadataValue } from "hooks/useEmbeddedMetadata"; | ||
|
||
const disabledFetchOptions = { | ||
cacheTime: Infinity, | ||
staleTime: Infinity, | ||
refetchOnMount: false, | ||
refetchOnReconnect: false, | ||
refetchOnWindowFocus: false, | ||
} as const satisfies UseQueryOptions; | ||
|
||
type UseQueryOptionsWithMetadata< | ||
TMetadata extends MetadataValue = MetadataValue, | ||
TQueryFnData = unknown, | ||
TError = unknown, | ||
TData = TQueryFnData, | ||
TQueryKey extends QueryKey = QueryKey, | ||
> = Omit< | ||
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, | ||
"initialData" | ||
> & { | ||
metadata: MetadataState<TMetadata>; | ||
}; | ||
|
||
type FormattedQueryOptionsResult< | ||
TQueryFnData = unknown, | ||
TError = unknown, | ||
TData = TQueryFnData, | ||
TQueryKey extends QueryKey = QueryKey, | ||
> = Omit< | ||
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, | ||
"initialData" | ||
> & { | ||
queryKey: NonNullable<TQueryKey>; | ||
}; | ||
|
||
/** | ||
* cachedQuery allows the caller to only make a request a single time, and use | ||
* `initialData` if it is provided. This is particularly helpful for passing | ||
* values injected via metadata. We do this for the initial user fetch, | ||
* buildinfo, and a few others to reduce page load time. | ||
*/ | ||
export const cachedQuery = < | ||
TQueryOptions extends UseQueryOptions<TData>, | ||
TData, | ||
export function cachedQuery< | ||
TMetadata extends MetadataValue = MetadataValue, | ||
TQueryFnData = unknown, | ||
TError = unknown, | ||
TData = TQueryFnData, | ||
TQueryKey extends QueryKey = QueryKey, | ||
>( | ||
options: TQueryOptions, | ||
): TQueryOptions => | ||
// Only do this if there is initial data, otherwise it can conflict with tests. | ||
({ | ||
...(options.initialData | ||
? { | ||
cacheTime: Infinity, | ||
staleTime: Infinity, | ||
refetchOnMount: false, | ||
refetchOnReconnect: false, | ||
refetchOnWindowFocus: false, | ||
} | ||
: {}), | ||
...options, | ||
}); | ||
options: UseQueryOptionsWithMetadata< | ||
TMetadata, | ||
TQueryFnData, | ||
TError, | ||
TData, | ||
TQueryKey | ||
>, | ||
): FormattedQueryOptionsResult<TQueryFnData, TError, TData, TQueryKey> { | ||
const { metadata, ...delegatedOptions } = options; | ||
const newOptions = { | ||
...delegatedOptions, | ||
initialData: metadata.available ? metadata.value : undefined, | ||
|
||
// Make sure the disabled options are always serialized last, so that no | ||
// one using this function can accidentally override the values | ||
...(metadata.available ? disabledFetchOptions : {}), | ||
}; | ||
|
||
return newOptions as FormattedQueryOptionsResult< | ||
TQueryFnData, | ||
TError, | ||
TData, | ||
TQueryKey | ||
>; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,6 +12,7 @@ import { getWorkspaceProxies, getWorkspaceProxyRegions } from "api/api"; | |
import { cachedQuery } from "api/queries/util"; | ||
import type { Region, WorkspaceProxy } from "api/typesGenerated"; | ||
import { useAuthenticated } from "contexts/auth/RequireAuth"; | ||
import { useEmbeddedMetadata } from "hooks/useEmbeddedMetadata"; | ||
import { type ProxyLatencyReport, useProxyLatency } from "./useProxyLatency"; | ||
|
||
export interface ProxyContextValue { | ||
|
@@ -94,37 +95,8 @@ export const ProxyProvider: FC<PropsWithChildren> = ({ children }) => { | |
computeUsableURLS(userSavedProxy), | ||
); | ||
|
||
const queryKey = ["get-proxies"]; | ||
// This doesn't seem like an idiomatic way to get react-query to use the | ||
// initial data without performing an API request on mount, but it works. | ||
// | ||
// If anyone would like to clean this up in the future, it should seed data | ||
// from the `meta` tag if it exists, and not fetch the regions route. | ||
const [initialData] = useState(() => { | ||
// Build info is injected by the Coder server into the HTML document. | ||
const regions = document.querySelector("meta[property=regions]"); | ||
if (regions) { | ||
const rawContent = regions.getAttribute("content"); | ||
try { | ||
const obj = JSON.parse(rawContent as string); | ||
if ("regions" in obj) { | ||
return obj.regions as Region[]; | ||
} | ||
return obj as Region[]; | ||
Comment on lines
-109
to
-113
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @Emyrk I wasn't completely sure why we had a check for whether the data getting parsed was either an array or an object with the array inside it, but just to be on the safe side, I ripped this out and centralized it in the metadata manager file There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great question. The type safety we have on these fields is terrible, and should be resolved imo to make things like this more clear. We just inject strings that are json. Very weak imo. I'll dig a bit and find out |
||
} catch (ex) { | ||
// Ignore this and fetch as normal! | ||
} | ||
} | ||
}); | ||
|
||
const { permissions } = useAuthenticated(); | ||
const query = async (): Promise<readonly Region[]> => { | ||
const endpoint = permissions.editWorkspaceProxies | ||
? getWorkspaceProxies | ||
: getWorkspaceProxyRegions; | ||
const resp = await endpoint(); | ||
return resp.regions; | ||
}; | ||
const { metadata } = useEmbeddedMetadata(); | ||
|
||
const { | ||
data: proxiesResp, | ||
|
@@ -133,9 +105,15 @@ export const ProxyProvider: FC<PropsWithChildren> = ({ children }) => { | |
isFetched: proxiesFetched, | ||
} = useQuery( | ||
cachedQuery({ | ||
initialData, | ||
queryKey, | ||
queryFn: query, | ||
metadata: metadata.regions, | ||
queryKey: ["get-proxies"], | ||
queryFn: async (): Promise<readonly Region[]> => { | ||
const endpoint = permissions.editWorkspaceProxies | ||
? getWorkspaceProxies | ||
: getWorkspaceProxyRegions; | ||
const resp = await endpoint(); | ||
return resp.regions; | ||
}, | ||
Comment on lines
+108
to
+116
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just inlined a bunch of the values, since they're only used here |
||
}), | ||
); | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Important – before, if any of the sub-components in
AppProviders
threw an error, we had nothing to catch it. MovedErrorBoundary
to be the top-most component