Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Parkreiner merged 21 commits intomainfrommes/login-fix
May 3, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
21 commits
Select commitHold shift + click to select a range
4da94ef
fix: remove some of the jank around our core App component
ParkreinerMay 2, 2024
9986024
refactor: scope navigation logic more aggressively
ParkreinerMay 2, 2024
7004c9c
refactor: add explicit return type to useAuthenticated
ParkreinerMay 2, 2024
ebfaec5
refactor: clean up ProxyContext code
ParkreinerMay 2, 2024
1192eb3
wip: add code for consolidating the HTML metadata
ParkreinerMay 2, 2024
bbe2ae0
refactor: clean up hook logic
ParkreinerMay 2, 2024
1c41937
refactor: rename useHtmlMetadata to useEmbeddedMetadata
ParkreinerMay 2, 2024
79e9c45
fix: correct names that weren't updated
ParkreinerMay 2, 2024
81f2cd9
fix: update type-safety of useEmbeddedMetadata further
ParkreinerMay 2, 2024
390418f
wip: switch codebase to use metadata hook
ParkreinerMay 3, 2024
486f292
Merge branch 'main' into mes/login-fix
ParkreinerMay 3, 2024
b77af73
Merge branch 'mes/login-fix' of https://github.com/coder/coder into m…
ParkreinerMay 3, 2024
e072f7a
refactor: simplify design of metadata hook
ParkreinerMay 3, 2024
2a58322
fix: update stray type mismatches
ParkreinerMay 3, 2024
b55abb7
fix: more type fixing
ParkreinerMay 3, 2024
c45e1b7
fix: resolve illegal invocation error
ParkreinerMay 3, 2024
2a63c1d
fix: get metadata issue resolved
ParkreinerMay 3, 2024
4d3b155
fix: update comments
ParkreinerMay 3, 2024
8067e77
chore: add unit tests for MetadataManager
ParkreinerMay 3, 2024
5e6e974
fix: beef up tests
ParkreinerMay 3, 2024
772b96f
fix: update typo in tests
ParkreinerMay 3, 2024
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
26 changes: 20 additions & 6 deletionssite/src/App.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -38,9 +38,23 @@ export const AppProviders: FC<AppProvidersProps> = ({
}) => {
// https://tanstack.com/query/v4/docs/react/devtools
const [showDevtools, setShowDevtools] = useState(false);

useEffect(() => {
window.toggleDevtools = () => setShowDevtools((old) => !old);
// eslint-disable-next-line react-hooks/exhaustive-deps -- no dependencies needed here
// Storing key in variable to avoid accidental typos; we're working with the
// window object, so there's basically zero type-checking available
const toggleKey = "toggleDevtools";

// Don't want to throw away the previous devtools value if some other
// extension added something already
const devtoolsBeforeSync = window[toggleKey];
window[toggleKey] = () => {
devtoolsBeforeSync?.();
setShowDevtools((current) => !current);
};

return () => {
window[toggleKey] = devtoolsBeforeSync;
};
}, []);

return (
Expand All@@ -60,10 +74,10 @@ export const AppProviders: FC<AppProvidersProps> = ({

export const App: FC = () => {
return (
<AppProviders>
<ErrorBoundary>
<ErrorBoundary>
<AppProviders>
<RouterProvider router={router} />
</ErrorBoundary>
</AppProviders>
</AppProviders>
</ErrorBoundary>
Comment on lines +77 to +81
Copy link
MemberAuthor

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 inAppProviders threw an error, we had nothing to catch it. MovedErrorBoundary to be the top-most component

);
};
10 changes: 4 additions & 6 deletionssite/src/api/queries/appearance.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
import type { QueryClient, UseQueryOptions } from "react-query";
import type { QueryClient } from "react-query";
import * as API from "api/api";
import type { AppearanceConfig } from "api/typesGenerated";
import{ getMetadataAsJSON } from "utils/metadata";
importtype { MetadataState } from "hooks/useEmbeddedMetadata";
import { cachedQuery } from "./util";

const initialAppearanceData = getMetadataAsJSON<AppearanceConfig>("appearance");
const appearanceConfigKey = ["appearance"] as const;

export const appearance = (): UseQueryOptions<AppearanceConfig> => {
// We either have our initial data or should immediately fetch and never again!
export const appearance = (metadata: MetadataState<AppearanceConfig>) => {
return cachedQuery({
initialData: initialAppearanceData,
metadata,
queryKey: ["appearance"],
queryFn: () => API.getAppearance(),
});
Expand Down
8 changes: 3 additions & 5 deletionssite/src/api/queries/buildInfo.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
import type { UseQueryOptions } from "react-query";
import * as API from "api/api";
import type { BuildInfoResponse } from "api/typesGenerated";
import{ getMetadataAsJSON } from "utils/metadata";
importtype { MetadataState } from "hooks/useEmbeddedMetadata";
import { cachedQuery } from "./util";

const initialBuildInfoData = getMetadataAsJSON<BuildInfoResponse>("build-info");
const buildInfoKey = ["buildInfo"] as const;

export const buildInfo = (): UseQueryOptions<BuildInfoResponse> => {
export const buildInfo = (metadata: MetadataState<BuildInfoResponse>) => {
// The version of the app can't change without reloading the page.
return cachedQuery({
initialData: initialBuildInfoData,
metadata,
queryKey: buildInfoKey,
queryFn: () => API.getBuildInfo(),
});
Expand Down
9 changes: 4 additions & 5 deletionssite/src/api/queries/entitlements.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
import type { QueryClient, UseQueryOptions } from "react-query";
import type { QueryClient } from "react-query";
import * as API from "api/api";
import type { Entitlements } from "api/typesGenerated";
import{ getMetadataAsJSON } from "utils/metadata";
importtype { MetadataState } from "hooks/useEmbeddedMetadata";
import { cachedQuery } from "./util";

const initialEntitlementsData = getMetadataAsJSON<Entitlements>("entitlements");
const entitlementsQueryKey = ["entitlements"] as const;

export const entitlements = (): UseQueryOptions<Entitlements> => {
export const entitlements = (metadata: MetadataState<Entitlements>) => {
return cachedQuery({
initialData: initialEntitlementsData,
metadata,
queryKey: entitlementsQueryKey,
queryFn: () => API.getEntitlements(),
});
Expand Down
8 changes: 3 additions & 5 deletionssite/src/api/queries/experiments.ts
View file
Open in desktop
Original file line numberDiff line numberDiff 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";
importtype { 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>) => {
Copy link
MemberAuthor

@ParkreinerParkreinerMay 3, 2024
edited
Loading

Choose a reason for hiding this comment

The 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(),
});
Expand Down
35 changes: 24 additions & 11 deletionssite/src/api/queries/users.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
import type {
QueryClient,
QueryKey,
UseMutationOptions,
UseQueryOptions,
} from "react-query";
Expand All@@ -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";

Expand DownExpand Up@@ -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
Expand All@@ -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,
});
Expand All@@ -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,
});
Expand DownExpand Up@@ -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
Copy link
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

This is the main part of the fix

queryClient.removeQueries();
},
};
Expand Down
85 changes: 66 additions & 19 deletionssite/src/api/queries/util.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,74 @@
importtype{UseQueryOptions}from"react-query";
importtype{UseQueryOptions,QueryKey}from"react-query";
importtype{MetadataState,MetadataValue}from"hooks/useEmbeddedMetadata";

constdisabledFetchOptions={
cacheTime:Infinity,
staleTime:Infinity,
refetchOnMount:false,
refetchOnReconnect:false,
refetchOnWindowFocus:false,
}asconstsatisfiesUseQueryOptions;

typeUseQueryOptionsWithMetadata<
TMetadataextendsMetadataValue=MetadataValue,
TQueryFnData=unknown,
TError=unknown,
TData=TQueryFnData,
TQueryKeyextendsQueryKey=QueryKey,
>=Omit<
UseQueryOptions<TQueryFnData,TError,TData,TQueryKey>,
"initialData"
>&{
metadata:MetadataState<TMetadata>;
};

typeFormattedQueryOptionsResult<
TQueryFnData=unknown,
TError=unknown,
TData=TQueryFnData,
TQueryKeyextendsQueryKey=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.
*/
exportconstcachedQuery=<
TQueryOptionsextendsUseQueryOptions<TData>,
TData,
exportfunctioncachedQuery<
TMetadataextendsMetadataValue=MetadataValue,
TQueryFnData=unknown,
TError=unknown,
TData=TQueryFnData,
TQueryKeyextendsQueryKey=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;
constnewOptions={
...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 :{}),
};

returnnewOptionsasFormattedQueryOptionsResult<
TQueryFnData,
TError,
TData,
TQueryKey
>;
}
44 changes: 11 additions & 33 deletionssite/src/contexts/ProxyContext.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -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 {
Expand DownExpand Up@@ -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
Copy link
MemberAuthor

Choose a reason for hiding this comment

The 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

Copy link
Member

@EmyrkEmyrkMay 3, 2024
edited
Loading

Choose a reason for hiding this comment

The 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,
Expand All@@ -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
Copy link
MemberAuthor

Choose a reason for hiding this comment

The 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

}),
);

Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp