Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,21 @@ export const sloDetailsHistoryLocatorID = 'SLO_DETAILS_HISTORY_LOCATOR';
export const sloEditLocatorID = 'SLO_EDIT_LOCATOR';
export const sloListLocatorID = 'SLO_LIST_LOCATOR';

export const OVERVIEW_TAB_ID = 'overview';
export const HISTORY_TAB_ID = 'history';
export const DEFINITION_TAB_ID = 'definition';
export const ALERTS_TAB_ID = 'alerts';

export type SloTabId =
| typeof OVERVIEW_TAB_ID
| typeof ALERTS_TAB_ID
| typeof HISTORY_TAB_ID
| typeof DEFINITION_TAB_ID;

export interface SloDetailsLocatorParams extends SerializableRecord {
sloId?: string;
sloId: string;
instanceId?: string;
tabId?: SloTabId;
}

export interface SloDetailsHistoryLocatorParams extends SerializableRecord {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ import {
import { i18n } from '@kbn/i18n';
import type { SLOWithSummaryResponse } from '@kbn/slo-schema';
import React, { useState } from 'react';
import type { SloTabId } from '@kbn/deeplinks-observability';
import { OVERVIEW_TAB_ID } from '@kbn/deeplinks-observability';
import { HeaderTitle } from '../../../pages/slo_details/components/header_title';
import type { SloTabId } from '../../../pages/slo_details/components/slo_details';
import { OVERVIEW_TAB_ID, SloDetails } from '../../../pages/slo_details/components/slo_details';
import { SloDetails } from '../../../pages/slo_details/components/slo_details';
import { useSloDetailsTabs } from '../../../pages/slo_details/hooks/use_slo_details_tabs';
import { getSloFormattedSummary } from '../../../pages/slos/hooks/use_slo_summary';
import { useKibana } from '../../../hooks/use_kibana';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import { ALL_VALUE } from '@kbn/slo-schema/src/schema/common';
export class SloDetailsLocatorDefinition implements LocatorDefinition<SloDetailsLocatorParams> {
public readonly id = sloDetailsLocatorID;

public readonly getLocation = async ({ sloId, instanceId }: SloDetailsLocatorParams) => {
const queryParams =
!!instanceId && instanceId !== ALL_VALUE
? `?instanceId=${encodeURIComponent(instanceId)}`
: '';
const path = !!sloId ? `/${encodeURIComponent(sloId)}${queryParams}` : '/';
public readonly getLocation = async ({ sloId, instanceId, tabId }: SloDetailsLocatorParams) => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kdelemme I saw you had refactored the locator here, so I decided to bring that part as well

const qs = new URLSearchParams();
if (!!instanceId && instanceId !== ALL_VALUE) qs.append('instanceId', instanceId);

let path = `/${encodeURIComponent(sloId)}${formatQueryParams(qs)}`;
if (tabId) {
path = `/${encodeURIComponent(sloId)}/${tabId}${formatQueryParams(qs)}`;
}

return {
app: 'slo',
Expand All @@ -26,3 +28,10 @@ export class SloDetailsLocatorDefinition implements LocatorDefinition<SloDetails
};
};
}

function formatQueryParams(qs: URLSearchParams): string {
if (qs.size === 0) {
return '';
}
return `?${qs.toString()}`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import DateMath from '@kbn/datemath';
import { createKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public';
import type { SLODefinitionResponse, SLOWithSummaryResponse } from '@kbn/slo-schema';
import type { RecursivePartial } from '@kbn/utility-types';
import deepmerge from 'deepmerge';
import moment from 'moment';
import { useEffect, useRef, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { toDuration } from '../../../../../utils/slo/duration';

const SLO_HISTORY_URL_STORAGE_KEY = '_a';

interface AppState {
range: {
from: Date;
to: Date;
};
}

interface SerializedAppState {
range: {
from: string;
to: string;
};
}

const DEFAULT_STATE: AppState = {
range: {
from: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
to: new Date(),
},
};

export function useUrlAppState(slo: SLOWithSummaryResponse | SLODefinitionResponse): {
state: AppState;
updateState: (state: AppState) => void;
} {
const [state, setState] = useState<AppState>(() => {
const initialState = {
...DEFAULT_STATE,
range: getDefaultRangeFromSlo(slo),
};
return initialState;
});

const history = useHistory();
const urlStateStorage = useRef(
createKbnUrlStateStorage({
history,
useHash: false,
useHashQuery: false,
})
);

useEffect(() => {
setState(
toAppState(
urlStateStorage.current?.get<SerializedAppState>(SLO_HISTORY_URL_STORAGE_KEY) ?? {},
slo
)
);
}, [urlStateStorage, slo]);

const updateState = (newState: AppState) => {
setState((prevState) => {
const updatedState = deepmerge(prevState, newState);
urlStateStorage.current?.set(SLO_HISTORY_URL_STORAGE_KEY, updatedState, {
replace: true,
});

return updatedState;
});
};

return {
state: deepmerge(DEFAULT_STATE, state),
updateState,
};
}

function getDefaultRangeFromSlo(
slo: SLOWithSummaryResponse | SLODefinitionResponse
): AppState['range'] {
if (slo.timeWindow.type === 'calendarAligned') {
const now = moment();
const duration = toDuration(slo.timeWindow.duration);
const unit = duration.unit === 'w' ? 'isoWeek' : 'month';

return {
from: moment.utc(now).startOf(unit).toDate(),
to: moment.utc(now).endOf(unit).toDate(),
};
}

return {
from: new Date(DateMath.parse(`now-${slo.timeWindow.duration}`)!.valueOf()),
to: new Date(DateMath.parse('now', { roundUp: true })!.valueOf()),
};
}

function toAppState(
urlState: RecursivePartial<SerializedAppState>,
slo: SLOWithSummaryResponse | SLODefinitionResponse
): AppState {
return {
...DEFAULT_STATE,
range:
urlState.range && urlState.range.from && urlState.range.to
? {
from: new Date(urlState.range.from),
to: new Date(urlState.range.to),
}
: getDefaultRangeFromSlo(slo),
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { EuiFlexGroup, EuiFlexItem, EuiPanel, EuiSuperDatePicker, EuiTitle } fro
import DateMath from '@kbn/datemath';
import { i18n } from '@kbn/i18n';
import type { SLOWithSummaryResponse } from '@kbn/slo-schema';
import moment from 'moment';
import React, { useState } from 'react';
import React from 'react';
import { useUrlAppState } from './hooks/use_url_app_state';
import { ErrorRateChart } from '../../../../components/slo/error_rate_chart';
import { useKibana } from '../../../../hooks/use_kibana';
import { toDuration } from '../../../../utils/slo/duration';
Expand All @@ -21,32 +21,15 @@ import { CalendarPeriodPicker } from './calendar_period_picker';

export interface Props {
slo: SLOWithSummaryResponse;
isAutoRefreshing: boolean;
}

export function SloDetailsHistory({ slo, isAutoRefreshing }: Props) {
export function SloDetailsHistory({ slo }: Props) {
const { uiSettings } = useKibana().services;

const [range, setRange] = useState<TimeBounds>(() => {
if (slo.timeWindow.type === 'calendarAligned') {
const now = moment();
const duration = toDuration(slo.timeWindow.duration);
const unit = duration.unit === 'w' ? 'isoWeek' : 'month';

return {
from: moment.utc(now).startOf(unit).toDate(),
to: moment.utc(now).endOf(unit).toDate(),
};
}

return {
from: new Date(DateMath.parse(`now-${slo.timeWindow.duration}`)!.valueOf()),
to: new Date(DateMath.parse('now', { roundUp: true })!.valueOf()),
};
});
const { state, updateState } = useUrlAppState(slo);

const onBrushed = ({ from, to }: TimeBounds) => {
setRange({ from, to });
updateState({ range: { from, to } });
};

return (
Expand All @@ -55,21 +38,23 @@ export function SloDetailsHistory({ slo, isAutoRefreshing }: Props) {
<EuiFlexItem grow css={{ maxWidth: 500 }}>
{slo.timeWindow.type === 'calendarAligned' ? (
<CalendarPeriodPicker
slo={slo}
period={toDuration(slo.timeWindow.duration).unit === 'w' ? 'week' : 'month'}
range={state.range}
onChange={(updatedRange: TimeBounds) => {
setRange(updatedRange);
updateState({ range: updatedRange });
}}
/>
) : (
<EuiSuperDatePicker
isLoading={false}
start={range.from.toISOString()}
end={range.to.toISOString()}
start={state.range.from.toISOString()}
end={state.range.to.toISOString()}
onTimeChange={(val: OnTimeChangeProps) => {
setRange({
const newRange = {
from: new Date(DateMath.parse(val.start)!.valueOf()),
to: new Date(DateMath.parse(val.end, { roundUp: true })!.valueOf()),
});
};
updateState({ range: newRange });
}}
width="full"
showUpdateButton={false}
Expand Down Expand Up @@ -98,7 +83,7 @@ export function SloDetailsHistory({ slo, isAutoRefreshing }: Props) {
</EuiFlexItem>
<ErrorRateChart
slo={slo}
dataTimeRange={range}
dataTimeRange={state.range}
onBrushed={onBrushed}
variant={['VIOLATED', 'DEGRADING'].includes(slo.summary.status) ? 'danger' : 'success'}
/>
Expand All @@ -108,12 +93,17 @@ export function SloDetailsHistory({ slo, isAutoRefreshing }: Props) {
<HistoricalDataCharts
slo={slo}
hideMetadata={true}
isAutoRefreshing={isAutoRefreshing}
range={range}
isAutoRefreshing={false}
range={state.range}
onBrushed={onBrushed}
/>

<EventsChartPanel slo={slo} range={range} hideRangeDurationLabel onBrushed={onBrushed} />
<EventsChartPanel
slo={slo}
range={state.range}
hideRangeDurationLabel
onBrushed={onBrushed}
/>
</EuiFlexGroup>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import { EuiFlexGroup } from '@elastic/eui';
import type { SLOWithSummaryResponse } from '@kbn/slo-schema';
import type { SloTabId } from '@kbn/deeplinks-observability';
import { ALERTS_TAB_ID, DEFINITION_TAB_ID, HISTORY_TAB_ID } from '@kbn/deeplinks-observability';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { BurnRatePanel } from './burn_rate_panel/burn_rate_panel';
Expand All @@ -19,18 +21,6 @@ import { SloHealthCallout } from './slo_health_callout';
import { SloRemoteCallout } from './slo_remote_callout';
import { ActionModalProvider } from '../../../context/action_modal';

export const TAB_ID_URL_PARAM = 'tabId';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TAB_ID_URL_PARAM is not used anywhere, so I removed it. Rest consts were moved to deeplinks package

export const OVERVIEW_TAB_ID = 'overview';
export const HISTORY_TAB_ID = 'history';
export const DEFINITION_TAB_ID = 'definition';
export const ALERTS_TAB_ID = 'alerts';

export type SloTabId =
| typeof OVERVIEW_TAB_ID
| typeof ALERTS_TAB_ID
| typeof HISTORY_TAB_ID
| typeof DEFINITION_TAB_ID;

export interface Props {
slo: SLOWithSummaryResponse;
isAutoRefreshing: boolean;
Expand Down Expand Up @@ -58,7 +48,7 @@ export function SloDetails({ slo, isAutoRefreshing, selectedTabId }: Props) {
}, [isAutoRefreshing]);

if (selectedTabId === HISTORY_TAB_ID) {
return <SloDetailsHistory slo={slo} isAutoRefreshing={isAutoRefreshing} />;
return <SloDetailsHistory slo={slo} />;
}

if (selectedTabId === DEFINITION_TAB_ID) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@

import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import type { SloTabId } from '@kbn/deeplinks-observability';
import { ALERTS_TAB_ID, HISTORY_TAB_ID, OVERVIEW_TAB_ID } from '@kbn/deeplinks-observability';
import type { SloDetailsPathParams } from '../types';
import type { SloTabId } from '../components/slo_details';
import { ALERTS_TAB_ID, HISTORY_TAB_ID, OVERVIEW_TAB_ID } from '../components/slo_details';

export const useSelectedTab = () => {
const { tabId } = useParams<SloDetailsPathParams>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@
import { EuiNotificationBadge, EuiToolTip } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import type { SLOWithSummaryResponse } from '@kbn/slo-schema';
import React from 'react';
import { paths } from '../../../../common/locators/paths';
import { useFetchActiveAlerts } from '../../../hooks/use_fetch_active_alerts';
import { useKibana } from '../../../hooks/use_kibana';
import type { SloTabId } from '../components/slo_details';
import type { SloTabId } from '@kbn/deeplinks-observability';
import {
ALERTS_TAB_ID,
DEFINITION_TAB_ID,
HISTORY_TAB_ID,
OVERVIEW_TAB_ID,
} from '../components/slo_details';
} from '@kbn/deeplinks-observability';
import React from 'react';
import { paths } from '../../../../common/locators/paths';
import { useFetchActiveAlerts } from '../../../hooks/use_fetch_active_alerts';
import { useKibana } from '../../../hooks/use_kibana';

interface Props {
slo?: SLOWithSummaryResponse | null;
Expand Down