Skip to content

Commit

Permalink
fix(state): lint and prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
Desvelao committed Dec 12, 2024
1 parent 65d7a4c commit 9a2dafa
Show file tree
Hide file tree
Showing 4 changed files with 193 additions and 119 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ import {
EuiCallOut,
EuiDescriptionList,
EuiSpacer,
EuiFlexGroup,
EuiFlexItem,
} from '@elastic/eui';
import React, { Fragment, useState, useEffect, useRef } from 'react';
import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import { AppState, ErrorHandler } from '../../../react-services';
import { compose } from 'redux';
import { ErrorHandler } from '../../../react-services';
import {
useAppConfig,
useRouterSearch,
Expand All @@ -33,7 +35,7 @@ import {
} from '../services';
import { CheckResult } from '../components/check-result';
import { withErrorBoundary, withRouteResolvers } from '../../common/hocs';
import { getCore, getHttp, getWzCurrentAppID } from '../../../kibana-services';
import { getCore, getHttp } from '../../../kibana-services';
import {
HEALTH_CHECK_REDIRECTION_TIME,
WAZUH_INDEX_TYPE_MONITORING,
Expand All @@ -43,7 +45,6 @@ import { getThemeAssetURL, getAssetURL } from '../../../utils/assets';
import { serverApis } from '../../../utils/applications';
import { RedirectAppLinks } from '../../../../../../src/plugins/opensearch_dashboards_react/public';
import { ip, wzConfig } from '../../../services/resolves';
import { compose } from 'redux';
import NavigationService from '../../../react-services/navigation-service';

const checks = {
Expand Down Expand Up @@ -94,12 +95,51 @@ const checks = {
},
};

const addTagsToUrl = (error: string) => {
const words = error.split(' ');

for (const [index, word] of words.entries()) {
if (word.includes('http://') || word.includes('https://')) {
if (words[index - 1] === 'guide:') {
if (word.endsWith('.') || word.endsWith(',')) {
words[index - 2] = `<a href="${word.slice(
0,
-1,
)}" rel="noopener noreferrer" target="_blank">${
words[index - 2]
} ${words[index - 1].slice(0, -1)}</a>${word.slice(-1)}`;
} else {
words[index - 2] =
`<a href="${word}" rel="noopener noreferrer" target="_blank">${
words[index - 2]
} ${words[index - 1].slice(0, -1)}</a> `;
}

words.splice(index - 1, 2);
} else {
if (word.endsWith('.') || word.endsWith(',')) {
words[index] = `<a href="${word.slice(
0,
-1,
)}" rel="noopener noreferrer" target="_blank">${word.slice(
0,
-1,
)}</a>${word.slice(-1)}`;
} else {
words[index] =
`<a href="${word}" rel="noopener noreferrer" target="_blank">${word}</a>`;
}
}
}
}

return words.join(' ');
};

function HealthCheckComponent() {
const [checkWarnings, setCheckWarnings] = useState<{ [key: string]: [] }>({});
const [checkErrors, setCheckErrors] = useState<{ [key: string]: [] }>({});
const [checksReady, setChecksReady] = useState<{ [key: string]: boolean }>(
{},
);
const [checkWarnings, setCheckWarnings] = useState<Record<string, []>>({});
const [checkErrors, setCheckErrors] = useState<Record<string, []>>({});
const [checksReady, setChecksReady] = useState<Record<string, boolean>>({});
const [isDebugMode, setIsDebugMode] = useState<boolean>(false);
const appConfig = useAppConfig();
const checksInitiated = useRef(false);
Expand All @@ -119,6 +159,7 @@ function HealthCheckComponent() {
.pathname +
'?' +
searchParams;

NavigationService.getInstance().navigate(relativePath);
} else {
NavigationService.getInstance().navigate('/');
Expand All @@ -136,19 +177,18 @@ function HealthCheckComponent() {

useEffect(() => {
// Redirect to app when all checks are ready
Object.keys(checks).every(check => checksReady[check]) &&
if (
Object.keys(checks).every(check => checksReady[check]) &&
!isDebugMode &&
!thereAreWarnings &&
(() =>
setTimeout(
redirectionPassHealthcheck,
HEALTH_CHECK_REDIRECTION_TIME,
))();
!thereAreWarnings
) {
setTimeout(redirectionPassHealthcheck, HEALTH_CHECK_REDIRECTION_TIME);
}
}, [checksReady]);

useEffect(() => {
// Check if Health should not redirect automatically (Debug mode)
setIsDebugMode(typeof search.debug !== 'undefined');
setIsDebugMode(search.debug !== undefined);
}, []);

const handleWarnings = (checkID, warnings, parsed) => {
Expand All @@ -160,6 +200,7 @@ function HealthCheckComponent() {
}),
)
: warnings;

setCheckWarnings(prev => ({ ...prev, [checkID]: newWarnings }));
};

Expand All @@ -172,6 +213,7 @@ function HealthCheckComponent() {
}),
)
: errors;

setCheckErrors(prev => ({ ...prev, [checkID]: newErrors }));
};

Expand All @@ -198,73 +240,32 @@ function HealthCheckComponent() {

const renderChecks = () => {
const showLogButton = thereAreErrors || thereAreWarnings || isDebugMode;
return Object.keys(checks).map((check, index) => {
return (
<CheckResult
showLogButton={showLogButton}
key={`health_check_check_${check}`}
name={check}
title={checks[check].title}
awaitFor={checks[check].awaitFor}
shouldCheck={
checks[check].shouldCheck || appConfig.data[`checks.${check}`]
}
validationService={checks[check].validator(appConfig)}
handleWarnings={handleWarnings}
handleErrors={handleErrors}
cleanWarnings={cleanWarnings}
cleanErrors={cleanErrors}
isLoading={appConfig.isLoading}
handleCheckReady={handleCheckReady}
checksReady={checksReady}
canRetry={checks[check].canRetry}
/>
);
});
};

const addTagsToUrl = error => {
const words = error.split(' ');
words.forEach((word, index) => {
if (word.includes('http://') || word.includes('https://')) {
if (words[index - 1] === 'guide:') {
if (word.endsWith('.') || word.endsWith(',')) {
words[index - 2] = `<a href="${word.slice(
0,
-1,
)}" rel="noopener noreferrer" target="_blank">${
words[index - 2]
} ${words[index - 1].slice(0, -1)}</a>${word.slice(-1)}`;
} else {
words[
index - 2
] = `<a href="${word}" rel="noopener noreferrer" target="_blank">${
words[index - 2]
} ${words[index - 1].slice(0, -1)}</a> `;
}
words.splice(index - 1, 2);
} else {
if (word.endsWith('.') || word.endsWith(',')) {
words[index] = `<a href="${word.slice(
0,
-1,
)}" rel="noopener noreferrer" target="_blank">${word.slice(
0,
-1,
)}</a>${word.slice(-1)}`;
} else {
words[
index
] = `<a href="${word}" rel="noopener noreferrer" target="_blank">${word}</a>`;
}
return Object.keys(checks).map(check => (
<CheckResult
showLogButton={showLogButton}
key={`health_check_check_${check}`}
name={check}
title={checks[check].title}
awaitFor={checks[check].awaitFor}
shouldCheck={
checks[check].shouldCheck || appConfig.data[`checks.${check}`]
}
}
});
return words.join(' ');
validationService={checks[check].validator(appConfig)}
handleWarnings={handleWarnings}
handleErrors={handleErrors}
cleanWarnings={cleanWarnings}
cleanErrors={cleanErrors}
isLoading={appConfig.isLoading}
handleCheckReady={handleCheckReady}
checksReady={checksReady}
canRetry={checks[check].canRetry}
/>
));
};

const renderWarnings = () => {
return Object.keys(checkWarnings).map(checkID =>
const renderWarnings = () =>
Object.keys(checkWarnings).map(checkID =>
checkWarnings[checkID].map((warning, index) => (
<Fragment key={index}>
<EuiCallOut
Expand All @@ -285,10 +286,8 @@ function HealthCheckComponent() {
</Fragment>
)),
);
};

const renderErrors = () => {
return Object.keys(checkErrors).map(checkID =>
const renderErrors = () =>
Object.keys(checkErrors).map(checkID =>
checkErrors[checkID].map((error, index) => (
<Fragment key={index}>
<EuiCallOut
Expand All @@ -309,7 +308,6 @@ function HealthCheckComponent() {
</Fragment>
)),
);
};

return (
<div className='health-check'>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
import { ILogger } from '../../../../common/services/configuration';
import { StateContainer } from '../types';
import { BehaviorSubject } from 'rxjs';
import { Logger } from '../../../../common/services/configuration';
import { StateContainer } from '../types';

export class DataSourceAlertsStateContainer implements StateContainer {
private store: any;
private storeKey: string = 'currentPattern';
private readonly store: any;
private readonly STORE_KEY = 'currentPattern';
updater$: BehaviorSubject<string>;
constructor(private logger: ILogger, { store }) {

constructor(
private readonly logger: Logger,
{ store },
) {
this.store = store;
this.updater$ = new BehaviorSubject(this.get());
}

get() {
try {
this.logger.debug('Getting data');
const rawData = this.store.get(this.storeKey);

const rawData = this.store.get(this.STORE_KEY);
let result = '';

if (rawData) {
this.logger.debug('Getting decoded data');

let decodedData = decodeURI(rawData);

this.logger.debug(`Decoded data: ${decodedData}`);

/* I assume in previous versions, the selected index pattern could be wrapped with " characters.
Expand All @@ -27,9 +35,10 @@ export class DataSourceAlertsStateContainer implements StateContainer {
if (
decodedData &&
decodedData[0] === '"' &&
decodedData[decodedData.length - 1] === '"'
decodedData.at(-1) === '"'
) {
const newPattern = decodedData.substring(1, decodedData.length - 1);
const newPattern = decodedData.slice(1, -1);

this.set(newPattern);
decodedData = decodeURI(this.store.get('currentPattern'));
}
Expand All @@ -39,29 +48,37 @@ export class DataSourceAlertsStateContainer implements StateContainer {
this.logger.debug('No raw data');
result = '';
}

this.logger.debug(`Data: ${result}`);

return result;
} catch (error) {
this.logger.error(error.message);
this.logger.error(`Error getting data: ${error.message}`);
throw error;
}
}
set(data) {

set(data: any) {
try {
this.logger.debug(`Setting data: ${data}`);

const encodedData = encodeURI(data);

this.logger.debug(`Setting encoded data: ${encodedData}`);

const exp = new Date();

exp.setDate(exp.getDate() + 365);

if (data) {
this.store.set(this.storeKey, encodedData, {
this.store.set(this.STORE_KEY, encodedData, {
expires: exp,
});
this.updater$.next(encodedData);
this.logger.debug(`Encoded data was set: ${encodedData}`);
}
} catch (error) {
this.logger.error(error.message);
this.logger.error(`Error setting data: ${error.message}`);
// TODO: implement
// const options = {
// context: `${AppState.name}.setClusterInfo`,
Expand All @@ -77,22 +94,30 @@ export class DataSourceAlertsStateContainer implements StateContainer {
throw error;
}
}

remove() {
try {
this.logger.debug('Removing');
const result = this.store.remove(this.storeKey);
this.updater$.next(undefined);

const result = this.store.remove(this.STORE_KEY);

this.updater$.next();
this.logger.debug('Removed');

return result;
} catch (error) {
this.logger.error(error.message);
throw error;
}
}
subscribe(callback) {

subscribe(callback: (value: any) => void) {
this.logger.debug('Subscribing');

const subscription = this.updater$.subscribe(callback);

this.logger.debug('Subscribed');

return subscription;
}
}
Loading

0 comments on commit 9a2dafa

Please sign in to comment.