Skip to content

Commit

Permalink
refactor: call bootstrap before running the app
Browse files Browse the repository at this point in the history
  • Loading branch information
jog1t committed Nov 20, 2024
1 parent 7c7bd5a commit de1eb12
Show file tree
Hide file tree
Showing 15 changed files with 171 additions and 52 deletions.
4 changes: 2 additions & 2 deletions apps/hub/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ function InnerApp() {
return <RouterProvider router={router} context={{ auth }} />;
}

export function App() {
export function App({ cacheKey }: { cacheKey?: string }) {
return (
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister: queryClientPersister }}
persistOptions={{ persister: queryClientPersister, buster: cacheKey }}
>
<ConfigProvider value={getConfig()}>
<ThirdPartyProviders>
Expand Down
3 changes: 1 addition & 2 deletions apps/hub/src/domains/auth/queries/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ export const bootstrapQueryOptions = () => {
export const bootstrapOpenGbQueryOptions = () => {
return queryOptions({
...bootstrapQueryOptions(),
select: (data) =>
data.domains?.opengb || data.domains?.main || window.location.host,
select: (data) => data.domains?.opengb || window.location.host,
});
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dataCentersQueryOptions } from "@/domains/project/queries";
import { regionsQueryOptions } from "@/domains/project/queries";
import {
Flex,
Select,
Expand All @@ -22,7 +22,7 @@ export function ServerDatacenterSelect({
...props
}: ServerDatacenterSelectProps) {
const { data } = useSuspenseQuery(
dataCentersQueryOptions({ projectId, environmentId }),
regionsQueryOptions({ projectId, environmentId }),
);

return (
Expand All @@ -38,7 +38,7 @@ export function ServerDatacenterSelect({
showLabel
projectId={projectId}
environmentId={environmentId}
datacenterId={datacenter.id}
regionId={datacenter.id}
/>
</Flex>
</SelectItem>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
import { AssetImage, Flex, WithTooltip } from "@rivet-gg/components";
import { useSuspenseQuery } from "@tanstack/react-query";
import { dataCenterQueryOptions } from "../../queries";
import { regionQueryOptions } from "../../queries";
import {
REGION_LABEL,
getRegionEmoji,
getRegionKey,
} from "../matchmaker/lobby-region";

interface ServerDatacenterProps {
datacenterId: string;
regionId: string;
projectId: string;
environmentId: string;
showLabel?: boolean | "abbreviated";
}

export function ServerDatacenter({
projectId,
datacenterId,
regionId,
environmentId,
showLabel,
}: ServerDatacenterProps) {
const { data: region } = useSuspenseQuery(
dataCenterQueryOptions({ projectId, environmentId, datacenterId }),
regionQueryOptions({ projectId, environmentId, regionId }),
);

const regionKey = getRegionKey(region?.slug);
const regionKey = getRegionKey(region?.name);

if (showLabel) {
return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ function ServerRow({
showLabel="abbreviated"
projectId={projectId}
environmentId={environmentId}
datacenterId={server.datacenter}
regionId={server.datacenter}
/>
</SmallText>
<SmallText>{server.id.split("-")[0]}</SmallText>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export function ServersServerDetails({
showLabel="abbreviated"
projectId={projectId}
environmentId={environmentId}
datacenterId={data.datacenter}
regionId={data.datacenter}
/>
</SmallText>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export const serverLogsQueryOptions = (
meta,
queryKey: [_, projectId, __, environmentId, ___, serverId, ____, stream],
}) =>
rivetClient.servers.logs.getServerLogs(
rivetClient.servers.logs.get(
projectId,
environmentId,
serverId,
Expand Down Expand Up @@ -159,7 +159,7 @@ export const projectBuildsQueryOptions = ({
],
signal: abortSignal,
}) =>
rivetClient.servers.builds.listBuilds(projectId, environmentId, tags, {
rivetClient.servers.builds.list(projectId, environmentId, tags, {
abortSignal,
}),
select: (data) => data.builds,
Expand Down Expand Up @@ -188,7 +188,7 @@ export const buildQueryOptions = ({
signal: abortSignal,
queryKey: [_, projectId, __, environmentId, ___, buildId],
}) =>
rivetClient.servers.builds.getBuild(
rivetClient.servers.builds.get(
projectId,
environmentId,
buildId,
Expand All @@ -202,47 +202,43 @@ export const buildQueryOptions = ({
});
};

export const dataCentersQueryOptions = ({
export const regionsQueryOptions = ({
projectId,
environmentId,
}: { projectId: string; environmentId: string }) => {
return queryOptions({
queryKey: [
"project",
projectId,
"environment",
environmentId,
"datacenters",
],
queryKey: ["project", projectId, "environment", environmentId, "regions"],
queryFn: ({
signal: abortSignal,
queryKey: [_, projectId, __, environmentId],
}) =>
rivetClient.servers.datacenters.listDatacenters(
projectId,
environmentId,
rivetClient.actor.regions.list(
{
project: projectId,
environment: environmentId,
},
{
abortSignal,
},
),
select: (data) => data.datacenters,
select: (data) => data.regions,
});
};

export const dataCenterQueryOptions = ({
export const regionQueryOptions = ({
projectId,
environmentId,
datacenterId,
regionId,
}: {
projectId: string;
environmentId: string;
datacenterId: string;
regionId: string;
}) => {
return queryOptions({
...dataCentersQueryOptions({ projectId, environmentId }),
...regionsQueryOptions({ projectId, environmentId }),
select: (data) =>
dataCentersQueryOptions({ projectId, environmentId })
regionsQueryOptions({ projectId, environmentId })
.select?.(data)
.find((datacenter) => datacenter.id === datacenterId),
.find((region) => region.id === regionId),
});
};
7 changes: 7 additions & 0 deletions apps/hub/src/hooks/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Adapted from: https://github.com/streamich/react-use/blob/e1d0cd9f7fb2a124a9d46879489abfefdf48d836/src/misc/types.ts

export type PromiseType<P extends Promise<unknown>> = P extends Promise<infer T>
? T
: never;
// biome-ignore lint/suspicious/noExplicitAny: this is a type that is used to represent a function that returns a promise
export type FunctionReturningPromise = (...args: any[]) => Promise<any>;
72 changes: 72 additions & 0 deletions apps/hub/src/hooks/use-async-fn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Adapted from https://github.com/streamich/react-use/blob/e1d0cd9f7fb2a124a9d46879489abfefdf48d836/src/useAsyncFn.ts
import { type DependencyList, useCallback, useRef, useState } from "react";
import type { FunctionReturningPromise, PromiseType } from "./types";
import useMountedState from "./use-mounted-state";

export type AsyncState<T> =
| {
loading: boolean;
error?: undefined;
value?: undefined;
}
| {
loading: true;
error?: Error | undefined;
value?: T;
}
| {
loading: false;
error: Error;
value?: undefined;
}
| {
loading: false;
error?: undefined;
value: T;
};

type StateFromFunctionReturningPromise<T extends FunctionReturningPromise> =
AsyncState<PromiseType<ReturnType<T>>>;

export type AsyncFnReturn<
T extends FunctionReturningPromise = FunctionReturningPromise,
> = [StateFromFunctionReturningPromise<T>, T];

export function useAsyncFn<T extends FunctionReturningPromise>(
fn: T,
deps: DependencyList = [],
initialState: StateFromFunctionReturningPromise<T> = { loading: false },
): AsyncFnReturn<T> {
const lastCallId = useRef(0);
const isMounted = useMountedState();
const [state, set] =
useState<StateFromFunctionReturningPromise<T>>(initialState);

// biome-ignore lint/correctness/useExhaustiveDependencies: we don't want to re-run this effect when `fn` changes
const callback = useCallback((...args: Parameters<T>): ReturnType<T> => {
const callId = ++lastCallId.current;

if (!state.loading) {
set((prevState) => ({ ...prevState, loading: true }));
}

return fn(...args).then(
(value) => {
isMounted() &&
callId === lastCallId.current &&
set({ value, loading: false });

return value;
},
(error) => {
isMounted() &&
callId === lastCallId.current &&
set({ error, loading: false });

return error;
},
) as ReturnType<T>;
}, deps);

return [state, callback as unknown as T];
}
21 changes: 21 additions & 0 deletions apps/hub/src/hooks/use-async.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Adapted from: https://github.com/streamich/react-use/blob/e1d0cd9f7fb2a124a9d46879489abfefdf48d836/src/useAsync.ts
import { type DependencyList, useEffect } from "react";
import type { FunctionReturningPromise } from "./types";
import { useAsyncFn } from "./use-async-fn";

export { type AsyncState, type AsyncFnReturn } from "./use-async-fn";

Check failure on line 6 in apps/hub/src/hooks/use-async.ts

View workflow job for this annotation

GitHub Actions / quality

lint/style/useExportType

All exports are only types.

Check failure on line 6 in apps/hub/src/hooks/use-async.ts

View workflow job for this annotation

GitHub Actions / quality

lint/style/useExportType

All exports are only types.

export function useAsync<T extends FunctionReturningPromise>(
fn: T,
deps: DependencyList = [],
) {
const [state, callback] = useAsyncFn(fn, deps, {
loading: true,
});

useEffect(() => {
callback();
}, [callback]);

return state;
}
17 changes: 17 additions & 0 deletions apps/hub/src/hooks/use-mounted-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Adapted from: https://github.com/streamich/react-use/blob/e1d0cd9f7fb2a124a9d46879489abfefdf48d836/src/useMountedState.ts
import { useCallback, useEffect, useRef } from "react";

export default function useMountedState(): () => boolean {
const mountedRef = useRef<boolean>(false);
const get = useCallback(() => mountedRef.current, []);

useEffect(() => {
mountedRef.current = true;

return () => {
mountedRef.current = false;
};
}, []);

return get;
}
31 changes: 22 additions & 9 deletions apps/hub/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,29 @@ import ReactDOM from "react-dom/client";
import { App } from "./app";
import "./index.css";
import { initThirdPartyProviders } from "./components/third-party-providers";
import { rivetClient } from "./queries/global";

initThirdPartyProviders();

// biome-ignore lint/style/noNonNullAssertion: it should always be present
const rootElement = document.getElementById("root")!;
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement);
root.render(
<StrictMode>
<App />
</StrictMode>,
);
rivetClient.cloud
.bootstrap()
.then((response) => {
console.log(response);
run({ cacheKey: response.deployHash });
})
.catch(() => {
run();
});

function run({ cacheKey }: { cacheKey?: string } = {}) {
// biome-ignore lint/style/noNonNullAssertion: it should always be present
const rootElement = document.getElementById("root")!;
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement);
root.render(
<StrictMode>
<App cacheKey={cacheKey} />
</StrictMode>,
);
}
}
6 changes: 0 additions & 6 deletions apps/hub/src/routes/_authenticated/access-token.$token.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as Layout from "@/layouts/page-centered";
import { rivetClient } from "@/queries/global";
import {
Button,
Card,
Expand Down Expand Up @@ -35,9 +34,4 @@ function InviteCodeInviteRoute() {

export const Route = createFileRoute("/_authenticated/access-token/$token")({
component: InviteCodeInviteRoute,
loader: async ({ params: { token } }) => {
await rivetClient.auth.identity.accessToken.completeAccessTokenVerification(
{ accessToken: token },
);
},
});
Binary file modified apps/hub/vendor/rivet-gg-api.tgz
Binary file not shown.
4 changes: 2 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4381,14 +4381,14 @@ __metadata:

"@rivet-gg/api@file:vendor/rivet-gg-api.tgz::locator=%40rivet-gg%2Fhub%40workspace%3Aapps%2Fhub":
version: 24.1.0
resolution: "@rivet-gg/api@file:vendor/rivet-gg-api.tgz#vendor/rivet-gg-api.tgz::hash=f84e6f&locator=%40rivet-gg%2Fhub%40workspace%3Aapps%2Fhub"
resolution: "@rivet-gg/api@file:vendor/rivet-gg-api.tgz#vendor/rivet-gg-api.tgz::hash=d68df2&locator=%40rivet-gg%2Fhub%40workspace%3Aapps%2Fhub"
dependencies:
form-data: "npm:^4.0.0"
js-base64: "npm:^3.7.5"
node-fetch: "npm:2"
qs: "npm:^6.11.2"
url-join: "npm:^5.0.0"
checksum: 10c0/b13044402f475548f8dba4e0e8eeceb31056ba89137608c35a9d02ff202f323f6e6246e16779c9a380c3876b21a70435ee9d91710246bfe972ef527e2891e648
checksum: 10c0/13e5b7e2e4211b9cfe3fc07d66385bd33bc97e43c19d6fa636ef9d76dbd365d716ae15c93d6a0011519f3bb8771c9d402d4950774d77229350a111a8c5cd02ca
languageName: node
linkType: hard

Expand Down

0 comments on commit de1eb12

Please sign in to comment.