Skip to content

Commit

Permalink
updated cluster status hook
Browse files Browse the repository at this point in the history
  • Loading branch information
tulsiojha committed Aug 28, 2024
1 parent 156d9e7 commit 37aa2eb
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 48 deletions.
82 changes: 82 additions & 0 deletions src/apps/console/hooks/use-cluster-status-v2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import {
Dispatch,
ReactNode,
SetStateAction,
createContext,
useCallback,
useContext,
useMemo,
useState,
} from 'react';
import { ExtractNodeType, parseNodes } from '../server/r-utils/common';
import { IByocClusters } from '../server/gql/queries/byok-cluster-queries';
import { useParams } from '@remix-run/react';
import { useSocketWatch } from '~/root/lib/client/helpers/socket/useWatch';
import { useConsoleApi } from '../server/gql/api-provider';
import useDebounce from '~/root/lib/client/hooks/use-debounce';

type IClusterMap = { [key: string]: ExtractNodeType<IByocClusters> };

const ClusterStatusContext = createContext<{
clusters: IClusterMap;
setClusters: Dispatch<SetStateAction<IClusterMap>>;
}>({ clusters: {}, setClusters: () => {} });

const ClusterStatusProvider = ({ children }: { children: ReactNode }) => {
const [clusters, setClusters] = useState<IClusterMap>({});
const api = useConsoleApi();
const [update, setUpdate] = useState(false);

const { account } = useParams();

const topic = useCallback(() => {
return Object.keys(clusters).map((c) => `account:${account}.cluster:${c}`);
}, [clusters])();

const listCluster = useCallback(async () => {
try {
const cl = await api.listAllClusters();
const parsed = parseNodes(cl.data).reduce(
(acc, c) => {
acc[c.metadata.name] = c;
return acc;
},
{} as { [key: string]: ExtractNodeType<IByocClusters> },
);
setClusters(parsed);
return clusters;
} catch (err) {
console.error(err);
return false;
}
}, []);

useDebounce(
() => {
listCluster();
},
3000,
[update],
);

useSocketWatch(() => {
setUpdate((p) => !p);
}, topic);

return (
<ClusterStatusContext.Provider
value={useMemo(
() => ({ clusters, setClusters }),
[clusters, setClusters],
)}
>
{children}
</ClusterStatusContext.Provider>
);
};

export default ClusterStatusProvider;

export const useClusterStatusV2 = () => {
return useContext(ClusterStatusContext);
};
4 changes: 3 additions & 1 deletion src/apps/console/hooks/use-cluster-status.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { useCallback, useEffect, useState } from 'react';
import { useConsoleApi } from '../server/gql/api-provider';
import { parseNodes } from '../server/r-utils/common';

const findClusterStatus = (item?: { lastOnlineAt?: string }): boolean => {
export const findClusterStatus = (item?: {
lastOnlineAt?: string;
}): boolean => {
if (!item || !item.lastOnlineAt) {
return false;
}
Expand Down
32 changes: 22 additions & 10 deletions src/apps/console/routes/_main+/$account+/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { useSearch } from '~/root/lib/client/helpers/search-filter';
import { IMSvTemplates } from '~/console/server/gql/queries/managed-templates-queries';
import { IByocClusters } from '~/console/server/gql/queries/byok-cluster-queries';
import { IConsoleRootContext } from '../_layout/_layout';
import { useClusterStatusV2 } from '~/console/hooks/use-cluster-status-v2';

export const loader = async (ctx: IRemixCtx) => {
const { account } = ctx.params;
Expand All @@ -66,14 +67,14 @@ export const loader = async (ctx: IRemixCtx) => {
}

const { data: msvTemplates, errors: msvError } = await GQLServerHandler(
ctx.request
ctx.request,
).listMSvTemplates({});
if (msvError) {
throw msvError[0];
}

const { data: clusterList, errors: clusterError } = await GQLServerHandler(
ctx.request
ctx.request,
).listByokClusters({
pagination: {
first: 100,
Expand All @@ -84,10 +85,13 @@ export const loader = async (ctx: IRemixCtx) => {
throw clusterError[0];
}

const cMaps = parseNodes(clusterList).reduce((acc, c) => {
acc[c.metadata.name] = c;
return acc;
}, {} as { [key: string]: ExtractNodeType<IByocClusters> });
const cMaps = parseNodes(clusterList).reduce(
(acc, c) => {
acc[c.metadata.name] = c;
return acc;
},
{} as { [key: string]: ExtractNodeType<IByocClusters> },
);

acccountData = data;
return {
Expand Down Expand Up @@ -187,6 +191,14 @@ const Account = () => {
useEffect(() => {
ensureAccountClientSide(params);
}, []);

const { setClusters } = useClusterStatusV2();

useEffect(() => {
// @ts-ignore
setClusters(clustersMap);
}, [clustersMap]);

return (
<>
<Outlet
Expand Down Expand Up @@ -370,7 +382,7 @@ const CurrentBreadcrum = ({ account }: { account: IAccount }) => {

const { data: accounts } = useCustomSwr(
() => '/accounts',
async () => api.listAccounts({})
async () => api.listAccounts({}),
);

const [searchText, setSearchText] = useState('');
Expand All @@ -387,7 +399,7 @@ const CurrentBreadcrum = ({ account }: { account: IAccount }) => {
searchText,
keys: ['searchField'],
},
[searchText, accounts]
[searchText, accounts],
);

const [open, setOpen] = useState(false);
Expand Down Expand Up @@ -422,7 +434,7 @@ const CurrentBreadcrum = ({ account }: { account: IAccount }) => {
aria-label="accounts"
className={cn(
'outline-none rounded py-lg px-md mx-md bg-surface-basic-hovered',
open || isMouseOver ? 'bg-surface-basic-pressed' : ''
open || isMouseOver ? 'bg-surface-basic-pressed' : '',
)}
onMouseOver={() => {
setIsMouseOver(true);
Expand Down Expand Up @@ -470,7 +482,7 @@ const CurrentBreadcrum = ({ account }: { account: IAccount }) => {
'flex flex-row items-center justify-between',
parseName(item) === parseName(account)
? 'bg-surface-basic-pressed hover:!bg-surface-basic-pressed'
: ''
: '',
)}
>
<span>{item.displayName}</span>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ import ResourceExtraAction, {
IResourceExtraItem,
} from '~/console/components/resource-extra-action';
import { SyncStatusV2 } from '~/console/components/sync-status';
import useClusterStatus from '~/console/hooks/use-cluster-status';
import useClusterStatus, {
findClusterStatus,
} from '~/console/hooks/use-cluster-status';
import { IAccountContext } from '~/console/routes/_main+/$account+/_layout';
import { useConsoleApi } from '~/console/server/gql/api-provider';
import { IEnvironments } from '~/console/server/gql/queries/environment-queries';
Expand All @@ -34,6 +36,7 @@ import { useWatchReload } from '~/lib/client/helpers/socket/useWatch';
import { useReload } from '~/root/lib/client/helpers/reloader';
import { handleError } from '~/root/lib/utils/common';
import CloneEnvironment from './clone-environment';
import { useClusterStatusV2 } from '~/console/hooks/use-cluster-status-v2';

const RESOURCE_NAME = 'environment';
type BaseType = ExtractNodeType<IEnvironments>;
Expand Down Expand Up @@ -192,18 +195,19 @@ const GridView = ({ items = [], onAction }: IResource) => {

const ListView = ({ items, onAction }: IResource) => {
const { account } = useParams();
const { findClusterStatus, clusters, loading } = useClusterStatus();
// const { findClusterStatus } = useClusterStatus();
const { clusters } = useClusterStatusV2();

const [clusterOnlineStatus, setClusterOnlineStatus] = useState<
Record<string, boolean>
>({});
useEffect(() => {
const states: Record<string, boolean> = {};
clusters.forEach((c) => {
states[c.metadata.name] = findClusterStatus(c);
});
setClusterOnlineStatus(states);
}, [clusters]);
// const [clusterOnlineStatus, setClusterOnlineStatus] = useState<
// Record<string, boolean>
// >({});
// useEffect(() => {
// const states: Record<string, boolean> = {};
// clusters.forEach((c) => {
// states[c.metadata.name] = findClusterStatus(c);
// });
// setClusterOnlineStatus(states);
// }, [clusters]);

return (
<ListV2.Root
Expand Down Expand Up @@ -243,7 +247,8 @@ const ListView = ({ items, onAction }: IResource) => {
],
rows: items.map((i) => {
const { name, id, updateInfo } = parseItem(i);
const isClusterOnline = clusterOnlineStatus[i.clusterName];
// const isClusterOnline = clusterOnlineStatus[i.clusterName];=
const isClusterOnline = findClusterStatus(clusters[i.clusterName]);

return {
columns: {
Expand All @@ -266,9 +271,9 @@ const ListView = ({ items, onAction }: IResource) => {
if (i.isArchived) {
return <Badge type="neutral">Archived</Badge>;
}
if (loading) {
return null;
}
// if (loading) {
// return null;
// }

if (!isClusterOnline) {
return <Badge type="warning">Cluster Offline</Badge>;
Expand Down Expand Up @@ -314,7 +319,7 @@ const EnvironmentResourcesV2 = ({ items = [] }: { items: BaseType[] }) => {
useWatchReload(
items.map((i) => {
return `account:${parseName(account)}.environment:${parseName(i)}`;
})
}),
);

const suspendEnvironment = async (item: BaseType, suspend: boolean) => {
Expand All @@ -340,7 +345,7 @@ const EnvironmentResourcesV2 = ({ items = [] }: { items: BaseType[] }) => {
suspend
? 'Environment suspended successfully'
: 'Environment resumed successfully'
}`
}`,
);
reloadPage();
} catch (err) {
Expand All @@ -349,7 +354,7 @@ const EnvironmentResourcesV2 = ({ items = [] }: { items: BaseType[] }) => {
};

const [showDeleteDialog, setShowDeleteDialog] = useState<BaseType | null>(
null
null,
);
const [visible, setVisible] = useState<BaseType | null>(null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { ViewClusterLogs } from '~/console/components/cluster-logs-popop';
import { ensureAccountClientSide } from '~/console/server/utils/auth-utils';
import TooltipV2 from '~/components/atoms/tooltipV2';
import HandleByokCluster from '../byok-cluster/handle-byok-cluster';
import { useClusterStatusV2 } from '~/console/hooks/use-cluster-status-v2';

type BaseType = ExtractNodeType<IClusters> & { type: 'normal' };
type ByokBaseType = ExtractNodeType<IByocClusters> & { type: 'byok' };
Expand Down Expand Up @@ -120,7 +121,7 @@ const ByokInstructionsPopup = ({
return api.getBYOKClusterInstructions({
name: item.metadata.name,
});
}
},
);

return (
Expand Down Expand Up @@ -415,6 +416,7 @@ const GridView = ({ items = [], onEdit, onDelete, onShowLogs }: IResource) => {
};
const ListView = ({ items = [], onEdit, onDelete, onShowLogs }: IResource) => {
const { account } = useParams();
const { clusters } = useClusterStatusV2();
return (
<ListV2.Root
linkComponent={Link}
Expand Down Expand Up @@ -485,7 +487,9 @@ const ListView = ({ items = [], onEdit, onDelete, onShowLogs }: IResource) => {
),
},
status: {
render: () => <GetSyncStatus lastOnlineAt={i.lastOnlineAt} />,
render: () => (
<GetSyncStatus lastOnlineAt={clusters[id]?.lastOnlineAt} />
),
},
updated: {
render: () => (
Expand Down Expand Up @@ -530,7 +534,7 @@ const ClusterResourcesV2 = ({
useWatchReload(
bItems.map((i) => {
return `account:${parseName(account)}.cluster:${parseName(i)}`;
})
}),
);

const [showDeleteDialog, setShowDeleteDialog] =
Expand Down
33 changes: 18 additions & 15 deletions src/apps/console/routes/_main+/_layout/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import { ExtractNodeType, parseNodes } from '~/console/server/r-utils/common';
import { ICommsNotifications } from '~/console/server/gql/queries/comms-queries';
import { LoadingPlaceHolder } from '~/console/components/loading';
import logger from '~/root/lib/client/helpers/log';
import ClusterStatusProvider from '~/console/hooks/use-cluster-status-v2';

const restActions = (ctx: IExtRemixCtx) => {
return withContext(ctx, {});
Expand Down Expand Up @@ -304,7 +305,7 @@ const NotificationMenu = () => {
first: 100,
},
}),
true
true,
);

const notifications = parseNodes(notificationsData);
Expand Down Expand Up @@ -477,7 +478,7 @@ const Console = () => {
{breadcrum.map((bc: any, index) =>
cloneElement(bc.handle.breadcrum(bc), {
key: generateKey(index),
})
}),
)}
</Breadcrum.Root>
)
Expand All @@ -494,19 +495,21 @@ const Console = () => {
</div>
}
/>
<ViewModeProvider>
<SubNavDataProvider>
<UnsavedChangesProvider>
<Container className="pb-5xl">
<Outlet
context={{
...loaderData,
}}
/>
</Container>
</UnsavedChangesProvider>
</SubNavDataProvider>
</ViewModeProvider>
<ClusterStatusProvider>
<ViewModeProvider>
<SubNavDataProvider>
<UnsavedChangesProvider>
<Container className="pb-5xl">
<Outlet
context={{
...loaderData,
}}
/>
</Container>
</UnsavedChangesProvider>
</SubNavDataProvider>
</ViewModeProvider>
</ClusterStatusProvider>
</div>
);
};
Expand Down

0 comments on commit 37aa2eb

Please sign in to comment.