devmadhuu commented on code in PR #9033:
URL: https://github.com/apache/ozone/pull/9033#discussion_r2349447223


##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/v2/pages/overview/overview.tsx:
##########
@@ -16,31 +16,55 @@
  * limitations under the License.
  */
 
-import React, { useEffect, useRef, useState } from 'react';
-import moment from 'moment';
-import filesize from 'filesize';
-import axios from 'axios';
+import React, { useState, useRef, useEffect } from 'react';
 import { Row, Col, Button } from 'antd';
-import {
-  CheckCircleFilled,
-  WarningFilled
-} from '@ant-design/icons';
 import { Link } from 'react-router-dom';
+import moment from 'moment';
 
-import AutoReloadPanel from '@/components/autoReloadPanel/autoReloadPanel';
+import OverviewSimpleCard from 
'@/v2/components/overviewCard/overviewSimpleCard';
 import OverviewSummaryCard from 
'@/v2/components/overviewCard/overviewSummaryCard';
 import OverviewStorageCard from 
'@/v2/components/overviewCard/overviewStorageCard';
-import OverviewSimpleCard from 
'@/v2/components/overviewCard/overviewSimpleCard';
-
-import { AutoReloadHelper } from '@/utils/autoReloadHelper';
-import { checkResponseError, showDataFetchError } from '@/utils/common';
-import { AxiosGetHelper, cancelRequests, PromiseAllSettledGetHelper } from 
'@/utils/axiosRequestHelper';
-
-import { ClusterStateResponse, OverviewState, StorageReport } from 
'@/v2/types/overview.types';
-
+import { AxiosGetHelper } from '@/utils/axiosRequestHelper';
+import { showDataFetchError } from '@/utils/common';
+import { cancelRequests } from '@/utils/axiosRequestHelper';
+import { useApiData } from '@/v2/hooks/useAPIData.hook';
+import { useAutoReload } from '@/v2/hooks/useAutoReload.hook';
+import AutoReloadPanel from '@/components/autoReloadPanel/autoReloadPanel';
+import { ClusterStateResponse, KeysSummary, OverviewState, TaskStatus } from 
'@/v2/types/overview.types';
 import './overview.less';
+import filesize from 'filesize';
+import { CheckCircleFilled, WarningFilled } from '@ant-design/icons';
 
+const DEFAULT_CLUSTER_STATE: ClusterStateResponse = {

Review Comment:
   Can we move these default constants to something like 
`overview.constants.ts` ?
   ```
   export const OVERVIEW_DEFAULTS = {
       CLUSTER_STATE: { ... },
       TASK_STATUS: [],
       // ...
     };
   ```



##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/v2/pages/overview/overview.tsx:
##########
@@ -16,31 +16,55 @@
  * limitations under the License.
  */
 
-import React, { useEffect, useRef, useState } from 'react';
-import moment from 'moment';
-import filesize from 'filesize';
-import axios from 'axios';
+import React, { useState, useRef, useEffect } from 'react';
 import { Row, Col, Button } from 'antd';
-import {
-  CheckCircleFilled,
-  WarningFilled
-} from '@ant-design/icons';
 import { Link } from 'react-router-dom';
+import moment from 'moment';
 
-import AutoReloadPanel from '@/components/autoReloadPanel/autoReloadPanel';
+import OverviewSimpleCard from 
'@/v2/components/overviewCard/overviewSimpleCard';
 import OverviewSummaryCard from 
'@/v2/components/overviewCard/overviewSummaryCard';
 import OverviewStorageCard from 
'@/v2/components/overviewCard/overviewStorageCard';
-import OverviewSimpleCard from 
'@/v2/components/overviewCard/overviewSimpleCard';
-
-import { AutoReloadHelper } from '@/utils/autoReloadHelper';
-import { checkResponseError, showDataFetchError } from '@/utils/common';
-import { AxiosGetHelper, cancelRequests, PromiseAllSettledGetHelper } from 
'@/utils/axiosRequestHelper';
-
-import { ClusterStateResponse, OverviewState, StorageReport } from 
'@/v2/types/overview.types';
-
+import { AxiosGetHelper } from '@/utils/axiosRequestHelper';
+import { showDataFetchError } from '@/utils/common';
+import { cancelRequests } from '@/utils/axiosRequestHelper';
+import { useApiData } from '@/v2/hooks/useAPIData.hook';
+import { useAutoReload } from '@/v2/hooks/useAutoReload.hook';
+import AutoReloadPanel from '@/components/autoReloadPanel/autoReloadPanel';
+import { ClusterStateResponse, KeysSummary, OverviewState, TaskStatus } from 
'@/v2/types/overview.types';
 import './overview.less';
+import filesize from 'filesize';
+import { CheckCircleFilled, WarningFilled } from '@ant-design/icons';
 
+const DEFAULT_CLUSTER_STATE: ClusterStateResponse = {
+  missingContainers: 0,
+  totalDatanodes: 0,
+  healthyDatanodes: 0,
+  pipelines: 0,
+  storageReport: { capacity: 0, used: 0, remaining: 0, committed: 0 },
+  containers: 0,
+  volumes: 0,
+  buckets: 0,
+  keys: 0,
+  openContainers: 0,
+  deletedContainers: 0,
+  keysPendingDeletion: 0,
+  scmServiceId: 'N/A',
+  omServiceId: 'N/A'
+};
 
+const DEFAULT_TASK_STATUS: TaskStatus[] = [];
+const DEFAULT_OPEN_KEYS_SUMMARY: KeysSummary & {totalOpenKeys: number} = {
+  totalUnreplicatedDataSize: 0,
+  totalReplicatedDataSize: 0,
+  totalOpenKeys: 0
+};
+const DEFAULT_DELETE_PENDING_KEYS_SUMMARY: KeysSummary & {totalDeletedKeys: 
number} = {

Review Comment:
   same comment as above for all default constants 



##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/v2/components/errors/errorCard.tsx:
##########
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+import React from 'react';
+import { DisconnectOutlined } from "@ant-design/icons"
+import { Card } from 'antd';
+
+type ErrorCardProps = {
+  title: string;
+  compact?: boolean;
+};
+
+// ------------- Styles -------------- //
+const cardHeadStyle: React.CSSProperties = { fontSize: '14px' };
+const compactCardBodyStyle: React.CSSProperties = {
+  padding: '24px',
+  justifyTracks: 'space-between'

Review Comment:
   Is it a typo ? 
   ```suggestion
     justifyContent: 'space-between'
   ```



##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/v2/hooks/useAPIData.hook.ts:
##########
@@ -0,0 +1,186 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { useState, useEffect, useRef } from 'react';
+import { AxiosGetHelper } from '@/utils/axiosRequestHelper';
+
+export interface ApiState<T> {
+  data: T;
+  loading: boolean;
+  error: string | null;
+  lastUpdated: number | null;
+}
+
+export interface UseApiDataOptions {
+  retryAttempts?: number;
+  retryDelay?: number;
+  initialFetch?: boolean;
+  onError?: (error: string) => void;
+};
+
+export function useApiData<T>(
+  url: string,
+  defaultValue: T,
+  options: UseApiDataOptions = {}
+): ApiState<T> & {
+  refetch: () => void;
+  clearError: () => void;
+} {
+  const {
+    retryAttempts = 3,
+    retryDelay = 1000,
+    initialFetch = true,
+    onError
+  } = options;
+
+  const [state, setState] = useState<ApiState<T>>({
+    data: defaultValue,
+    loading: initialFetch,
+    error: null,
+    lastUpdated: null
+  });
+
+  const controllerRef = useRef<AbortController>();
+  const retryCountRef = useRef(0);
+  const retryTimeoutRef = useRef<NodeJS.Timeout>();
+  
+  // Store stable references
+  const urlRef = useRef(url);
+  const retryAttemptsRef = useRef(retryAttempts);
+  const retryDelayRef = useRef(retryDelay);
+  const onErrorRef = useRef(onError);
+
+  // Update refs when props change
+  useEffect(() => {
+    urlRef.current = url;
+  }, [url]);
+
+  useEffect(() => {
+    retryAttemptsRef.current = retryAttempts;
+  }, [retryAttempts]);
+
+  useEffect(() => {
+    retryDelayRef.current = retryDelay;
+  }, [retryDelay]);
+
+  useEffect(() => {
+    onErrorRef.current = onError;
+  }, [onError]);
+
+
+  const fetchData = async (isRetry = false) => {
+    if (!isRetry) {
+      setState(prev => ({ ...prev, loading: true, error: null }));
+      retryCountRef.current = 0;
+    }
+
+    try {
+      const { request, controller } = AxiosGetHelper(
+        urlRef.current,
+        controllerRef.current,
+        'Request cancelled due to component unmount or new request'
+      );
+      controllerRef.current = controller;
+
+      const response = await request;
+      
+      setState({
+        data: response.data,
+        loading: false,
+        error: null,
+        lastUpdated: Date.now()
+      });
+
+      retryCountRef.current = 0;
+    } catch (error: any) {
+      if (error.name === 'CanceledError') {
+        return;
+      }
+
+      const errorMessage = error.response?.data?.message || 

Review Comment:
   ```suggestion
         const errorMessage = error.response?.data?.message ||
                         error.response?.statusText ||
                         error.message ||
                         `Request failed with status ${error.response?.status 
|| 'unknown'}`;
   ```



##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/v2/types/overview.types.ts:
##########
@@ -33,29 +33,15 @@ export type ClusterStateResponse = {
   omServiceId: string;
 }
 
-export type OverviewState = {
-  loading: boolean;
-  datanodes: string;
-  pipelines: number;
-  containers: number;
-  volumes: number;
-  buckets: number;
-  keys: number;
-  missingContainersCount: number;
-  lastRefreshed: number;
-  lastUpdatedOMDBDelta: number;
-  lastUpdatedOMDBFull: number;
-  omStatus: string;
-  openContainers: number;
-  deletedContainers: number;
-  openSummarytotalUnrepSize: number;
-  openSummarytotalRepSize: number;
-  openSummarytotalOpenKeys: number;
-  deletePendingSummarytotalUnrepSize: number;
-  deletePendingSummarytotalRepSize: number;
-  deletePendingSummarytotalDeletedKeys: number;
-  scmServiceId: string;
-  omServiceId: string;
+export type TaskStatus = {
+  taskName: string;

Review Comment:
   Usually okay, but it is a suggestion to try using more specific task names 
when we know already:
   
   ```
   export type TaskStatus = {
       taskName: 'OmDeltaRequest' | 'OmSnapshotRequest' | string;
       lastUpdatedTimestamp: number;
       lastUpdatedSeqNumber: number;
     }
   ```



##########
hadoop-ozone/recon/src/main/resources/webapps/recon/ozone-recon-web/src/v2/hooks/useAutoReload.hook.tsx:
##########
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { useEffect, useRef, useState } from 'react';
+import { AUTO_RELOAD_INTERVAL_DEFAULT } from 
'@/constants/autoReload.constants';
+
+export function useAutoReload(
+  refreshFunction: () => void,
+  interval: number = AUTO_RELOAD_INTERVAL_DEFAULT
+) {
+  const intervalRef = useRef<number>(0);
+  const [isPolling, setIsPolling] = useState<boolean>(false);
+  const refreshFunctionRef = useRef(refreshFunction);
+
+  // Update the ref when the function changes
+  refreshFunctionRef.current = refreshFunction;
+
+  const stopPolling = () => {
+    if (intervalRef.current > 0) {
+      clearTimeout(intervalRef.current);
+      intervalRef.current = 0;
+      setIsPolling(false);
+    }
+  };
+
+  const startPolling = () => {
+    stopPolling();
+    const poll = () => {
+      refreshFunctionRef.current();
+      intervalRef.current = window.setTimeout(poll, interval);
+    };
+    poll();
+    setIsPolling(true);
+  };
+
+  const handleAutoReloadToggle = (checked: boolean) => {
+    sessionStorage.setItem('autoReloadEnabled', JSON.stringify(checked));
+    if (checked) {
+      startPolling();
+    } else {
+      stopPolling();
+    }
+  };
+
+  // Initialize polling on mount if auto-reload is enabled
+  useEffect(() => {

Review Comment:
   Usually it is okay, but best code practice to avoid double polling is by 
using below way:
   
   ```
   useEffect(() => {
       const autoReloadEnabled = sessionStorage.getItem('autoReloadEnabled') 
!== 'false';
       if (autoReloadEnabled) {
         const timeoutId = setTimeout(startPolling, 100); // Slight delay
         return () => {
           clearTimeout(timeoutId);
           stopPolling();
         };
       }
       return stopPolling;
     }, []);
   
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to