Skip to content

Commit d5ed630

Browse files
[Uptime] Migrate to new es client (#82003) (#82875)
* migrate to new es client * fix tests * fix type * types * types * update * update * update * upadte * update snaps Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
1 parent 95ddeae commit d5ed630

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+838
-615
lines changed

x-pack/plugins/uptime/public/components/overview/empty_state/__tests__/__snapshots__/empty_state.test.tsx.snap

Lines changed: 1 addition & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

x-pack/plugins/uptime/public/components/overview/empty_state/__tests__/empty_state.test.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ describe('EmptyState component', () => {
4242

4343
it(`renders error message when an error occurs`, () => {
4444
const errors: IHttpFetchError[] = [
45-
new HttpFetchError('There was an error fetching your data.', 'error', {} as any),
45+
new HttpFetchError('There was an error fetching your data.', 'error', {} as any, {} as any, {
46+
body: { message: 'There was an error fetching your data.' },
47+
}),
4648
];
4749
const component = mountWithRouter(
4850
<EmptyStateComponent statesIndexStatus={null} errors={errors} loading={false}>

x-pack/plugins/uptime/public/components/overview/empty_state/empty_state_error.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ interface EmptyStateErrorProps {
1515

1616
export const EmptyStateError = ({ errors }: EmptyStateErrorProps) => {
1717
const unauthorized = errors.find(
18-
(error: Error) => error.message && error.message.includes('unauthorized')
18+
(error: IHttpFetchError) => error.message && error.message.includes('unauthorized')
1919
);
2020

2121
return (
@@ -46,7 +46,9 @@ export const EmptyStateError = ({ errors }: EmptyStateErrorProps) => {
4646
body={
4747
<Fragment>
4848
{!unauthorized &&
49-
errors.map((error: Error) => <p key={error.message}>{error.message}</p>)}
49+
errors.map((error: IHttpFetchError) => (
50+
<p key={error.body.message}>{error.body.message || error.message}</p>
51+
))}
5052
</Fragment>
5153
}
5254
/>

x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/monitor_list.test.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { MonitorListComponent, noItemsMessage } from '../monitor_list';
1717
import { renderWithRouter, shallowWithRouter } from '../../../../lib';
1818
import * as redux from 'react-redux';
1919
import moment from 'moment';
20+
import { IHttpFetchError } from '../../../../../../../../src/core/public';
2021

2122
jest.mock('@elastic/eui/lib/services/accessibility/html_id_generator', () => {
2223
return {
@@ -187,7 +188,11 @@ describe('MonitorList component', () => {
187188
it('renders error list', () => {
188189
const component = shallowWithRouter(
189190
<MonitorListComponent
190-
monitorList={{ list: getMonitorList(), error: new Error('foo message'), loading: false }}
191+
monitorList={{
192+
list: getMonitorList(),
193+
error: new Error('foo message') as IHttpFetchError,
194+
loading: false,
195+
}}
191196
pageSize={10}
192197
setPageSize={jest.fn()}
193198
/>

x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ export const MonitorListComponent: ({
187187
<EuiSpacer size="m" />
188188
<EuiBasicTable
189189
aria-label={labels.getDescriptionLabel(items.length)}
190-
error={error?.message}
190+
error={error?.body?.message || error?.message}
191191
loading={loading}
192192
isExpandable={true}
193193
hasActions={true}

x-pack/plugins/uptime/public/state/reducers/monitor_list.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
*/
66

77
import { handleActions, Action } from 'redux-actions';
8+
import { IHttpFetchError } from 'src/core/public';
89
import { getMonitorList, getMonitorListSuccess, getMonitorListFailure } from '../actions';
910
import { MonitorSummariesResult } from '../../../common/runtime_types';
1011

1112
export interface MonitorList {
12-
error?: Error;
13+
error?: IHttpFetchError;
1314
loading: boolean;
1415
list: MonitorSummariesResult;
1516
}
@@ -24,7 +25,7 @@ export const initialState: MonitorList = {
2425
loading: false,
2526
};
2627

27-
type Payload = MonitorSummariesResult & Error;
28+
type Payload = MonitorSummariesResult & IHttpFetchError;
2829

2930
export const monitorListReducer = handleActions<MonitorList, Payload>(
3031
{
@@ -41,7 +42,7 @@ export const monitorListReducer = handleActions<MonitorList, Payload>(
4142
error: undefined,
4243
list: { ...action.payload },
4344
}),
44-
[String(getMonitorListFailure)]: (state: MonitorList, action: Action<Error>) => ({
45+
[String(getMonitorListFailure)]: (state: MonitorList, action: Action<IHttpFetchError>) => ({
4546
...state,
4647
error: action.payload,
4748
loading: false,

x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,20 @@ import {
99
IRouter,
1010
SavedObjectsClientContract,
1111
ISavedObjectsRepository,
12-
ILegacyScopedClusterClient,
12+
IScopedClusterClient,
13+
ElasticsearchClient,
1314
} from 'src/core/server';
1415
import { UMKibanaRoute } from '../../../rest_api';
1516
import { PluginSetupContract } from '../../../../../features/server';
1617
import { DynamicSettings } from '../../../../common/runtime_types';
1718
import { MlPluginSetup as MlSetup } from '../../../../../ml/server';
1819

19-
export type ESAPICaller = ILegacyScopedClusterClient['callAsCurrentUser'];
20-
2120
export type UMElasticsearchQueryFn<P, R = any> = (
22-
params: { callES: ESAPICaller; dynamicSettings: DynamicSettings } & P
21+
params: {
22+
callES: ElasticsearchClient;
23+
esClient?: IScopedClusterClient;
24+
dynamicSettings: DynamicSettings;
25+
} & P
2326
) => Promise<R>;
2427

2528
export type UMSavedObjectsQueryFn<T = any, P = undefined> = (

x-pack/plugins/uptime/server/lib/adapters/telemetry/kibana_telemetry_adapter.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@
55
*/
66

77
import moment from 'moment';
8-
import { ISavedObjectsRepository, SavedObjectsClientContract } from 'kibana/server';
8+
import {
9+
ISavedObjectsRepository,
10+
ILegacyScopedClusterClient,
11+
SavedObjectsClientContract,
12+
ElasticsearchClient,
13+
} from 'kibana/server';
914
import { CollectorFetchContext, UsageCollectionSetup } from 'src/plugins/usage_collection/server';
1015
import { PageViewParams, UptimeTelemetry, Usage } from './types';
11-
import { ESAPICaller } from '../framework';
1216
import { savedObjectsAdapter } from '../../saved_objects';
1317

1418
interface UptimeTelemetryCollector {
@@ -21,6 +25,8 @@ const BUCKET_SIZE = 3600;
2125
const BUCKET_NUMBER = 24;
2226

2327
export class KibanaTelemetryAdapter {
28+
public static callCluster: ILegacyScopedClusterClient['callAsCurrentUser'] | ElasticsearchClient;
29+
2430
public static registerUsageCollector = (
2531
usageCollector: UsageCollectionSetup,
2632
getSavedObjectsClient: () => ISavedObjectsRepository | undefined
@@ -125,7 +131,7 @@ export class KibanaTelemetryAdapter {
125131
}
126132

127133
public static async countNoOfUniqueMonitorAndLocations(
128-
callCluster: ESAPICaller,
134+
callCluster: ILegacyScopedClusterClient['callAsCurrentUser'] | ElasticsearchClient,
129135
savedObjectsClient: ISavedObjectsRepository | SavedObjectsClientContract
130136
) {
131137
const dynamicSettings = await savedObjectsAdapter.getUptimeDynamicSettings(savedObjectsClient);
@@ -187,7 +193,11 @@ export class KibanaTelemetryAdapter {
187193
},
188194
};
189195

190-
const result = await callCluster('search', params);
196+
const { body: result } =
197+
typeof callCluster === 'function'
198+
? await callCluster('search', params)
199+
: await callCluster.search(params);
200+
191201
const numberOfUniqueMonitors: number = result?.aggregations?.unique_monitors?.value ?? 0;
192202
const numberOfUniqueLocations: number = result?.aggregations?.unique_locations?.value ?? 0;
193203
const monitorNameStats: any = result?.aggregations?.monitor_name;

x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ const mockOptions = (
5656
services = alertsMock.createAlertServices(),
5757
state = {}
5858
): any => {
59+
services.scopedClusterClient = jest.fn() as any;
60+
5961
services.savedObjectsClient.get.mockResolvedValue({
6062
id: '',
6163
type: '',
@@ -282,7 +284,8 @@ describe('status check alert', () => {
282284
expect.assertions(5);
283285
toISOStringSpy.mockImplementation(() => 'foo date string');
284286
const mockGetter: jest.Mock<GetMonitorStatusResult[]> = jest.fn();
285-
mockGetter.mockReturnValue([
287+
288+
mockGetter.mockReturnValueOnce([
286289
{
287290
monitorId: 'first',
288291
location: 'harrisburg',
@@ -326,6 +329,7 @@ describe('status check alert', () => {
326329
const state = await alert.executor(options);
327330
const [{ value: alertInstanceMock }] = alertServices.alertInstanceFactory.mock.results;
328331
expect(mockGetter).toHaveBeenCalledTimes(1);
332+
329333
expect(mockGetter.mock.calls[0]).toMatchInlineSnapshot(`
330334
Array [
331335
Object {

x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts

Lines changed: 50 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@ import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants/alerts';
1212
import { commonStateTranslations, durationAnomalyTranslations } from './translations';
1313
import { AnomaliesTableRecord } from '../../../../ml/common/types/anomalies';
1414
import { getSeverityType } from '../../../../ml/common/util/anomaly_utils';
15-
import { savedObjectsAdapter } from '../saved_objects';
1615
import { UptimeCorePlugins } from '../adapters/framework';
1716
import { UptimeAlertTypeFactory } from './types';
1817
import { Ping } from '../../../common/runtime_types/ping';
1918
import { getMLJobId } from '../../../common/lib';
2019
import { getLatestMonitor } from '../requests/get_latest_monitor';
20+
import { uptimeAlertWrapper } from './uptime_alert_wrapper';
2121

2222
const { DURATION_ANOMALY } = ACTION_GROUP_DEFINITIONS;
2323

@@ -61,61 +61,58 @@ const getAnomalies = async (
6161
);
6262
};
6363

64-
export const durationAnomalyAlertFactory: UptimeAlertTypeFactory = (_server, _libs, plugins) => ({
65-
id: 'xpack.uptime.alerts.durationAnomaly',
66-
name: durationAnomalyTranslations.alertFactoryName,
67-
validate: {
68-
params: schema.object({
69-
monitorId: schema.string(),
70-
severity: schema.number(),
71-
}),
72-
},
73-
defaultActionGroupId: DURATION_ANOMALY.id,
74-
actionGroups: [
75-
{
76-
id: DURATION_ANOMALY.id,
77-
name: DURATION_ANOMALY.name,
64+
export const durationAnomalyAlertFactory: UptimeAlertTypeFactory = (_server, _libs, plugins) =>
65+
uptimeAlertWrapper({
66+
id: 'xpack.uptime.alerts.durationAnomaly',
67+
name: durationAnomalyTranslations.alertFactoryName,
68+
validate: {
69+
params: schema.object({
70+
monitorId: schema.string(),
71+
severity: schema.number(),
72+
}),
7873
},
79-
],
80-
actionVariables: {
81-
context: [],
82-
state: [...durationAnomalyTranslations.actionVariables, ...commonStateTranslations],
83-
},
84-
producer: 'uptime',
85-
async executor(options) {
86-
const {
87-
services: { alertInstanceFactory, callCluster, savedObjectsClient },
88-
state,
89-
params,
90-
} = options;
74+
defaultActionGroupId: DURATION_ANOMALY.id,
75+
actionGroups: [
76+
{
77+
id: DURATION_ANOMALY.id,
78+
name: DURATION_ANOMALY.name,
79+
},
80+
],
81+
actionVariables: {
82+
context: [],
83+
state: [...durationAnomalyTranslations.actionVariables, ...commonStateTranslations],
84+
},
85+
async executor({ options, esClient, savedObjectsClient, dynamicSettings }) {
86+
const {
87+
services: { alertInstanceFactory },
88+
state,
89+
params,
90+
} = options;
9191

92-
const { anomalies } =
93-
(await getAnomalies(plugins, savedObjectsClient, params, state.lastCheckedAt)) ?? {};
92+
const { anomalies } =
93+
(await getAnomalies(plugins, savedObjectsClient, params, state.lastCheckedAt)) ?? {};
9494

95-
const foundAnomalies = anomalies?.length > 0;
95+
const foundAnomalies = anomalies?.length > 0;
9696

97-
if (foundAnomalies) {
98-
const dynamicSettings = await savedObjectsAdapter.getUptimeDynamicSettings(
99-
savedObjectsClient
100-
);
101-
const monitorInfo = await getLatestMonitor({
102-
dynamicSettings,
103-
callES: callCluster,
104-
dateStart: 'now-15m',
105-
dateEnd: 'now',
106-
monitorId: params.monitorId,
107-
});
108-
anomalies.forEach((anomaly, index) => {
109-
const alertInstance = alertInstanceFactory(DURATION_ANOMALY.id + index);
110-
const summary = getAnomalySummary(anomaly, monitorInfo);
111-
alertInstance.replaceState({
112-
...updateState(state, false),
113-
...summary,
97+
if (foundAnomalies) {
98+
const monitorInfo = await getLatestMonitor({
99+
dynamicSettings,
100+
callES: esClient,
101+
dateStart: 'now-15m',
102+
dateEnd: 'now',
103+
monitorId: params.monitorId,
104+
});
105+
anomalies.forEach((anomaly, index) => {
106+
const alertInstance = alertInstanceFactory(DURATION_ANOMALY.id + index);
107+
const summary = getAnomalySummary(anomaly, monitorInfo);
108+
alertInstance.replaceState({
109+
...updateState(state, false),
110+
...summary,
111+
});
112+
alertInstance.scheduleActions(DURATION_ANOMALY.id);
114113
});
115-
alertInstance.scheduleActions(DURATION_ANOMALY.id);
116-
});
117-
}
114+
}
118115

119-
return updateState(state, foundAnomalies);
120-
},
121-
});
116+
return updateState(state, foundAnomalies);
117+
},
118+
});

0 commit comments

Comments
 (0)