Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
4da94ef
fix: remove some of the jank around our core App component
Parkreiner May 2, 2024
9986024
refactor: scope navigation logic more aggressively
Parkreiner May 2, 2024
7004c9c
refactor: add explicit return type to useAuthenticated
Parkreiner May 2, 2024
ebfaec5
refactor: clean up ProxyContext code
Parkreiner May 2, 2024
1192eb3
wip: add code for consolidating the HTML metadata
Parkreiner May 2, 2024
bbe2ae0
refactor: clean up hook logic
Parkreiner May 2, 2024
1c41937
refactor: rename useHtmlMetadata to useEmbeddedMetadata
Parkreiner May 2, 2024
79e9c45
fix: correct names that weren't updated
Parkreiner May 2, 2024
81f2cd9
fix: update type-safety of useEmbeddedMetadata further
Parkreiner May 2, 2024
390418f
wip: switch codebase to use metadata hook
Parkreiner May 3, 2024
486f292
Merge branch 'main' into mes/login-fix
Parkreiner May 3, 2024
b77af73
Merge branch 'mes/login-fix' of https://github.com/coder/coder into m…
Parkreiner May 3, 2024
e072f7a
refactor: simplify design of metadata hook
Parkreiner May 3, 2024
2a58322
fix: update stray type mismatches
Parkreiner May 3, 2024
b55abb7
fix: more type fixing
Parkreiner May 3, 2024
c45e1b7
fix: resolve illegal invocation error
Parkreiner May 3, 2024
2a63c1d
fix: get metadata issue resolved
Parkreiner May 3, 2024
4d3b155
fix: update comments
Parkreiner May 3, 2024
8067e77
chore: add unit tests for MetadataManager
Parkreiner May 3, 2024
5e6e974
fix: beef up tests
Parkreiner May 3, 2024
772b96f
fix: update typo in tests
Parkreiner May 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
44 changes: 11 additions & 33 deletions site/src/contexts/ProxyContext.tsx
Original file line number Diff line number Diff 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 Down Expand 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
Member Author

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

@Emyrk Emyrk May 3, 2024

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
Member Author

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
20 changes: 11 additions & 9 deletions site/src/contexts/auth/RequireAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import { embedRedirect } from "utils/redirect";
import { type AuthContextValue, useAuthContext } from "./AuthProvider";

export const RequireAuth: FC = () => {
const location = useLocation();
const { signOut, isSigningOut, isSignedOut, isSignedIn, isLoading } =
useAuthContext();
const location = useLocation();

useEffect(() => {
if (isLoading || isSigningOut || !isSignedIn) {
Expand Down Expand Up @@ -65,7 +65,15 @@ export const RequireAuth: FC = () => {
);
};

export const useAuthenticated = () => {
// We can do some TS magic here but I would rather to be explicit on what
// values are not undefined when authenticated
type NonNullableAuth = AuthContextValue & {
user: Exclude<AuthContextValue["user"], undefined>;
permissions: Exclude<AuthContextValue["permissions"], undefined>;
organizationId: Exclude<AuthContextValue["organizationId"], undefined>;
};

export const useAuthenticated = (): NonNullableAuth => {
const auth = useAuthContext();

if (!auth.user) {
Expand All @@ -76,11 +84,5 @@ export const useAuthenticated = () => {
throw new Error("Permissions are not available.");
}

// We can do some TS magic here but I would rather to be explicit on what
// values are not undefined when authenticated
return auth as AuthContextValue & {
user: Exclude<AuthContextValue["user"], undefined>;
permissions: Exclude<AuthContextValue["permissions"], undefined>;
organizationId: Exclude<AuthContextValue["organizationId"], undefined>;
};
return auth as NonNullableAuth;
};
41 changes: 39 additions & 2 deletions site/src/hooks/useEmbeddedMetadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
BuildInfoResponse,
Entitlements,
Experiments,
Region,
User,
} from "api/typesGenerated";

Expand All @@ -22,6 +23,7 @@ type AvailableMetadata = Readonly<{
experiments: Experiments;
appearance: AppearanceConfig;
entitlements: Entitlements;
regions: readonly Region[];
"build-info": BuildInfoResponse;
}>;

Expand All @@ -42,7 +44,7 @@ export type RuntimeHtmlMetadata = Readonly<{
type SubscriptionCallback = (metadata: RuntimeHtmlMetadata) => void;
type QuerySelector = typeof document.querySelector;

type ParseJsonResult<T extends MetadataValue> = Readonly<
type ParseJsonResult<T = unknown> = Readonly<
| {
value: T;
node: Element;
Expand Down Expand Up @@ -76,6 +78,7 @@ export class MetadataManager implements MetadataManagerApi {
entitlements: this.registerValue<Entitlements>("entitlements"),
experiments: this.registerValue<Experiments>("experiments"),
"build-info": this.registerValue<BuildInfoResponse>("build-info"),
regions: this.registerRegionValue("region"),
};
}

Expand All @@ -84,6 +87,40 @@ export class MetadataManager implements MetadataManagerApi {
this.subscriptions.forEach((cb) => cb(metadataBinding));
}

/**
* This is a band-aid solution for code that was specific to the Region
* type.
*
* Ideally the code should be updated on the backend to ensure that the
* response is one consistent type, and then this method should be removed
* entirely.
*
* Removing this method would also ensure that the other types in this file
* can be tightened up even further (e.g., adding a type constraint to
* parseJson)
*/
private registerRegionValue(key: "region"): MetadataState<readonly Region[]> {
type RegionResponse =
| readonly Region[]
| Readonly<{
regions: readonly Region[];
}>;

const { value, node } = this.parseJson<RegionResponse>("regions");

let newEntry: MetadataState<readonly Region[]>;
if (!node || value === undefined) {
newEntry = { value: undefined, status: "missing" };
} else if ("regions" in value) {
newEntry = { value: value.regions, status: "loaded" };
} else {
newEntry = { value, status: "loaded" };
}

this.trackedMetadataNodes.set(key, node);
return newEntry;
}

private registerValue<T extends MetadataValue>(
key: MetadataKey,
): MetadataState<T> {
Expand All @@ -100,7 +137,7 @@ export class MetadataManager implements MetadataManagerApi {
return newEntry;
}

private parseJson<T extends MetadataValue>(key: string): ParseJsonResult<T> {
private parseJson<T = unknown>(key: string): ParseJsonResult<T> {
const node = this.querySelector(`meta[property=${key}]`);
if (!node) {
return { value: undefined, node: null };
Expand Down