From 75e71499786849705617ce188a05cd9f286b8649 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Wed, 11 Mar 2020 17:11:53 +0000 Subject: [PATCH 1/9] [ML] Typescripting client side endpoint functions --- .../annotations/annotation_flyout/index.tsx | 2 +- .../analytics_service/delete_analytics.ts | 2 +- .../analytics_service/get_analytics.test.ts | 2 +- .../analytics_service/get_analytics.ts | 4 +- .../analytics_service/stop_analytics.ts | 3 +- .../common/job_validator/validators.ts | 3 +- .../application/services/http_service.ts | 32 +- .../services/ml_api_service/annotations.ts | 6 +- .../ml_api_service/data_frame_analytics.js | 77 --- .../ml_api_service/data_frame_analytics.ts | 95 +++ .../services/ml_api_service/datavisualizer.js | 45 -- .../services/ml_api_service/datavisualizer.ts | 52 ++ .../ml_api_service/{filters.js => filters.ts} | 46 +- .../services/ml_api_service/index.ts | 643 ++++++++++++++++++ .../{index.d.ts => index_.d.ts} | 0 .../services/ml_api_service/jobs.ts | 268 ++++++++ .../services/ml_api_service/results.js | 89 --- .../services/ml_api_service/results.ts | 99 +++ .../timeseries_search_service.ts | 2 +- 19 files changed, 1206 insertions(+), 264 deletions(-) delete mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.js create mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts delete mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.js create mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts rename x-pack/legacy/plugins/ml/public/application/services/ml_api_service/{filters.js => filters.ts} (50%) create mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts rename x-pack/legacy/plugins/ml/public/application/services/ml_api_service/{index.d.ts => index_.d.ts} (100%) create mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts delete mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.js create mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts diff --git a/x-pack/legacy/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx b/x-pack/legacy/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx index 65fe36a7b611b..ceaf986b0d54f 100644 --- a/x-pack/legacy/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx +++ b/x-pack/legacy/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx @@ -77,7 +77,7 @@ class AnnotationFlyoutUI extends Component { const { annotation } = this.props; const toastNotifications = getToastNotifications(); - if (annotation === null) { + if (annotation === null || annotation._id === undefined) { return; } diff --git a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts index 3c0c3fa0df87c..7383f565bd673 100644 --- a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts +++ b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts @@ -19,7 +19,7 @@ export const deleteAnalytics = async (d: DataFrameAnalyticsListRow) => { const toastNotifications = getToastNotifications(); try { if (isDataFrameAnalyticsFailed(d.stats.state)) { - await ml.dataFrameAnalytics.stopDataFrameAnalytics(d.config.id, true, true); + await ml.dataFrameAnalytics.stopDataFrameAnalytics(d.config.id, true); } await ml.dataFrameAnalytics.deleteDataFrameAnalytics(d.config.id); toastNotifications.addSuccess( diff --git a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.test.ts b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.test.ts index 1aaddda358082..7e337684371cd 100644 --- a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.test.ts +++ b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { GetDataFrameAnalyticsStatsResponseOk } from '../../../../../services/ml_api_service'; +import { GetDataFrameAnalyticsStatsResponseOk } from '../../../../../services/ml_api_service/data_frame_analytics'; import { getAnalyticsJobsStats } from './get_analytics'; import { DATA_FRAME_TASK_STATE } from '../../components/analytics_list/common'; diff --git a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts index 1875216408c62..2a33691d0a75d 100644 --- a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts +++ b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts @@ -5,12 +5,12 @@ */ import { i18n } from '@kbn/i18n'; +import { ml } from '../../../../../services/ml_api_service'; import { GetDataFrameAnalyticsStatsResponse, GetDataFrameAnalyticsStatsResponseError, GetDataFrameAnalyticsStatsResponseOk, - ml, -} from '../../../../../services/ml_api_service'; +} from '../../../../../services/ml_api_service/data_frame_analytics'; import { DataFrameAnalyticsConfig, REFRESH_ANALYTICS_LIST_STATE, diff --git a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/stop_analytics.ts b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/stop_analytics.ts index c92c03c3b0f16..d277e3af1d5e6 100644 --- a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/stop_analytics.ts +++ b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/stop_analytics.ts @@ -20,8 +20,7 @@ export const stopAnalytics = async (d: DataFrameAnalyticsListRow) => { try { await ml.dataFrameAnalytics.stopDataFrameAnalytics( d.config.id, - isDataFrameAnalyticsFailed(d.stats.state), - true + isDataFrameAnalyticsFailed(d.stats.state) ); toastNotifications.addSuccess( i18n.translate('xpack.ml.dataframe.analyticsList.stopAnalyticsSuccessMessage', { diff --git a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts index 85018ab2f7944..ea7ba21699f60 100644 --- a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts +++ b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts @@ -12,6 +12,7 @@ import { ml, } from '../../../../services/ml_api_service'; import { JobCreator } from '../job_creator'; +import { CombinedJob } from '../../../../../../common/types/anomaly_detection_jobs'; export enum VALIDATOR_SEVERITY { ERROR, @@ -57,7 +58,7 @@ export function cardinalityValidator( return ml.validateCardinality$({ ...jobCreator.jobConfig, datafeed_config: jobCreator.datafeedConfig, - }); + } as CombinedJob); }), map(validationResults => { for (const validationResult of validationResults) { diff --git a/x-pack/legacy/plugins/ml/public/application/services/http_service.ts b/x-pack/legacy/plugins/ml/public/application/services/http_service.ts index 75db2470d77cc..976bab02a1eb5 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/http_service.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/http_service.ts @@ -5,7 +5,7 @@ */ import { Observable } from 'rxjs'; - +import { HttpFetchOptionsWithPath } from 'kibana/public'; import { getHttp } from '../util/dependency_cache'; function getResultHeaders(headers: HeadersInit): HeadersInit { @@ -16,29 +16,29 @@ function getResultHeaders(headers: HeadersInit): HeadersInit { } as HeadersInit; } -interface HttpOptions { - url: string; - method: string; - headers?: any; - data?: any; -} +// interface HttpOptions { +// url: string; +// method: string; +// headers?: any; +// data?: any; +// } /** * Function for making HTTP requests to Kibana's backend. * Wrapper for Kibana's HttpHandler. */ -export async function http(options: HttpOptions) { - if (!options?.url) { - throw new Error('URL is missing'); +export async function http(options: HttpFetchOptionsWithPath) { + if (!options?.path) { + throw new Error('URL path is missing'); } try { - let url = ''; - url = url + (options.url || ''); + let path = ''; + path = path + (options.path || ''); const headers = getResultHeaders(options.headers ?? {}); const allHeaders = options.headers === undefined ? headers : { ...options.headers, ...headers }; - const body = options.data === undefined ? null : JSON.stringify(options.data); + const body = options.body === undefined ? null : JSON.stringify(options.body); const payload: RequestInit = { method: options.method || 'GET', @@ -50,7 +50,7 @@ export async function http(options: HttpOptions) { payload.body = body; } - return await getHttp().fetch(url, payload); + return await getHttp().fetch(path, payload); } catch (e) { throw new Error(e); } @@ -64,7 +64,7 @@ interface RequestOptions extends RequestInit { * Function for making HTTP requests to Kibana's backend which returns an Observable * with request cancellation support. */ -export function http$(url: string, options: RequestOptions): Observable { +export function http$(path: string, options: RequestOptions): Observable { const requestInit: RequestInit = { ...options, credentials: 'same-origin', @@ -73,7 +73,7 @@ export function http$(url: string, options: RequestOptions): Observable { headers: getResultHeaders(options.headers ?? {}), }; - return fromHttpHandler(url, requestInit); + return fromHttpHandler(path, requestInit); } /** diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts index cc30d481a6355..28d3fbd642f33 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts @@ -22,14 +22,14 @@ export const annotations = { }, indexAnnotation(obj: any) { return http({ - url: `${basePath()}/annotations/index`, + path: `${basePath()}/annotations/index`, method: 'PUT', - data: obj, + body: obj, }); }, deleteAnnotation(id: string) { return http({ - url: `${basePath()}/annotations/delete/${id}`, + path: `${basePath()}/annotations/delete/${id}`, method: 'DELETE', }); }, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.js b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.js deleted file mode 100644 index 8a74cddce3f6d..0000000000000 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.js +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { http } from '../http_service'; - -import { basePath } from './index'; - -export const dataFrameAnalytics = { - getDataFrameAnalytics(analyticsId) { - const analyticsIdString = analyticsId !== undefined ? `/${analyticsId}` : ''; - return http({ - url: `${basePath()}/data_frame/analytics${analyticsIdString}`, - method: 'GET', - }); - }, - getDataFrameAnalyticsStats(analyticsId) { - if (analyticsId !== undefined) { - return http({ - url: `${basePath()}/data_frame/analytics/${analyticsId}/_stats`, - method: 'GET', - }); - } - - return http({ - url: `${basePath()}/data_frame/analytics/_stats`, - method: 'GET', - }); - }, - createDataFrameAnalytics(analyticsId, analyticsConfig) { - return http({ - url: `${basePath()}/data_frame/analytics/${analyticsId}`, - method: 'PUT', - data: analyticsConfig, - }); - }, - evaluateDataFrameAnalytics(evaluateConfig) { - return http({ - url: `${basePath()}/data_frame/_evaluate`, - method: 'POST', - data: evaluateConfig, - }); - }, - explainDataFrameAnalytics(jobConfig) { - return http({ - url: `${basePath()}/data_frame/analytics/_explain`, - method: 'POST', - data: jobConfig, - }); - }, - deleteDataFrameAnalytics(analyticsId) { - return http({ - url: `${basePath()}/data_frame/analytics/${analyticsId}`, - method: 'DELETE', - }); - }, - startDataFrameAnalytics(analyticsId) { - return http({ - url: `${basePath()}/data_frame/analytics/${analyticsId}/_start`, - method: 'POST', - }); - }, - stopDataFrameAnalytics(analyticsId, force = false) { - return http({ - url: `${basePath()}/data_frame/analytics/${analyticsId}/_stop?force=${force}`, - method: 'POST', - }); - }, - getAnalyticsAuditMessages(analyticsId) { - return http({ - url: `${basePath()}/data_frame/analytics/${analyticsId}/messages`, - method: 'GET', - }); - }, -}; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts new file mode 100644 index 0000000000000..80af9a66fa44c --- /dev/null +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts @@ -0,0 +1,95 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { http } from '../http_service'; + +import { basePath } from './index'; +import { DataFrameAnalyticsStats } from '../../data_frame_analytics/pages/analytics_management/components/analytics_list/common'; + +export interface GetDataFrameAnalyticsStatsResponseOk { + node_failures?: object; + count: number; + data_frame_analytics: DataFrameAnalyticsStats[]; +} + +export interface GetDataFrameAnalyticsStatsResponseError { + statusCode: number; + error: string; + message: string; +} + +export type GetDataFrameAnalyticsStatsResponse = + | GetDataFrameAnalyticsStatsResponseOk + | GetDataFrameAnalyticsStatsResponseError; + +export const dataFrameAnalytics = { + getDataFrameAnalytics(analyticsId?: string): Promise { + const analyticsIdString = analyticsId !== undefined ? `/${analyticsId}` : ''; + return http({ + path: `${basePath()}/data_frame/analytics${analyticsIdString}`, + method: 'GET', + }); + }, + getDataFrameAnalyticsStats(analyticsId?: string): Promise { + if (analyticsId !== undefined) { + return http({ + path: `${basePath()}/data_frame/analytics/${analyticsId}/_stats`, + method: 'GET', + }); + } + + return http({ + path: `${basePath()}/data_frame/analytics/_stats`, + method: 'GET', + }); + }, + createDataFrameAnalytics(analyticsId: string, analyticsConfig: any): Promise { + return http({ + path: `${basePath()}/data_frame/analytics/${analyticsId}`, + method: 'PUT', + body: analyticsConfig, + }); + }, + evaluateDataFrameAnalytics(evaluateConfig: any): Promise { + return http({ + path: `${basePath()}/data_frame/_evaluate`, + method: 'POST', + body: evaluateConfig, + }); + }, + explainDataFrameAnalytics(jobConfig: any): Promise { + return http({ + path: `${basePath()}/data_frame/analytics/_explain`, + method: 'POST', + body: jobConfig, + }); + }, + deleteDataFrameAnalytics(analyticsId: string): Promise { + return http({ + path: `${basePath()}/data_frame/analytics/${analyticsId}`, + method: 'DELETE', + }); + }, + startDataFrameAnalytics(analyticsId: string): Promise { + return http({ + path: `${basePath()}/data_frame/analytics/${analyticsId}/_start`, + method: 'POST', + }); + }, + stopDataFrameAnalytics(analyticsId: string, force: boolean = false): Promise { + return http({ + path: `${basePath()}/data_frame/analytics/${analyticsId}/_stop`, + method: 'POST', + query: { force }, + }); + }, + getAnalyticsAuditMessages(analyticsId: string): Promise { + return http({ + path: `${basePath()}/data_frame/analytics/${analyticsId}/messages`, + method: 'GET', + }); + }, +}; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.js b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.js deleted file mode 100644 index 364fa57ba7d6b..0000000000000 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.js +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { http } from '../http_service'; - -import { basePath } from './index'; - -export const fileDatavisualizer = { - analyzeFile(obj, params = {}) { - let paramString = ''; - if (Object.keys(params).length) { - paramString = '?'; - for (const p in params) { - if (params.hasOwnProperty(p)) { - paramString += `&${p}=${params[p]}`; - } - } - } - return http({ - url: `${basePath()}/file_data_visualizer/analyze_file${paramString}`, - method: 'POST', - data: obj, - }); - }, - - import(obj) { - const paramString = obj.id !== undefined ? `?id=${obj.id}` : ''; - const { index, data, settings, mappings, ingestPipeline } = obj; - - return http({ - url: `${basePath()}/file_data_visualizer/import${paramString}`, - method: 'POST', - data: { - index, - data, - settings, - mappings, - ingestPipeline, - }, - }); - }, -}; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts new file mode 100644 index 0000000000000..dabdb0156f2e3 --- /dev/null +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts @@ -0,0 +1,52 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { http } from '../http_service'; + +import { basePath } from './index'; + +export const fileDatavisualizer = { + analyzeFile(file: string, params: Record = {}) { + return http({ + path: `${basePath()}/file_data_visualizer/analyze_file`, + method: 'POST', + body: file, + query: params, + }); + }, + + import({ + id, + index, + data, + settings, + mappings, + ingestPipeline, + }: { + id: string; + index: string; + data: any; + settings: any; + mappings: any; + ingestPipeline: any; + }) { + const query = id !== undefined ? { id } : {}; + const body = JSON.stringify({ + index, + data, + settings, + mappings, + ingestPipeline, + }); + + return http({ + path: `${basePath()}/file_data_visualizer/import`, + method: 'POST', + query, + body, + }); + }, +}; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.js b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.ts similarity index 50% rename from x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.js rename to x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.ts index 010a531a192f1..bf3a53f2d2a1c 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.js +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.ts @@ -12,55 +12,51 @@ import { http } from '../http_service'; import { basePath } from './index'; export const filters = { - filters(obj) { + filters(obj?: { filterId?: string }) { const filterId = obj && obj.filterId ? `/${obj.filterId}` : ''; return http({ - url: `${basePath()}/filters${filterId}`, + path: `${basePath()}/filters${filterId}`, method: 'GET', }); }, filtersStats() { return http({ - url: `${basePath()}/filters/_stats`, + path: `${basePath()}/filters/_stats`, method: 'GET', }); }, - addFilter(filterId, description, items) { + addFilter(filterId: string, description: string, items: string[]) { + const body = JSON.stringify({ + filterId, + description, + items, + }); return http({ - url: `${basePath()}/filters`, + path: `${basePath()}/filters`, method: 'PUT', - data: { - filterId, - description, - items, - }, + body, }); }, - updateFilter(filterId, description, addItems, removeItems) { - const data = {}; - if (description !== undefined) { - data.description = description; - } - if (addItems !== undefined) { - data.addItems = addItems; - } - if (removeItems !== undefined) { - data.removeItems = removeItems; - } + updateFilter(filterId: string, description: string, addItems: string[], removeItems: string[]) { + const body = JSON.stringify({ + ...(description !== undefined ? { description } : {}), + ...(addItems !== undefined ? { addItems } : {}), + ...(removeItems !== undefined ? { removeItems } : {}), + }); return http({ - url: `${basePath()}/filters/${filterId}`, + path: `${basePath()}/filters/${filterId}`, method: 'PUT', - data, + body, }); }, - deleteFilter(filterId) { + deleteFilter(filterId: string) { return http({ - url: `${basePath()}/filters/${filterId}`, + path: `${basePath()}/filters/${filterId}`, method: 'DELETE', }); }, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts new file mode 100644 index 0000000000000..56de0566f0a72 --- /dev/null +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts @@ -0,0 +1,643 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Observable } from 'rxjs'; +import { http, http$ } from '../http_service'; + +import { annotations } from './annotations'; +import { dataFrameAnalytics } from './data_frame_analytics'; +import { filters } from './filters'; +import { results } from './results'; +import { jobs } from './jobs'; +import { fileDatavisualizer } from './datavisualizer'; +import { MlServerDefaults, MlServerLimits } from '../ml_server_info'; + +import { PrivilegesResponse } from '../../../../common/types/privileges'; +import { Calendar, CalendarId, UpdateCalendar } from '../../../../common/types/calendars'; +import { CombinedJob } from '../../../../common/types/anomaly_detection_jobs'; +import { ES_AGGREGATION } from '../../../../common/constants/aggregation_types'; + +export interface MlInfoResponse { + defaults: MlServerDefaults; + limits: MlServerLimits; + native_code: { + build_hash: string; + version: string; + }; + upgrade_mode: boolean; + cloudId?: string; +} + +// TODO This is not a complete representation of all methods of `ml.*`. +// It just satisfies needs for other parts of the code area which use +// TypeScript and rely on the methods typed in here. +// This allows the import of `ml` into TypeScript code. +interface EsIndex { + name: string; +} + +export interface BucketSpanEstimatorData { + aggTypes: Array; + duration: { + start: number; + end: number; + }; + fields: Array; + index: string; + query: any; + splitField: string | undefined; + timeField: string | undefined; +} + +export interface BucketSpanEstimatorResponse { + name: string; + ms: number; + error?: boolean; + message?: { msg: string } | string; +} + +export interface GetTimeFieldRangeResponse { + success: boolean; + start: { epoch: number; string: string }; + end: { epoch: number; string: string }; +} + +export interface SuccessCardinality { + id: 'success_cardinality'; +} + +export interface CardinalityModelPlotHigh { + id: 'cardinality_model_plot_high'; + modelPlotCardinality: number; +} + +export type CardinalityValidationResult = SuccessCardinality | CardinalityModelPlotHigh; +export type CardinalityValidationResults = CardinalityValidationResult[]; + +export function basePath() { + return '/api/ml'; +} + +export const ml = { + getJobs(obj?: { jobId?: string }) { + const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; + return http({ + path: `${basePath()}/anomaly_detectors${jobId}`, + }); + }, + + getJobStats(obj: { jobId?: string }) { + const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; + return http({ + path: `${basePath()}/anomaly_detectors${jobId}/_stats`, + }); + }, + + addJob({ jobId, job }: { jobId: string; job: any }) { + const body = JSON.stringify({ job }); + return http({ + path: `${basePath()}/anomaly_detectors/${jobId}`, + method: 'PUT', + body, + }); + }, + + openJob({ jobId }: { jobId: string }) { + return http({ + path: `${basePath()}/anomaly_detectors/${jobId}/_open`, + method: 'POST', + }); + }, + + closeJob({ jobId }: { jobId: string }) { + return http({ + path: `${basePath()}/anomaly_detectors/${jobId}/_close`, + method: 'POST', + }); + }, + + deleteJob({ jobId }: { jobId: string }) { + return http({ + path: `${basePath()}/anomaly_detectors/${jobId}`, + method: 'DELETE', + }); + }, + + forceDeleteJob({ jobId }: { jobId: string }) { + return http({ + path: `${basePath()}/anomaly_detectors/${jobId}?force=true`, + method: 'DELETE', + }); + }, + + updateJob({ jobId, job }: { jobId: string; job: any }) { + const body = JSON.stringify({ job }); + return http({ + path: `${basePath()}/anomaly_detectors/${jobId}/_update`, + method: 'POST', + body, + }); + }, + + estimateBucketSpan(obj: BucketSpanEstimatorData): Promise { + const body = JSON.stringify(obj); + return http({ + path: `${basePath()}/validate/estimate_bucket_span`, + method: 'POST', + body, + }); + }, + + validateJob({ job }: { job: any }) { + const body = JSON.stringify({ job }); + return http({ + path: `${basePath()}/validate/job`, + method: 'POST', + body, + }); + }, + + validateCardinality$(job: CombinedJob): Observable { + const body = JSON.stringify({ job }); + return http$(`${basePath()}/validate/cardinality`, { + method: 'POST', + body, + }); + }, + + getDatafeeds(obj: { datafeedId: string }) { + const datafeedId = obj && obj.datafeedId ? `/${obj.datafeedId}` : ''; + return http({ + path: `${basePath()}/datafeeds${datafeedId}`, + }); + }, + + getDatafeedStats(obj: { datafeedId: string }) { + const datafeedId = obj && obj.datafeedId ? `/${obj.datafeedId}` : ''; + return http({ + path: `${basePath()}/datafeeds${datafeedId}/_stats`, + }); + }, + + addDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: any }) { + const body = JSON.stringify({ datafeedConfig }); + return http({ + path: `${basePath()}/datafeeds/${datafeedId}`, + method: 'PUT', + body, + }); + }, + + updateDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: any }) { + const body = JSON.stringify({ datafeedConfig }); + return http({ + path: `${basePath()}/datafeeds/${datafeedId}/_update`, + method: 'POST', + body, + }); + }, + + deleteDatafeed({ datafeedId }: { datafeedId: string }) { + return http({ + path: `${basePath()}/datafeeds/${datafeedId}`, + method: 'DELETE', + }); + }, + + forceDeleteDatafeed({ datafeedId }: { datafeedId: string }) { + return http({ + path: `${basePath()}/datafeeds/${datafeedId}?force=true`, + method: 'DELETE', + }); + }, + + startDatafeed({ datafeedId, start, end }: { datafeedId: string; start: number; end: number }) { + const body = JSON.stringify({ + ...(start !== undefined ? { start } : {}), + ...(end !== undefined ? { end } : {}), + }); + + return http({ + path: `${basePath()}/datafeeds/${datafeedId}/_start`, + method: 'POST', + body, + }); + }, + + stopDatafeed({ datafeedId }: { datafeedId: string }) { + return http({ + path: `${basePath()}/datafeeds/${datafeedId}/_stop`, + method: 'POST', + }); + }, + + datafeedPreview({ datafeedId }: { datafeedId: string }) { + return http({ + path: `${basePath()}/datafeeds/${datafeedId}/_preview`, + method: 'GET', + }); + }, + + validateDetector({ detector }: { detector: any }) { + const body = JSON.stringify({ detector }); + return http({ + path: `${basePath()}/anomaly_detectors/_validate/detector`, + method: 'POST', + body, + }); + }, + + forecast({ jobId, duration }: { jobId: string; duration?: string }) { + const body = JSON.stringify({ + ...(duration !== undefined ? { duration } : {}), + }); + + return http({ + path: `${basePath()}/anomaly_detectors/${jobId}/_forecast`, + method: 'POST', + body, + }); + }, + + overallBuckets({ + jobId, + topN, + bucketSpan, + start, + end, + }: { + jobId: string; + topN: string; + bucketSpan: string; + start: number; + end: number; + }) { + const body = JSON.stringify({ topN, bucketSpan, start, end }); + return http({ + path: `${basePath()}/anomaly_detectors/${jobId}/results/overall_buckets`, + method: 'POST', + body, + }); + }, + + hasPrivileges(obj: any) { + const body = JSON.stringify(obj); + return http({ + path: `${basePath()}/_has_privileges`, + method: 'POST', + body, + }); + }, + + checkMlPrivileges(): Promise { + return http({ + path: `${basePath()}/ml_capabilities`, + method: 'GET', + }); + }, + + checkManageMLPrivileges(): Promise { + return http({ + path: `${basePath()}/ml_capabilities?ignoreSpaces=true`, + method: 'GET', + }); + }, + + getNotificationSettings() { + return http({ + path: `${basePath()}/notification_settings`, + method: 'GET', + }); + }, + + getFieldCaps({ index, fields }: { index: string; fields: string[] }) { + const body = JSON.stringify({ + ...(index !== undefined ? { index } : {}), + ...(fields !== undefined ? { fields } : {}), + }); + + return http({ + path: `${basePath()}/indices/field_caps`, + method: 'POST', + body, + }); + }, + + recognizeIndex({ indexPatternTitle }: { indexPatternTitle: string }) { + return http({ + path: `${basePath()}/modules/recognize/${indexPatternTitle}`, + method: 'GET', + }); + }, + + listDataRecognizerModules() { + return http({ + path: `${basePath()}/modules/get_module`, + method: 'GET', + }); + }, + + getDataRecognizerModule({ moduleId }: { moduleId: string }) { + return http({ + path: `${basePath()}/modules/get_module/${moduleId}`, + method: 'GET', + }); + }, + + dataRecognizerModuleJobsExist({ moduleId }: { moduleId: string }) { + return http({ + path: `${basePath()}/modules/jobs_exist/${moduleId}`, + method: 'GET', + }); + }, + + setupDataRecognizerConfig({ + moduleId, + prefix, + groups, + indexPatternName, + query, + useDedicatedIndex, + startDatafeed, + start, + end, + jobOverrides, + }: { + moduleId: string; + prefix?: string; + groups?: string[]; + indexPatternName?: string; + query?: any; + useDedicatedIndex?: boolean; + startDatafeed?: boolean; + start?: number; + end?: number; + jobOverrides?: any; + }) { + const body = JSON.stringify({ + prefix, + groups, + indexPatternName, + query, + useDedicatedIndex, + startDatafeed, + start, + end, + jobOverrides, + }); + + return http({ + path: `${basePath()}/modules/setup/${moduleId}`, + method: 'POST', + body, + }); + }, + + getVisualizerFieldStats({ + indexPatternTitle, + query, + timeFieldName, + earliest, + latest, + samplerShardSize, + interval, + fields, + maxExamples, + }: { + indexPatternTitle: string; + query: any; + timeFieldName?: string; + earliest?: number; + latest?: number; + samplerShardSize?: number; + interval?: string; + fields?: any[]; + maxExamples?: number; + }) { + const body = JSON.stringify({ + query, + timeFieldName, + earliest, + latest, + samplerShardSize, + interval, + fields, + maxExamples, + }); + + return http({ + path: `${basePath()}/data_visualizer/get_field_stats/${indexPatternTitle}`, + method: 'POST', + body, + }); + }, + + getVisualizerOverallStats({ + indexPatternTitle, + query, + timeFieldName, + earliest, + latest, + samplerShardSize, + aggregatableFields, + nonAggregatableFields, + }: { + indexPatternTitle: string; + query: any; + timeFieldName?: string; + earliest?: number; + latest?: number; + samplerShardSize?: number; + aggregatableFields: string[]; + nonAggregatableFields: string[]; + }) { + const body = JSON.stringify({ + query, + timeFieldName, + earliest, + latest, + samplerShardSize, + aggregatableFields, + nonAggregatableFields, + }); + + return http({ + path: `${basePath()}/data_visualizer/get_overall_stats/${indexPatternTitle}`, + method: 'POST', + body, + }); + }, + + /** + * Gets a list of calendars + * @param obj + * @returns {Promise} + */ + calendars(obj?: { calendarId?: CalendarId; calendarIds?: CalendarId[] }): Promise { + const { calendarId, calendarIds } = obj || {}; + let calendarIdsPathComponent = ''; + if (calendarId) { + calendarIdsPathComponent = `/${calendarId}`; + } else if (calendarIds) { + calendarIdsPathComponent = `/${calendarIds.join(',')}`; + } + return http({ + path: `${basePath()}/calendars${calendarIdsPathComponent}`, + method: 'GET', + }); + }, + + addCalendar(obj: any) { + const body = JSON.stringify(obj); + return http({ + path: `${basePath()}/calendars`, + method: 'PUT', + body, + }); + }, + + updateCalendar(obj: UpdateCalendar) { + const calendarId = obj && obj.calendarId ? `/${obj.calendarId}` : ''; + const body = JSON.stringify(obj); + return http({ + path: `${basePath()}/calendars${calendarId}`, + method: 'PUT', + body, + }); + }, + + deleteCalendar({ calendarId }: { calendarId?: string }) { + return http({ + path: `${basePath()}/calendars/${calendarId}`, + method: 'DELETE', + }); + }, + + mlNodeCount(): Promise<{ count: number }> { + return http({ + path: `${basePath()}/ml_node_count`, + method: 'GET', + }); + }, + + mlInfo(): Promise { + return http({ + path: `${basePath()}/info`, + method: 'GET', + }); + }, + + calculateModelMemoryLimit({ + indexPattern, + splitFieldName, + query, + fieldNames, + influencerNames, + timeFieldName, + earliestMs, + latestMs, + }: { + indexPattern: string; + splitFieldName: string; + query: any; + fieldNames: string[]; + influencerNames: string[]; + timeFieldName: string; + earliestMs: number; + latestMs: number; + }): Promise<{ modelMemoryLimit: string }> { + const body = JSON.stringify({ + indexPattern, + splitFieldName, + query, + fieldNames, + influencerNames, + timeFieldName, + earliestMs, + latestMs, + }); + + return http({ + path: `${basePath()}/validate/calculate_model_memory_limit`, + method: 'POST', + body, + }); + }, + + getCardinalityOfFields({ + index, + fieldNames, + query, + timeFieldName, + earliestMs, + latestMs, + }: { + index: string; + fieldNames: string[]; + query: any; + timeFieldName: string; + earliestMs: number; + latestMs: number; + }) { + const body = JSON.stringify({ index, fieldNames, query, timeFieldName, earliestMs, latestMs }); + + return http({ + path: `${basePath()}/fields_service/field_cardinality`, + method: 'POST', + body, + }); + }, + + getTimeFieldRange({ + index, + timeFieldName, + query, + }: { + index: string; + timeFieldName?: string; + query: any; + }): Promise { + const body = JSON.stringify({ index, timeFieldName, query }); + + return http({ + path: `${basePath()}/fields_service/time_field_range`, + method: 'POST', + body, + }); + }, + + esSearch(obj: any): Promise { + const body = JSON.stringify(obj); + return http({ + path: `${basePath()}/es_search`, + method: 'POST', + body, + }); + }, + + esSearch$(obj: any): Observable { + const body = JSON.stringify(obj); + return http$(`${basePath()}/es_search`, { + method: 'POST', + body, + }); + }, + + getIndices(): Promise { + const tempBasePath = '/api'; + return http({ + path: `${tempBasePath}/index_management/indices`, + method: 'GET', + }); + }, + + annotations, + dataFrameAnalytics, + filters, + results, + jobs, + fileDatavisualizer, +}; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.d.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index_.d.ts similarity index 100% rename from x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.d.ts rename to x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index_.d.ts diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts new file mode 100644 index 0000000000000..0d3164fb4bfe6 --- /dev/null +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts @@ -0,0 +1,268 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { http } from '../http_service'; + +import { basePath } from './index'; +import { Dictionary } from '../../../../common/types/common'; +import { MlJobWithTimeRange, MlSummaryJobs } from '../../../../common/types/anomaly_detection_jobs'; +import { JobMessage } from '../../../../common/types/audit_message'; +import { AggFieldNamePair } from '../../../../common/types/fields'; +import { ExistingJobsAndGroups } from '../job_service'; +import { + CategorizationAnalyzer, + CategoryFieldExample, + FieldExampleCheck, +} from '../../../../common/types/categories'; +import { CATEGORY_EXAMPLES_VALIDATION_STATUS } from '../../../../common/constants/new_job'; +import { Category } from '../../../../common/types/categories'; + +export const jobs = { + jobsSummary(jobIds: string[]): Promise { + const body = JSON.stringify({ jobIds }); + return http({ + path: `${basePath()}/jobs/jobs_summary`, + method: 'POST', + body, + }); + }, + + jobsWithTimerange( + dateFormatTz: string + ): Promise<{ jobs: MlJobWithTimeRange[]; jobsMap: Dictionary }> { + const body = JSON.stringify({ dateFormatTz }); + return http({ + path: `${basePath()}/jobs/jobs_with_time_range`, + method: 'POST', + body, + }); + }, + + jobs(jobIds: string[]) { + const body = JSON.stringify({ jobIds }); + return http({ + path: `${basePath()}/jobs/jobs`, + method: 'POST', + body, + }); + }, + + groups() { + return http({ + path: `${basePath()}/jobs/groups`, + method: 'GET', + }); + }, + + updateGroups(updatedJobs: string[]) { + const body = JSON.stringify({ updatedJobs }); + return http({ + path: `${basePath()}/jobs/update_groups`, + method: 'POST', + body, + }); + }, + + forceStartDatafeeds(datafeedIds: string[], start: string, end: string) { + const body = JSON.stringify({ + datafeedIds, + start, + end, + }); + + return http({ + path: `${basePath()}/jobs/force_start_datafeeds`, + method: 'POST', + body, + }); + }, + + stopDatafeeds(datafeedIds: string[]) { + const body = JSON.stringify({ datafeedIds }); + return http({ + path: `${basePath()}/jobs/stop_datafeeds`, + method: 'POST', + body, + }); + }, + + deleteJobs(jobIds: string[]) { + const body = JSON.stringify({ jobIds }); + return http({ + path: `${basePath()}/jobs/delete_jobs`, + method: 'POST', + body, + }); + }, + + closeJobs(jobIds: string[]) { + const body = JSON.stringify({ jobIds }); + return http({ + path: `${basePath()}/jobs/close_jobs`, + method: 'POST', + body, + }); + }, + + jobAuditMessages(jobId: string, from?: number): Promise { + const jobIdString = jobId !== undefined ? `/${jobId}` : ''; + const query = from !== undefined ? { from } : {}; + return http({ + path: `${basePath()}/job_audit_messages/messages${jobIdString}`, + method: 'GET', + query, + }); + }, + + deletingJobTasks() { + return http({ + path: `${basePath()}/jobs/deleting_jobs_tasks`, + method: 'GET', + }); + }, + + jobsExist(jobIds: string[]) { + const body = JSON.stringify({ jobIds }); + return http({ + path: `${basePath()}/jobs/jobs_exist`, + method: 'POST', + body, + }); + }, + + newJobCaps(indexPatternTitle: string, isRollup: boolean = false) { + const query = isRollup === true ? { rollup: true } : {}; + return http({ + path: `${basePath()}/jobs/new_job_caps/${indexPatternTitle}`, + method: 'GET', + query, + }); + }, + + newJobLineChart( + indexPatternTitle: string, + timeField: string, + start: number, + end: number, + intervalMs: number, + query: any, + aggFieldNamePairs: AggFieldNamePair[], + splitFieldName: string | null, + splitFieldValue: string | null + ) { + const body = JSON.stringify({ + indexPatternTitle, + timeField, + start, + end, + intervalMs, + query, + aggFieldNamePairs, + splitFieldName, + splitFieldValue, + }); + return http({ + path: `${basePath()}/jobs/new_job_line_chart`, + method: 'POST', + body, + }); + }, + + newJobPopulationsChart( + indexPatternTitle: string, + timeField: string, + start: number, + end: number, + intervalMs: number, + query: any, + aggFieldNamePairs: AggFieldNamePair[], + splitFieldName: string + ) { + const body = JSON.stringify({ + indexPatternTitle, + timeField, + start, + end, + intervalMs, + query, + aggFieldNamePairs, + splitFieldName, + }); + return http({ + path: `${basePath()}/jobs/new_job_population_chart`, + method: 'POST', + body, + }); + }, + + getAllJobAndGroupIds(): Promise { + return http({ + path: `${basePath()}/jobs/all_jobs_and_group_ids`, + method: 'GET', + }); + }, + + getLookBackProgress( + jobId: string, + start: number, + end: number + ): Promise<{ progress: number; isRunning: boolean; isJobClosed: boolean }> { + const body = JSON.stringify({ + jobId, + start, + end, + }); + return http({ + path: `${basePath()}/jobs/look_back_progress`, + method: 'POST', + body, + }); + }, + + categorizationFieldExamples( + indexPatternTitle: string, + query: any, + size: number, + field: string, + timeField: string, + start: number, + end: number, + analyzer: CategorizationAnalyzer + ): Promise<{ + examples: CategoryFieldExample[]; + sampleSize: number; + overallValidStatus: CATEGORY_EXAMPLES_VALIDATION_STATUS; + validationChecks: FieldExampleCheck[]; + }> { + const body = JSON.stringify({ + indexPatternTitle, + query, + size, + field, + timeField, + start, + end, + analyzer, + }); + return http({ + path: `${basePath()}/jobs/categorization_field_examples`, + method: 'POST', + body, + }); + }, + + topCategories( + jobId: string, + count: number + ): Promise<{ total: number; categories: Array<{ count?: number; category: Category }> }> { + const body = JSON.stringify({ jobId, count }); + return http({ + path: `${basePath()}/jobs/top_categories`, + method: 'POST', + body, + }); + }, +}; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.js b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.js deleted file mode 100644 index e770e80f4c4d9..0000000000000 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.js +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -// Service for obtaining data for the ML Results dashboards. - -import { http, http$ } from '../http_service'; - -import { basePath } from './index'; - -export const results = { - getAnomaliesTableData( - jobIds, - criteriaFields, - influencers, - aggregationInterval, - threshold, - earliestMs, - latestMs, - dateFormatTz, - maxRecords, - maxExamples, - influencersFilterQuery - ) { - return http$(`${basePath()}/results/anomalies_table_data`, { - method: 'POST', - body: { - jobIds, - criteriaFields, - influencers, - aggregationInterval, - threshold, - earliestMs, - latestMs, - dateFormatTz, - maxRecords, - maxExamples, - influencersFilterQuery, - }, - }); - }, - - getMaxAnomalyScore(jobIds, earliestMs, latestMs) { - return http({ - url: `${basePath()}/results/max_anomaly_score`, - method: 'POST', - data: { - jobIds, - earliestMs, - latestMs, - }, - }); - }, - - getCategoryDefinition(jobId, categoryId) { - return http({ - url: `${basePath()}/results/category_definition`, - method: 'POST', - data: { jobId, categoryId }, - }); - }, - - getCategoryExamples(jobId, categoryIds, maxExamples) { - return http({ - url: `${basePath()}/results/category_examples`, - method: 'POST', - data: { - jobId, - categoryIds, - maxExamples, - }, - }); - }, - - fetchPartitionFieldsValues(jobId, searchTerm, criteriaFields, earliestMs, latestMs) { - return http$(`${basePath()}/results/partition_fields_values`, { - method: 'POST', - body: { - jobId, - searchTerm, - criteriaFields, - earliestMs, - latestMs, - }, - }); - }, -}; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts new file mode 100644 index 0000000000000..e61c5676912dc --- /dev/null +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts @@ -0,0 +1,99 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +// Service for obtaining data for the ML Results dashboards. + +import { Observable } from 'rxjs'; +import { http, http$ } from '../http_service'; + +import { basePath } from './index'; + +import { JobId } from '../../../../common/types/anomaly_detection_jobs'; +import { PartitionFieldsDefinition } from '../results_service/result_service_rx'; + +export const results = { + getAnomaliesTableData( + jobIds: string[], + criteriaFields: string[], + influencers: string[], + aggregationInterval: string, + threshold: number, + earliestMs: number, + latestMs: number, + dateFormatTz: string, + maxRecords: number, + maxExamples: number, + influencersFilterQuery: any + ) { + const body = JSON.stringify({ + jobIds, + criteriaFields, + influencers, + aggregationInterval, + threshold, + earliestMs, + latestMs, + dateFormatTz, + maxRecords, + maxExamples, + influencersFilterQuery, + }); + + return http$(`${basePath()}/results/anomalies_table_data`, { + method: 'POST', + body, + }); + }, + + getMaxAnomalyScore(jobIds: string[], earliestMs: number, latestMs: number) { + const body = JSON.stringify({ + jobIds, + earliestMs, + latestMs, + }); + return http({ + path: `${basePath()}/results/max_anomaly_score`, + method: 'POST', + body, + }); + }, + + getCategoryDefinition(jobId: string, categoryId: string) { + const body = JSON.stringify({ jobId, categoryId }); + return http({ + path: `${basePath()}/results/category_definition`, + method: 'POST', + body, + }); + }, + + getCategoryExamples(jobId: string, categoryIds: string[], maxExamples: number) { + const body = JSON.stringify({ + jobId, + categoryIds, + maxExamples, + }); + return http({ + path: `${basePath()}/results/category_examples`, + method: 'POST', + body, + }); + }, + + fetchPartitionFieldsValues( + jobId: JobId, + searchTerm: Record, + criteriaFields: Array<{ fieldName: string; fieldValue: any }>, + earliestMs: number, + latestMs: number + ): Observable { + const body = JSON.stringify({ jobId, searchTerm, criteriaFields, earliestMs, latestMs }); + return http$(`${basePath()}/results/partition_fields_values`, { + method: 'POST', + body, + }); + }, +}; diff --git a/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts b/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts index 978f5f68d9d8d..db5ff2ad91910 100644 --- a/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts +++ b/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts @@ -138,7 +138,7 @@ function getChartDetails( obj.results.entityData.entities = entityFields; resolve(obj); } else { - const entityFieldNames = _.map(blankEntityFields, 'fieldName'); + const entityFieldNames: string[] = _.map(blankEntityFields, 'fieldName'); ml.getCardinalityOfFields({ index: chartConfig.datafeedConfig.indices, fieldNames: entityFieldNames, From 7341091616c88001331e3139ffcf94db68818ddf Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Wed, 11 Mar 2020 17:46:44 +0000 Subject: [PATCH 2/9] type clean up --- .../services/ml_api_service/index.js | 472 ------------------ .../services/ml_api_service/index.ts | 36 +- .../services/ml_api_service/index_.d.ts | 229 --------- .../services/ml_api_service/jobs.js | 246 --------- 4 files changed, 17 insertions(+), 966 deletions(-) delete mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.js delete mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index_.d.ts delete mode 100644 x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.js diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.js b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.js deleted file mode 100644 index 858fbd6959986..0000000000000 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.js +++ /dev/null @@ -1,472 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { pick } from 'lodash'; -import { http, http$ } from '../http_service'; - -import { annotations } from './annotations'; -import { dataFrameAnalytics } from './data_frame_analytics'; -import { filters } from './filters'; -import { results } from './results'; -import { jobs } from './jobs'; -import { fileDatavisualizer } from './datavisualizer'; - -export function basePath() { - return '/api/ml'; -} - -export const ml = { - getJobs(obj) { - const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; - return http({ - url: `${basePath()}/anomaly_detectors${jobId}`, - }); - }, - - getJobStats(obj) { - const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; - return http({ - url: `${basePath()}/anomaly_detectors${jobId}/_stats`, - }); - }, - - addJob(obj) { - return http({ - url: `${basePath()}/anomaly_detectors/${obj.jobId}`, - method: 'PUT', - data: obj.job, - }); - }, - - openJob(obj) { - return http({ - url: `${basePath()}/anomaly_detectors/${obj.jobId}/_open`, - method: 'POST', - }); - }, - - closeJob(obj) { - return http({ - url: `${basePath()}/anomaly_detectors/${obj.jobId}/_close`, - method: 'POST', - }); - }, - - deleteJob(obj) { - return http({ - url: `${basePath()}/anomaly_detectors/${obj.jobId}`, - method: 'DELETE', - }); - }, - - forceDeleteJob(obj) { - return http({ - url: `${basePath()}/anomaly_detectors/${obj.jobId}?force=true`, - method: 'DELETE', - }); - }, - - updateJob(obj) { - return http({ - url: `${basePath()}/anomaly_detectors/${obj.jobId}/_update`, - method: 'POST', - data: obj.job, - }); - }, - - estimateBucketSpan(obj) { - return http({ - url: `${basePath()}/validate/estimate_bucket_span`, - method: 'POST', - data: obj, - }); - }, - - validateJob(obj) { - return http({ - url: `${basePath()}/validate/job`, - method: 'POST', - data: obj, - }); - }, - - validateCardinality$(obj) { - return http$(`${basePath()}/validate/cardinality`, { - method: 'POST', - body: obj, - }); - }, - - getDatafeeds(obj) { - const datafeedId = obj && obj.datafeedId ? `/${obj.datafeedId}` : ''; - return http({ - url: `${basePath()}/datafeeds${datafeedId}`, - }); - }, - - getDatafeedStats(obj) { - const datafeedId = obj && obj.datafeedId ? `/${obj.datafeedId}` : ''; - return http({ - url: `${basePath()}/datafeeds${datafeedId}/_stats`, - }); - }, - - addDatafeed(obj) { - return http({ - url: `${basePath()}/datafeeds/${obj.datafeedId}`, - method: 'PUT', - data: obj.datafeedConfig, - }); - }, - - updateDatafeed(obj) { - return http({ - url: `${basePath()}/datafeeds/${obj.datafeedId}/_update`, - method: 'POST', - data: obj.datafeedConfig, - }); - }, - - deleteDatafeed(obj) { - return http({ - url: `${basePath()}/datafeeds/${obj.datafeedId}`, - method: 'DELETE', - }); - }, - - forceDeleteDatafeed(obj) { - return http({ - url: `${basePath()}/datafeeds/${obj.datafeedId}?force=true`, - method: 'DELETE', - }); - }, - - startDatafeed(obj) { - const data = {}; - if (obj.start !== undefined) { - data.start = obj.start; - } - if (obj.end !== undefined) { - data.end = obj.end; - } - return http({ - url: `${basePath()}/datafeeds/${obj.datafeedId}/_start`, - method: 'POST', - data, - }); - }, - - stopDatafeed(obj) { - return http({ - url: `${basePath()}/datafeeds/${obj.datafeedId}/_stop`, - method: 'POST', - }); - }, - - datafeedPreview(obj) { - return http({ - url: `${basePath()}/datafeeds/${obj.datafeedId}/_preview`, - method: 'GET', - }); - }, - - validateDetector(obj) { - return http({ - url: `${basePath()}/anomaly_detectors/_validate/detector`, - method: 'POST', - data: obj.detector, - }); - }, - - forecast(obj) { - const data = {}; - if (obj.duration !== undefined) { - data.duration = obj.duration; - } - - return http({ - url: `${basePath()}/anomaly_detectors/${obj.jobId}/_forecast`, - method: 'POST', - data, - }); - }, - - overallBuckets(obj) { - const data = pick(obj, ['topN', 'bucketSpan', 'start', 'end']); - return http({ - url: `${basePath()}/anomaly_detectors/${obj.jobId}/results/overall_buckets`, - method: 'POST', - data, - }); - }, - - hasPrivileges(obj) { - return http({ - url: `${basePath()}/_has_privileges`, - method: 'POST', - data: obj, - }); - }, - - checkMlPrivileges() { - return http({ - url: `${basePath()}/ml_capabilities`, - method: 'GET', - }); - }, - - checkManageMLPrivileges() { - return http({ - // TODO Fix http service parameters - url: `${basePath()}/ml_capabilities`, // '?ignoreSpaces=true' - method: 'GET', - }); - }, - - getNotificationSettings() { - return http({ - url: `${basePath()}/notification_settings`, - method: 'GET', - }); - }, - - getFieldCaps(obj) { - const data = {}; - if (obj.index !== undefined) { - data.index = obj.index; - } - if (obj.fields !== undefined) { - data.fields = obj.fields; - } - return http({ - url: `${basePath()}/indices/field_caps`, - method: 'POST', - data, - }); - }, - - recognizeIndex(obj) { - return http({ - url: `${basePath()}/modules/recognize/${encodeURIComponent(obj.indexPatternTitle)}`, - method: 'GET', - }); - }, - - listDataRecognizerModules() { - return http({ - url: `${basePath()}/modules/get_module`, - method: 'GET', - }); - }, - - getDataRecognizerModule(obj) { - return http({ - url: `${basePath()}/modules/get_module/${obj.moduleId}`, - method: 'GET', - }); - }, - - dataRecognizerModuleJobsExist(obj) { - return http({ - url: `${basePath()}/modules/jobs_exist/${obj.moduleId}`, - method: 'GET', - }); - }, - - setupDataRecognizerConfig(obj) { - const data = pick(obj, [ - 'prefix', - 'groups', - 'indexPatternName', - 'query', - 'useDedicatedIndex', - 'startDatafeed', - 'start', - 'end', - 'jobOverrides', - ]); - - return http({ - url: `${basePath()}/modules/setup/${obj.moduleId}`, - method: 'POST', - data, - }); - }, - - getVisualizerFieldStats(obj) { - const data = pick(obj, [ - 'query', - 'timeFieldName', - 'earliest', - 'latest', - 'samplerShardSize', - 'interval', - 'fields', - 'maxExamples', - ]); - - return http({ - url: `${basePath()}/data_visualizer/get_field_stats/${encodeURIComponent( - obj.indexPatternTitle - )}`, - method: 'POST', - data, - }); - }, - - getVisualizerOverallStats(obj) { - const data = pick(obj, [ - 'query', - 'timeFieldName', - 'earliest', - 'latest', - 'samplerShardSize', - 'aggregatableFields', - 'nonAggregatableFields', - ]); - - return http({ - url: `${basePath()}/data_visualizer/get_overall_stats/${encodeURIComponent( - obj.indexPatternTitle - )}`, - method: 'POST', - data, - }); - }, - - /** - * Gets a list of calendars - * @param obj - * @returns {Promise} - */ - calendars(obj = {}) { - const { calendarId, calendarIds } = obj; - let calendarIdsPathComponent = ''; - if (calendarId) { - calendarIdsPathComponent = `/${calendarId}`; - } else if (calendarIds) { - calendarIdsPathComponent = `/${calendarIds.join(',')}`; - } - return http({ - url: `${basePath()}/calendars${calendarIdsPathComponent}`, - method: 'GET', - }); - }, - - addCalendar(obj) { - return http({ - url: `${basePath()}/calendars`, - method: 'PUT', - data: obj, - }); - }, - - updateCalendar(obj) { - const calendarId = obj && obj.calendarId ? `/${obj.calendarId}` : ''; - return http({ - url: `${basePath()}/calendars${calendarId}`, - method: 'PUT', - data: obj, - }); - }, - - deleteCalendar(obj) { - return http({ - url: `${basePath()}/calendars/${obj.calendarId}`, - method: 'DELETE', - }); - }, - - mlNodeCount() { - return http({ - url: `${basePath()}/ml_node_count`, - method: 'GET', - }); - }, - - mlInfo() { - return http({ - url: `${basePath()}/info`, - method: 'GET', - }); - }, - - calculateModelMemoryLimit(obj) { - const data = pick(obj, [ - 'indexPattern', - 'splitFieldName', - 'query', - 'fieldNames', - 'influencerNames', - 'timeFieldName', - 'earliestMs', - 'latestMs', - ]); - - return http({ - url: `${basePath()}/validate/calculate_model_memory_limit`, - method: 'POST', - data, - }); - }, - - getCardinalityOfFields(obj) { - const data = pick(obj, [ - 'index', - 'fieldNames', - 'query', - 'timeFieldName', - 'earliestMs', - 'latestMs', - ]); - - return http({ - url: `${basePath()}/fields_service/field_cardinality`, - method: 'POST', - data, - }); - }, - - getTimeFieldRange(obj) { - const data = pick(obj, ['index', 'timeFieldName', 'query']); - - return http({ - url: `${basePath()}/fields_service/time_field_range`, - method: 'POST', - data, - }); - }, - - esSearch(obj) { - return http({ - url: `${basePath()}/es_search`, - method: 'POST', - data: obj, - }); - }, - - esSearch$(obj) { - return http$(`${basePath()}/es_search`, { - method: 'POST', - body: obj, - }); - }, - - getIndices() { - const tempBasePath = '/api'; - return http({ - url: `${tempBasePath}/index_management/indices`, - method: 'GET', - }); - }, - - annotations, - dataFrameAnalytics, - filters, - results, - jobs, - fileDatavisualizer, -}; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts index 56de0566f0a72..d1089cded7b4e 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts @@ -17,8 +17,14 @@ import { MlServerDefaults, MlServerLimits } from '../ml_server_info'; import { PrivilegesResponse } from '../../../../common/types/privileges'; import { Calendar, CalendarId, UpdateCalendar } from '../../../../common/types/calendars'; -import { CombinedJob } from '../../../../common/types/anomaly_detection_jobs'; +import { + Job, + Datafeed, + CombinedJob, + Detector, +} from '../../../../common/types/anomaly_detection_jobs'; import { ES_AGGREGATION } from '../../../../common/constants/aggregation_types'; +import { FieldRequestConfig } from '../../datavisualizer/index_based/common'; export interface MlInfoResponse { defaults: MlServerDefaults; @@ -31,14 +37,6 @@ export interface MlInfoResponse { cloudId?: string; } -// TODO This is not a complete representation of all methods of `ml.*`. -// It just satisfies needs for other parts of the code area which use -// TypeScript and rely on the methods typed in here. -// This allows the import of `ml` into TypeScript code. -interface EsIndex { - name: string; -} - export interface BucketSpanEstimatorData { aggTypes: Array; duration: { @@ -96,7 +94,7 @@ export const ml = { }); }, - addJob({ jobId, job }: { jobId: string; job: any }) { + addJob({ jobId, job }: { jobId: string; job: Job }) { const body = JSON.stringify({ job }); return http({ path: `${basePath()}/anomaly_detectors/${jobId}`, @@ -133,7 +131,7 @@ export const ml = { }); }, - updateJob({ jobId, job }: { jobId: string; job: any }) { + updateJob({ jobId, job }: { jobId: string; job: Job }) { const body = JSON.stringify({ job }); return http({ path: `${basePath()}/anomaly_detectors/${jobId}/_update`, @@ -151,7 +149,7 @@ export const ml = { }); }, - validateJob({ job }: { job: any }) { + validateJob({ job }: { job: Job }) { const body = JSON.stringify({ job }); return http({ path: `${basePath()}/validate/job`, @@ -182,7 +180,7 @@ export const ml = { }); }, - addDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: any }) { + addDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) { const body = JSON.stringify({ datafeedConfig }); return http({ path: `${basePath()}/datafeeds/${datafeedId}`, @@ -191,7 +189,7 @@ export const ml = { }); }, - updateDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: any }) { + updateDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) { const body = JSON.stringify({ datafeedConfig }); return http({ path: `${basePath()}/datafeeds/${datafeedId}/_update`, @@ -241,7 +239,7 @@ export const ml = { }); }, - validateDetector({ detector }: { detector: any }) { + validateDetector({ detector }: { detector: Detector }) { const body = JSON.stringify({ detector }); return http({ path: `${basePath()}/anomaly_detectors/_validate/detector`, @@ -375,7 +373,7 @@ export const ml = { startDatafeed?: boolean; start?: number; end?: number; - jobOverrides?: any; + jobOverrides?: Array>; }) { const body = JSON.stringify({ prefix, @@ -414,7 +412,7 @@ export const ml = { latest?: number; samplerShardSize?: number; interval?: string; - fields?: any[]; + fields?: FieldRequestConfig[]; maxExamples?: number; }) { const body = JSON.stringify({ @@ -490,7 +488,7 @@ export const ml = { }); }, - addCalendar(obj: any) { + addCalendar(obj: Calendar) { const body = JSON.stringify(obj); return http({ path: `${basePath()}/calendars`, @@ -626,7 +624,7 @@ export const ml = { }); }, - getIndices(): Promise { + getIndices(): Promise> { const tempBasePath = '/api'; return http({ path: `${tempBasePath}/index_management/indices`, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index_.d.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index_.d.ts deleted file mode 100644 index 9aec9a4c0bfad..0000000000000 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index_.d.ts +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { Observable } from 'rxjs'; -import { Annotation } from '../../../../common/types/annotations'; -import { Dictionary } from '../../../../common/types/common'; -import { AggFieldNamePair } from '../../../../common/types/fields'; -import { Category } from '../../../../common/types/categories'; -import { ExistingJobsAndGroups } from '../job_service'; -import { PrivilegesResponse } from '../../../../common/types/privileges'; -import { - MlInfoResponse, - MlServerDefaults, - MlServerLimits, -} from '../../../../common/types/ml_server_info'; -import { ES_AGGREGATION } from '../../../../common/constants/aggregation_types'; -import { DataFrameAnalyticsStats } from '../../data_frame_analytics/pages/analytics_management/components/analytics_list/common'; -import { JobMessage } from '../../../../common/types/audit_message'; -import { DataFrameAnalyticsConfig } from '../../data_frame_analytics/common/analytics'; -import { DeepPartial } from '../../../../common/types/common'; -import { PartitionFieldsDefinition } from '../results_service/result_service_rx'; -import { annotations } from './annotations'; -import { Calendar, CalendarId, UpdateCalendar } from '../../../../common/types/calendars'; -import { - MlJobWithTimeRange, - MlSummaryJobs, - CombinedJob, - JobId, -} from '../../../../common/types/anomaly_detection_jobs'; -import { - CategorizationAnalyzer, - CategoryFieldExample, - FieldExampleCheck, -} from '../../../../common/types/categories'; -import { CATEGORY_EXAMPLES_VALIDATION_STATUS } from '../../../../common/constants/new_job'; - -declare const basePath: () => string; - -// TODO This is not a complete representation of all methods of `ml.*`. -// It just satisfies needs for other parts of the code area which use -// TypeScript and rely on the methods typed in here. -// This allows the import of `ml` into TypeScript code. -interface EsIndex { - name: string; -} - -export interface GetTimeFieldRangeResponse { - success: boolean; - start: { epoch: number; string: string }; - end: { epoch: number; string: string }; -} - -export interface BucketSpanEstimatorData { - aggTypes: Array; - duration: { - start: number; - end: number; - }; - fields: Array; - index: string; - query: any; - splitField: string | undefined; - timeField: string | undefined; -} - -export interface BucketSpanEstimatorResponse { - name: string; - ms: number; - error?: boolean; - message?: { msg: string } | string; -} - -export interface SuccessCardinality { - id: 'success_cardinality'; -} - -export interface CardinalityModelPlotHigh { - id: 'cardinality_model_plot_high'; - modelPlotCardinality: number; -} - -export type CardinalityValidationResult = SuccessCardinality | CardinalityModelPlotHigh; -export type CardinalityValidationResults = CardinalityValidationResult[]; - -declare interface Ml { - annotations: { - deleteAnnotation(id: string | undefined): Promise; - indexAnnotation(annotation: Annotation): Promise; - getAnnotations: typeof annotations.getAnnotations; - }; - - dataFrameAnalytics: { - getDataFrameAnalytics(analyticsId?: string): Promise; - getDataFrameAnalyticsStats(analyticsId?: string): Promise; - createDataFrameAnalytics(analyticsId: string, analyticsConfig: any): Promise; - evaluateDataFrameAnalytics(evaluateConfig: any): Promise; - explainDataFrameAnalytics(jobConfig: DeepPartial): Promise; - deleteDataFrameAnalytics(analyticsId: string): Promise; - startDataFrameAnalytics(analyticsId: string): Promise; - stopDataFrameAnalytics( - analyticsId: string, - force?: boolean, - waitForCompletion?: boolean - ): Promise; - getAnalyticsAuditMessages(analyticsId: string): Promise; - }; - - hasPrivileges(obj: object): Promise; - - checkMlPrivileges(): Promise; - checkManageMLPrivileges(): Promise; - getJobStats(obj: object): Promise; - getDatafeedStats(obj: object): Promise; - esSearch(obj: object): Promise; - esSearch$(obj: object): Observable; - getIndices(): Promise; - dataRecognizerModuleJobsExist(obj: { moduleId: string }): Promise; - getDataRecognizerModule(obj: { moduleId: string }): Promise; - setupDataRecognizerConfig(obj: object): Promise; - getTimeFieldRange(obj: object): Promise; - calculateModelMemoryLimit(obj: object): Promise<{ modelMemoryLimit: string }>; - calendars(obj?: { calendarId?: CalendarId; calendarIds?: CalendarId[] }): Promise; - updateCalendar(obj: UpdateCalendar): Promise; - - getVisualizerFieldStats(obj: object): Promise; - getVisualizerOverallStats(obj: object): Promise; - - results: { - getMaxAnomalyScore: (jobIds: string[], earliestMs: number, latestMs: number) => Promise; - fetchPartitionFieldsValues: ( - jobId: JobId, - searchTerm: Record, - criteriaFields: Array<{ fieldName: string; fieldValue: any }>, - earliestMs: number, - latestMs: number - ) => Observable; - }; - - jobs: { - jobsSummary(jobIds: string[]): Promise; - jobsWithTimerange( - dateFormatTz: string - ): Promise<{ jobs: MlJobWithTimeRange[]; jobsMap: Dictionary }>; - jobs(jobIds: string[]): Promise; - groups(): Promise; - updateGroups(updatedJobs: string[]): Promise; - forceStartDatafeeds(datafeedIds: string[], start: string, end: string): Promise; - stopDatafeeds(datafeedIds: string[]): Promise; - deleteJobs(jobIds: string[]): Promise; - closeJobs(jobIds: string[]): Promise; - jobAuditMessages(jobId: string, from?: string): Promise; - deletingJobTasks(): Promise; - newJobCaps(indexPatternTitle: string, isRollup: boolean): Promise; - newJobLineChart( - indexPatternTitle: string, - timeField: string, - start: number, - end: number, - intervalMs: number, - query: object, - aggFieldNamePairs: AggFieldNamePair[], - splitFieldName: string | null, - splitFieldValue: string | null - ): Promise; - newJobPopulationsChart( - indexPatternTitle: string, - timeField: string, - start: number, - end: number, - intervalMs: number, - query: object, - aggFieldNamePairs: AggFieldNamePair[], - splitFieldName: string - ): Promise; - getAllJobAndGroupIds(): Promise; - getLookBackProgress( - jobId: string, - start: number, - end: number - ): Promise<{ progress: number; isRunning: boolean; isJobClosed: boolean }>; - categorizationFieldExamples( - indexPatternTitle: string, - query: object, - size: number, - field: string, - timeField: string | undefined, - start: number, - end: number, - analyzer: CategorizationAnalyzer - ): Promise<{ - examples: CategoryFieldExample[]; - sampleSize: number; - overallValidStatus: CATEGORY_EXAMPLES_VALIDATION_STATUS; - validationChecks: FieldExampleCheck[]; - }>; - topCategories( - jobId: string, - count: number - ): Promise<{ total: number; categories: Array<{ count?: number; category: Category }> }>; - }; - - estimateBucketSpan(data: BucketSpanEstimatorData): Promise; - - mlNodeCount(): Promise<{ count: number }>; - mlInfo(): Promise; - getCardinalityOfFields(obj: Record): any; - validateCardinality$(job: CombinedJob): Observable; -} - -declare const ml: Ml; - -export interface GetDataFrameAnalyticsStatsResponseOk { - node_failures?: object; - count: number; - data_frame_analytics: DataFrameAnalyticsStats[]; -} - -export interface GetDataFrameAnalyticsStatsResponseError { - statusCode: number; - error: string; - message: string; -} - -export type GetDataFrameAnalyticsStatsResponse = - | GetDataFrameAnalyticsStatsResponseOk - | GetDataFrameAnalyticsStatsResponseError; diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.js b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.js deleted file mode 100644 index cef2b3d2ffd7f..0000000000000 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.js +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { http } from '../http_service'; - -import { basePath } from './index'; - -export const jobs = { - jobsSummary(jobIds) { - return http({ - url: `${basePath()}/jobs/jobs_summary`, - method: 'POST', - data: { - jobIds, - }, - }); - }, - - jobsWithTimerange(dateFormatTz) { - return http({ - url: `${basePath()}/jobs/jobs_with_time_range`, - method: 'POST', - data: { - dateFormatTz, - }, - }); - }, - - jobs(jobIds) { - return http({ - url: `${basePath()}/jobs/jobs`, - method: 'POST', - data: { - jobIds, - }, - }); - }, - - groups() { - return http({ - url: `${basePath()}/jobs/groups`, - method: 'GET', - }); - }, - - updateGroups(updatedJobs) { - return http({ - url: `${basePath()}/jobs/update_groups`, - method: 'POST', - data: { - jobs: updatedJobs, - }, - }); - }, - - forceStartDatafeeds(datafeedIds, start, end) { - return http({ - url: `${basePath()}/jobs/force_start_datafeeds`, - method: 'POST', - data: { - datafeedIds, - start, - end, - }, - }); - }, - - stopDatafeeds(datafeedIds) { - return http({ - url: `${basePath()}/jobs/stop_datafeeds`, - method: 'POST', - data: { - datafeedIds, - }, - }); - }, - - deleteJobs(jobIds) { - return http({ - url: `${basePath()}/jobs/delete_jobs`, - method: 'POST', - data: { - jobIds, - }, - }); - }, - - closeJobs(jobIds) { - return http({ - url: `${basePath()}/jobs/close_jobs`, - method: 'POST', - data: { - jobIds, - }, - }); - }, - - jobAuditMessages(jobId, from) { - const jobIdString = jobId !== undefined ? `/${jobId}` : ''; - const fromString = from !== undefined ? `?from=${from}` : ''; - return http({ - url: `${basePath()}/job_audit_messages/messages${jobIdString}${fromString}`, - method: 'GET', - }); - }, - - deletingJobTasks() { - return http({ - url: `${basePath()}/jobs/deleting_jobs_tasks`, - method: 'GET', - }); - }, - - jobsExist(jobIds) { - return http({ - url: `${basePath()}/jobs/jobs_exist`, - method: 'POST', - data: { - jobIds, - }, - }); - }, - - newJobCaps(indexPatternTitle, isRollup = false) { - const isRollupString = isRollup === true ? `?rollup=true` : ''; - return http({ - url: `${basePath()}/jobs/new_job_caps/${encodeURIComponent( - indexPatternTitle - )}${isRollupString}`, - method: 'GET', - }); - }, - - newJobLineChart( - indexPatternTitle, - timeField, - start, - end, - intervalMs, - query, - aggFieldNamePairs, - splitFieldName, - splitFieldValue - ) { - return http({ - url: `${basePath()}/jobs/new_job_line_chart`, - method: 'POST', - data: { - indexPatternTitle, - timeField, - start, - end, - intervalMs, - query, - aggFieldNamePairs, - splitFieldName, - splitFieldValue, - }, - }); - }, - - newJobPopulationsChart( - indexPatternTitle, - timeField, - start, - end, - intervalMs, - query, - aggFieldNamePairs, - splitFieldName - ) { - return http({ - url: `${basePath()}/jobs/new_job_population_chart`, - method: 'POST', - data: { - indexPatternTitle, - timeField, - start, - end, - intervalMs, - query, - aggFieldNamePairs, - splitFieldName, - }, - }); - }, - - getAllJobAndGroupIds() { - return http({ - url: `${basePath()}/jobs/all_jobs_and_group_ids`, - method: 'GET', - }); - }, - - getLookBackProgress(jobId, start, end) { - return http({ - url: `${basePath()}/jobs/look_back_progress`, - method: 'POST', - data: { - jobId, - start, - end, - }, - }); - }, - - categorizationFieldExamples( - indexPatternTitle, - query, - size, - field, - timeField, - start, - end, - analyzer - ) { - return http({ - url: `${basePath()}/jobs/categorization_field_examples`, - method: 'POST', - data: { - indexPatternTitle, - query, - size, - field, - timeField, - start, - end, - analyzer, - }, - }); - }, - - topCategories(jobId, count) { - return http({ - url: `${basePath()}/jobs/top_categories`, - method: 'POST', - data: { - jobId, - count, - }, - }); - }, -}; From baac0265e0f27e14535abdc2edfa4bac483ea093 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Wed, 11 Mar 2020 21:21:26 +0000 Subject: [PATCH 3/9] cleaning up http requests --- .../create_watch_service.js | 12 ++-- .../application/services/http_service.ts | 72 +++++++------------ .../services/ml_api_service/annotations.ts | 9 ++- .../ml_api_service/data_frame_analytics.ts | 9 ++- .../services/ml_api_service/datavisualizer.ts | 3 +- .../services/ml_api_service/index.ts | 18 ++--- .../services/ml_api_service/results.ts | 6 +- 7 files changed, 57 insertions(+), 72 deletions(-) diff --git a/x-pack/legacy/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js b/x-pack/legacy/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js index 32b5634b143db..29e89022a5502 100644 --- a/x-pack/legacy/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js +++ b/x-pack/legacy/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js @@ -39,13 +39,12 @@ function randomNumber(min, max) { } function saveWatch(watchModel) { - const path = '/api/watcher'; - const url = `${path}/watch/${watchModel.id}`; + const path = `/api/watcher/watch/${watchModel.id}`; return http({ - url, + path, method: 'PUT', - data: watchModel.upstreamJSON, + body: JSON.stringify(watchModel.upstreamJSON), }); } @@ -187,10 +186,9 @@ class CreateWatchService { loadWatch(jobId) { const id = `ml-${jobId}`; - const path = '/api/watcher'; - const url = `${path}/watch/${id}`; + const path = `/api/watcher/watch/${id}`; return http({ - url, + path, method: 'GET', }); } diff --git a/x-pack/legacy/plugins/ml/public/application/services/http_service.ts b/x-pack/legacy/plugins/ml/public/application/services/http_service.ts index 976bab02a1eb5..0283041fa1148 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/http_service.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/http_service.ts @@ -5,7 +5,7 @@ */ import { Observable } from 'rxjs'; -import { HttpFetchOptionsWithPath } from 'kibana/public'; +import { HttpFetchOptionsWithPath, HttpFetchOptions } from 'kibana/public'; import { getHttp } from '../util/dependency_cache'; function getResultHeaders(headers: HeadersInit): HeadersInit { @@ -16,64 +16,40 @@ function getResultHeaders(headers: HeadersInit): HeadersInit { } as HeadersInit; } -// interface HttpOptions { -// url: string; -// method: string; -// headers?: any; -// data?: any; -// } - -/** - * Function for making HTTP requests to Kibana's backend. - * Wrapper for Kibana's HttpHandler. - */ -export async function http(options: HttpFetchOptionsWithPath) { - if (!options?.path) { +function getFetchOptions( + options: HttpFetchOptionsWithPath +): { path: string; fetchOptions: HttpFetchOptions } { + if (!options.path) { throw new Error('URL path is missing'); } - - try { - let path = ''; - path = path + (options.path || ''); - const headers = getResultHeaders(options.headers ?? {}); - - const allHeaders = options.headers === undefined ? headers : { ...options.headers, ...headers }; - const body = options.body === undefined ? null : JSON.stringify(options.body); - - const payload: RequestInit = { - method: options.method || 'GET', - headers: allHeaders, + return { + path: options.path, + fetchOptions: { credentials: 'same-origin', - }; - - if (body !== null) { - payload.body = body; - } - - return await getHttp().fetch(path, payload); - } catch (e) { - throw new Error(e); - } + method: options.method || 'GET', + ...(options.body ? { body: options.body } : {}), + ...(options.query ? { query: options.query } : {}), + headers: getResultHeaders(options.headers ?? {}), + }, + }; } -interface RequestOptions extends RequestInit { - body: BodyInit | any; +/** + * Function for making HTTP requests to Kibana's backend. + * Wrapper for Kibana's HttpHandler. + */ +export async function http(options: HttpFetchOptionsWithPath): Promise { + const { path, fetchOptions } = getFetchOptions(options); + return getHttp().fetch(path, fetchOptions); } /** * Function for making HTTP requests to Kibana's backend which returns an Observable * with request cancellation support. */ -export function http$(path: string, options: RequestOptions): Observable { - const requestInit: RequestInit = { - ...options, - credentials: 'same-origin', - method: options.method || 'GET', - ...(options.body ? { body: JSON.stringify(options.body) as string } : {}), - headers: getResultHeaders(options.headers ?? {}), - }; - - return fromHttpHandler(path, requestInit); +export function http$(options: HttpFetchOptionsWithPath): Observable { + const { path, fetchOptions } = getFetchOptions(options); + return fromHttpHandler(path, fetchOptions); } /** diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts index 28d3fbd642f33..9c334136f226d 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts @@ -15,16 +15,19 @@ export const annotations = { latestMs: number; maxAnnotations: number; }) { - return http$<{ annotations: Record }>(`${basePath()}/annotations`, { + const body = JSON.stringify(obj); + return http$<{ annotations: Record }>({ + path: `${basePath()}/annotations`, method: 'POST', - body: obj, + body, }); }, indexAnnotation(obj: any) { + const body = JSON.stringify(obj); return http({ path: `${basePath()}/annotations/index`, method: 'PUT', - body: obj, + body, }); }, deleteAnnotation(id: string) { diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts index 80af9a66fa44c..f478a97c94ae4 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts @@ -47,24 +47,27 @@ export const dataFrameAnalytics = { }); }, createDataFrameAnalytics(analyticsId: string, analyticsConfig: any): Promise { + const body = JSON.stringify(analyticsConfig); return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}`, method: 'PUT', - body: analyticsConfig, + body, }); }, evaluateDataFrameAnalytics(evaluateConfig: any): Promise { + const body = JSON.stringify(evaluateConfig); return http({ path: `${basePath()}/data_frame/_evaluate`, method: 'POST', - body: evaluateConfig, + body, }); }, explainDataFrameAnalytics(jobConfig: any): Promise { + const body = JSON.stringify(jobConfig); return http({ path: `${basePath()}/data_frame/analytics/_explain`, method: 'POST', - body: jobConfig, + body, }); }, deleteDataFrameAnalytics(analyticsId: string): Promise { diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts index dabdb0156f2e3..93e391ce515b9 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts @@ -10,10 +10,11 @@ import { basePath } from './index'; export const fileDatavisualizer = { analyzeFile(file: string, params: Record = {}) { + const body = JSON.stringify(file); return http({ path: `${basePath()}/file_data_visualizer/analyze_file`, method: 'POST', - body: file, + body, query: params, }); }, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts index d1089cded7b4e..4b9ebcd408e5b 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts @@ -95,7 +95,7 @@ export const ml = { }, addJob({ jobId, job }: { jobId: string; job: Job }) { - const body = JSON.stringify({ job }); + const body = JSON.stringify(job); return http({ path: `${basePath()}/anomaly_detectors/${jobId}`, method: 'PUT', @@ -132,7 +132,7 @@ export const ml = { }, updateJob({ jobId, job }: { jobId: string; job: Job }) { - const body = JSON.stringify({ job }); + const body = JSON.stringify(job); return http({ path: `${basePath()}/anomaly_detectors/${jobId}/_update`, method: 'POST', @@ -159,8 +159,9 @@ export const ml = { }, validateCardinality$(job: CombinedJob): Observable { - const body = JSON.stringify({ job }); - return http$(`${basePath()}/validate/cardinality`, { + const body = JSON.stringify(job); + return http$({ + path: `${basePath()}/validate/cardinality`, method: 'POST', body, }); @@ -181,7 +182,7 @@ export const ml = { }, addDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) { - const body = JSON.stringify({ datafeedConfig }); + const body = JSON.stringify(datafeedConfig); return http({ path: `${basePath()}/datafeeds/${datafeedId}`, method: 'PUT', @@ -190,7 +191,7 @@ export const ml = { }, updateDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) { - const body = JSON.stringify({ datafeedConfig }); + const body = JSON.stringify(datafeedConfig); return http({ path: `${basePath()}/datafeeds/${datafeedId}/_update`, method: 'POST', @@ -240,7 +241,7 @@ export const ml = { }, validateDetector({ detector }: { detector: Detector }) { - const body = JSON.stringify({ detector }); + const body = JSON.stringify(detector); return http({ path: `${basePath()}/anomaly_detectors/_validate/detector`, method: 'POST', @@ -618,7 +619,8 @@ export const ml = { esSearch$(obj: any): Observable { const body = JSON.stringify(obj); - return http$(`${basePath()}/es_search`, { + return http$({ + path: `${basePath()}/es_search`, method: 'POST', body, }); diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts index e61c5676912dc..2e5cc8af04d36 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts @@ -42,7 +42,8 @@ export const results = { influencersFilterQuery, }); - return http$(`${basePath()}/results/anomalies_table_data`, { + return http$({ + path: `${basePath()}/results/anomalies_table_data`, method: 'POST', body, }); @@ -91,7 +92,8 @@ export const results = { latestMs: number ): Observable { const body = JSON.stringify({ jobId, searchTerm, criteriaFields, earliestMs, latestMs }); - return http$(`${basePath()}/results/partition_fields_values`, { + return http$({ + path: `${basePath()}/results/partition_fields_values`, method: 'POST', body, }); From 919bf2c122b1e8be1e2d1756b31ecd05a5c76628 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Wed, 11 Mar 2020 21:39:33 +0000 Subject: [PATCH 4/9] remove http generics --- .../plugins/ml/public/application/services/http_service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/legacy/plugins/ml/public/application/services/http_service.ts b/x-pack/legacy/plugins/ml/public/application/services/http_service.ts index 0283041fa1148..bb5da7bec0f7b 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/http_service.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/http_service.ts @@ -38,9 +38,9 @@ function getFetchOptions( * Function for making HTTP requests to Kibana's backend. * Wrapper for Kibana's HttpHandler. */ -export async function http(options: HttpFetchOptionsWithPath): Promise { +export async function http(options: HttpFetchOptionsWithPath): Promise { const { path, fetchOptions } = getFetchOptions(options); - return getHttp().fetch(path, fetchOptions); + return getHttp().fetch(path, fetchOptions); } /** From dad3a6b4741b7faa280084e9246f7eff0f3424ef Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Thu, 12 Mar 2020 09:00:33 +0000 Subject: [PATCH 5/9] better use of generics and type clean up --- .../classification_exploration.tsx | 9 +- .../components/exploration/exploration.tsx | 9 +- .../regression_exploration.tsx | 9 +- .../analytics_service/get_analytics.ts | 16 +-- .../index_based/data_loader/data_loader.ts | 2 +- .../common/chart_loader/chart_loader.ts | 8 +- .../jobs/new_job/recognize/page.tsx | 4 +- .../anomaly_detection_panel.tsx | 6 +- .../application/services/http_service.ts | 4 +- .../services/ml_api_service/annotations.ts | 4 +- .../ml_api_service/data_frame_analytics.ts | 44 ++++--- .../services/ml_api_service/datavisualizer.ts | 4 +- .../services/ml_api_service/filters.ts | 10 +- .../services/ml_api_service/index.ts | 124 +++++++++--------- .../services/ml_api_service/jobs.ts | 79 +++++------ .../services/ml_api_service/results.ts | 16 +-- 16 files changed, 158 insertions(+), 190 deletions(-) diff --git a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/classification_exploration.tsx b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/classification_exploration.tsx index df2ca3e7de657..83afb489abcb0 100644 --- a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/classification_exploration.tsx +++ b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/classification_exploration.tsx @@ -19,11 +19,6 @@ import { IIndexPattern } from '../../../../../../../../../../../src/plugins/data import { newJobCapsService } from '../../../../../services/new_job_capabilities_service'; import { useMlContext } from '../../../../../contexts/ml'; -interface GetDataFrameAnalyticsResponse { - count: number; - data_frame_analytics: DataFrameAnalyticsConfig[]; -} - export const ExplorationTitle: React.FC<{ jobId: string }> = ({ jobId }) => ( @@ -69,9 +64,7 @@ export const ClassificationExploration: FC = ({ jobId, jobStatus }) => { const loadJobConfig = async () => { setIsLoadingJobConfig(true); try { - const analyticsConfigs: GetDataFrameAnalyticsResponse = await ml.dataFrameAnalytics.getDataFrameAnalytics( - jobId - ); + const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(jobId); if ( Array.isArray(analyticsConfigs.data_frame_analytics) && analyticsConfigs.data_frame_analytics.length > 0 diff --git a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration/exploration.tsx b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration/exploration.tsx index ce72e90b4c230..fe96b056dea11 100644 --- a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration/exploration.tsx +++ b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration/exploration.tsx @@ -72,11 +72,6 @@ import { useMlContext } from '../../../../../contexts/ml'; const FEATURE_INFLUENCE = 'feature_influence'; -interface GetDataFrameAnalyticsResponse { - count: number; - data_frame_analytics: DataFrameAnalyticsConfig[]; -} - const PAGE_SIZE_OPTIONS = [5, 10, 25, 50]; const ExplorationTitle: React.FC<{ jobId: string }> = ({ jobId }) => ( @@ -130,9 +125,7 @@ export const Exploration: FC = React.memo(({ jobId, jobStatus }) => { useEffect(() => { (async function() { - const analyticsConfigs: GetDataFrameAnalyticsResponse = await ml.dataFrameAnalytics.getDataFrameAnalytics( - jobId - ); + const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(jobId); if ( Array.isArray(analyticsConfigs.data_frame_analytics) && analyticsConfigs.data_frame_analytics.length > 0 diff --git a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/regression_exploration.tsx b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/regression_exploration.tsx index 569cf21792874..bb81682eeb5d7 100644 --- a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/regression_exploration.tsx +++ b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/regression_exploration.tsx @@ -19,11 +19,6 @@ import { IIndexPattern } from '../../../../../../../../../../../src/plugins/data import { newJobCapsService } from '../../../../../services/new_job_capabilities_service'; import { useMlContext } from '../../../../../contexts/ml'; -interface GetDataFrameAnalyticsResponse { - count: number; - data_frame_analytics: DataFrameAnalyticsConfig[]; -} - export const ExplorationTitle: React.FC<{ jobId: string }> = ({ jobId }) => ( @@ -69,9 +64,7 @@ export const RegressionExploration: FC = ({ jobId, jobStatus }) => { const loadJobConfig = async () => { setIsLoadingJobConfig(true); try { - const analyticsConfigs: GetDataFrameAnalyticsResponse = await ml.dataFrameAnalytics.getDataFrameAnalytics( - jobId - ); + const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(jobId); if ( Array.isArray(analyticsConfigs.data_frame_analytics) && analyticsConfigs.data_frame_analytics.length > 0 diff --git a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts index 2a33691d0a75d..df58f225e62de 100644 --- a/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts +++ b/x-pack/legacy/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts @@ -7,15 +7,10 @@ import { i18n } from '@kbn/i18n'; import { ml } from '../../../../../services/ml_api_service'; import { - GetDataFrameAnalyticsStatsResponse, GetDataFrameAnalyticsStatsResponseError, GetDataFrameAnalyticsStatsResponseOk, } from '../../../../../services/ml_api_service/data_frame_analytics'; -import { - DataFrameAnalyticsConfig, - REFRESH_ANALYTICS_LIST_STATE, - refreshAnalyticsList$, -} from '../../../../common'; +import { REFRESH_ANALYTICS_LIST_STATE, refreshAnalyticsList$ } from '../../../../common'; import { DATA_FRAME_MODE, @@ -27,11 +22,6 @@ import { } from '../../components/analytics_list/common'; import { AnalyticStatsBarStats } from '../../../../../components/stats_bar'; -interface GetDataFrameAnalyticsResponse { - count: number; - data_frame_analytics: DataFrameAnalyticsConfig[]; -} - export const isGetDataFrameAnalyticsStatsResponseOk = ( arg: any ): arg is GetDataFrameAnalyticsStatsResponseOk => { @@ -125,8 +115,8 @@ export const getAnalyticsFactory = ( } try { - const analyticsConfigs: GetDataFrameAnalyticsResponse = await ml.dataFrameAnalytics.getDataFrameAnalytics(); - const analyticsStats: GetDataFrameAnalyticsStatsResponse = await ml.dataFrameAnalytics.getDataFrameAnalyticsStats(); + const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(); + const analyticsStats = await ml.dataFrameAnalytics.getDataFrameAnalyticsStats(); const analyticsStatsResult = isGetDataFrameAnalyticsStatsResponseOk(analyticsStats) ? getAnalyticsJobsStats(analyticsStats) diff --git a/x-pack/legacy/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/legacy/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts index b0d8fa3d4fa88..931d767f1f1cd 100644 --- a/x-pack/legacy/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts +++ b/x-pack/legacy/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts @@ -76,7 +76,7 @@ export class DataLoader { fields: FieldRequestConfig[], interval?: string ): Promise { - const stats = await ml.getVisualizerFieldStats({ + const stats = await ml.getVisualizerFieldStats({ indexPatternTitle: this._indexPatternTitle, query, timeFieldName: this._indexPattern.timeFieldName, diff --git a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts index 5e92ab67fcc79..fb2f2099bcc0a 100644 --- a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts +++ b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts @@ -24,10 +24,10 @@ export type LineChartData = Record; const eq = (newArgs: any[], lastArgs: any[]) => isEqual(newArgs, lastArgs); -const newJobLineChart = memoizeOne(ml.jobs.newJobLineChart, eq); -const newJobPopulationsChart = memoizeOne(ml.jobs.newJobPopulationsChart, eq); -const getEventRateData = memoizeOne(mlResultsService.getEventRateData, eq); -const getCategoryFields = memoizeOne(getCategoryFieldsOrig, eq); +const newJobLineChart = memoizeOne(ml.jobs.newJobLineChart, eq); +const newJobPopulationsChart = memoizeOne(ml.jobs.newJobPopulationsChart, eq); +const getEventRateData = memoizeOne(mlResultsService.getEventRateData, eq); +const getCategoryFields = memoizeOne(getCategoryFieldsOrig, eq); export class ChartLoader { private _indexPatternTitle: IndexPatternTitle = ''; diff --git a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/recognize/page.tsx b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/recognize/page.tsx index ac7a2093d1f81..ddaaeaa8566be 100644 --- a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/recognize/page.tsx +++ b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/recognize/page.tsx @@ -106,7 +106,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { */ const loadModule = async () => { try { - const response: Module = await ml.getDataRecognizerModule({ moduleId }); + const response = await ml.getDataRecognizerModule({ moduleId }); setJobs(response.jobs); const kibanaObjectsResult = await checkForSavedObjects(response.kibana as KibanaObjects); @@ -165,7 +165,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { let jobOverridesPayload: JobOverride[] | null = Object.values(jobOverrides); jobOverridesPayload = jobOverridesPayload.length > 0 ? jobOverridesPayload : null; - const response: DataRecognizerConfigResponse = await ml.setupDataRecognizerConfig({ + const response = await ml.setupDataRecognizerConfig({ moduleId, prefix: resultJobPrefix, query: tempQuery, diff --git a/x-pack/legacy/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx b/x-pack/legacy/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx index 5f5c3f7c28670..44356aa169f68 100644 --- a/x-pack/legacy/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx +++ b/x-pack/legacy/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx @@ -102,7 +102,11 @@ export const AnomalyDetectionPanel: FC = ({ jobCreationDisabled }) => { const latestTimestamp = group.latest_timestamp; const startMoment = moment(latestTimestamp); const twentyFourHoursAgo = startMoment.subtract(24, 'hours').valueOf(); - return ml.results.getMaxAnomalyScore(group.jobIds, twentyFourHoursAgo, latestTimestamp); + return ml.results.getMaxAnomalyScore( + group.jobIds, + twentyFourHoursAgo, + latestTimestamp + ); }); const results = await Promise.all(promises); diff --git a/x-pack/legacy/plugins/ml/public/application/services/http_service.ts b/x-pack/legacy/plugins/ml/public/application/services/http_service.ts index bb5da7bec0f7b..0283041fa1148 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/http_service.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/http_service.ts @@ -38,9 +38,9 @@ function getFetchOptions( * Function for making HTTP requests to Kibana's backend. * Wrapper for Kibana's HttpHandler. */ -export async function http(options: HttpFetchOptionsWithPath): Promise { +export async function http(options: HttpFetchOptionsWithPath): Promise { const { path, fetchOptions } = getFetchOptions(options); - return getHttp().fetch(path, fetchOptions); + return getHttp().fetch(path, fetchOptions); } /** diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts index 9c334136f226d..29a5732026761 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/annotations.ts @@ -24,14 +24,14 @@ export const annotations = { }, indexAnnotation(obj: any) { const body = JSON.stringify(obj); - return http({ + return http({ path: `${basePath()}/annotations/index`, method: 'PUT', body, }); }, deleteAnnotation(id: string) { - return http({ + return http({ path: `${basePath()}/annotations/delete/${id}`, method: 'DELETE', }); diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts index f478a97c94ae4..9fa595259e062 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts @@ -8,6 +8,7 @@ import { http } from '../http_service'; import { basePath } from './index'; import { DataFrameAnalyticsStats } from '../../data_frame_analytics/pages/analytics_management/components/analytics_list/common'; +import { DataFrameAnalyticsConfig } from '../../data_frame_analytics/common'; export interface GetDataFrameAnalyticsStatsResponseOk { node_failures?: object; @@ -25,72 +26,77 @@ export type GetDataFrameAnalyticsStatsResponse = | GetDataFrameAnalyticsStatsResponseOk | GetDataFrameAnalyticsStatsResponseError; +interface GetDataFrameAnalyticsResponse { + count: number; + data_frame_analytics: DataFrameAnalyticsConfig[]; +} + export const dataFrameAnalytics = { - getDataFrameAnalytics(analyticsId?: string): Promise { + getDataFrameAnalytics(analyticsId?: string) { const analyticsIdString = analyticsId !== undefined ? `/${analyticsId}` : ''; - return http({ + return http({ path: `${basePath()}/data_frame/analytics${analyticsIdString}`, method: 'GET', }); }, - getDataFrameAnalyticsStats(analyticsId?: string): Promise { + getDataFrameAnalyticsStats(analyticsId?: string) { if (analyticsId !== undefined) { - return http({ + return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}/_stats`, method: 'GET', }); } - return http({ + return http({ path: `${basePath()}/data_frame/analytics/_stats`, method: 'GET', }); }, - createDataFrameAnalytics(analyticsId: string, analyticsConfig: any): Promise { + createDataFrameAnalytics(analyticsId: string, analyticsConfig: any) { const body = JSON.stringify(analyticsConfig); - return http({ + return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}`, method: 'PUT', body, }); }, - evaluateDataFrameAnalytics(evaluateConfig: any): Promise { + evaluateDataFrameAnalytics(evaluateConfig: any) { const body = JSON.stringify(evaluateConfig); - return http({ + return http({ path: `${basePath()}/data_frame/_evaluate`, method: 'POST', body, }); }, - explainDataFrameAnalytics(jobConfig: any): Promise { + explainDataFrameAnalytics(jobConfig: any) { const body = JSON.stringify(jobConfig); - return http({ + return http({ path: `${basePath()}/data_frame/analytics/_explain`, method: 'POST', body, }); }, - deleteDataFrameAnalytics(analyticsId: string): Promise { - return http({ + deleteDataFrameAnalytics(analyticsId: string) { + return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}`, method: 'DELETE', }); }, - startDataFrameAnalytics(analyticsId: string): Promise { - return http({ + startDataFrameAnalytics(analyticsId: string) { + return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}/_start`, method: 'POST', }); }, - stopDataFrameAnalytics(analyticsId: string, force: boolean = false): Promise { - return http({ + stopDataFrameAnalytics(analyticsId: string, force: boolean = false) { + return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}/_stop`, method: 'POST', query: { force }, }); }, - getAnalyticsAuditMessages(analyticsId: string): Promise { - return http({ + getAnalyticsAuditMessages(analyticsId: string) { + return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}/messages`, method: 'GET', }); diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts index 93e391ce515b9..9b492530d303d 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/datavisualizer.ts @@ -11,7 +11,7 @@ import { basePath } from './index'; export const fileDatavisualizer = { analyzeFile(file: string, params: Record = {}) { const body = JSON.stringify(file); - return http({ + return http({ path: `${basePath()}/file_data_visualizer/analyze_file`, method: 'POST', body, @@ -43,7 +43,7 @@ export const fileDatavisualizer = { ingestPipeline, }); - return http({ + return http({ path: `${basePath()}/file_data_visualizer/import`, method: 'POST', query, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.ts index bf3a53f2d2a1c..f0c58966d0a8d 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/filters.ts @@ -14,14 +14,14 @@ import { basePath } from './index'; export const filters = { filters(obj?: { filterId?: string }) { const filterId = obj && obj.filterId ? `/${obj.filterId}` : ''; - return http({ + return http({ path: `${basePath()}/filters${filterId}`, method: 'GET', }); }, filtersStats() { - return http({ + return http({ path: `${basePath()}/filters/_stats`, method: 'GET', }); @@ -33,7 +33,7 @@ export const filters = { description, items, }); - return http({ + return http({ path: `${basePath()}/filters`, method: 'PUT', body, @@ -47,7 +47,7 @@ export const filters = { ...(removeItems !== undefined ? { removeItems } : {}), }); - return http({ + return http({ path: `${basePath()}/filters/${filterId}`, method: 'PUT', body, @@ -55,7 +55,7 @@ export const filters = { }, deleteFilter(filterId: string) { - return http({ + return http({ path: `${basePath()}/filters/${filterId}`, method: 'DELETE', }); diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts index 4b9ebcd408e5b..2c7ff0a0325a8 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts @@ -82,21 +82,21 @@ export function basePath() { export const ml = { getJobs(obj?: { jobId?: string }) { const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; - return http({ + return http({ path: `${basePath()}/anomaly_detectors${jobId}`, }); }, getJobStats(obj: { jobId?: string }) { const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; - return http({ + return http({ path: `${basePath()}/anomaly_detectors${jobId}/_stats`, }); }, addJob({ jobId, job }: { jobId: string; job: Job }) { const body = JSON.stringify(job); - return http({ + return http({ path: `${basePath()}/anomaly_detectors/${jobId}`, method: 'PUT', body, @@ -104,28 +104,28 @@ export const ml = { }, openJob({ jobId }: { jobId: string }) { - return http({ + return http({ path: `${basePath()}/anomaly_detectors/${jobId}/_open`, method: 'POST', }); }, closeJob({ jobId }: { jobId: string }) { - return http({ + return http({ path: `${basePath()}/anomaly_detectors/${jobId}/_close`, method: 'POST', }); }, deleteJob({ jobId }: { jobId: string }) { - return http({ + return http({ path: `${basePath()}/anomaly_detectors/${jobId}`, method: 'DELETE', }); }, forceDeleteJob({ jobId }: { jobId: string }) { - return http({ + return http({ path: `${basePath()}/anomaly_detectors/${jobId}?force=true`, method: 'DELETE', }); @@ -133,16 +133,16 @@ export const ml = { updateJob({ jobId, job }: { jobId: string; job: Job }) { const body = JSON.stringify(job); - return http({ + return http({ path: `${basePath()}/anomaly_detectors/${jobId}/_update`, method: 'POST', body, }); }, - estimateBucketSpan(obj: BucketSpanEstimatorData): Promise { + estimateBucketSpan(obj: BucketSpanEstimatorData) { const body = JSON.stringify(obj); - return http({ + return http({ path: `${basePath()}/validate/estimate_bucket_span`, method: 'POST', body, @@ -151,7 +151,7 @@ export const ml = { validateJob({ job }: { job: Job }) { const body = JSON.stringify({ job }); - return http({ + return http({ path: `${basePath()}/validate/job`, method: 'POST', body, @@ -169,21 +169,21 @@ export const ml = { getDatafeeds(obj: { datafeedId: string }) { const datafeedId = obj && obj.datafeedId ? `/${obj.datafeedId}` : ''; - return http({ + return http({ path: `${basePath()}/datafeeds${datafeedId}`, }); }, getDatafeedStats(obj: { datafeedId: string }) { const datafeedId = obj && obj.datafeedId ? `/${obj.datafeedId}` : ''; - return http({ + return http({ path: `${basePath()}/datafeeds${datafeedId}/_stats`, }); }, addDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) { const body = JSON.stringify(datafeedConfig); - return http({ + return http({ path: `${basePath()}/datafeeds/${datafeedId}`, method: 'PUT', body, @@ -192,7 +192,7 @@ export const ml = { updateDatafeed({ datafeedId, datafeedConfig }: { datafeedId: string; datafeedConfig: Datafeed }) { const body = JSON.stringify(datafeedConfig); - return http({ + return http({ path: `${basePath()}/datafeeds/${datafeedId}/_update`, method: 'POST', body, @@ -200,14 +200,14 @@ export const ml = { }, deleteDatafeed({ datafeedId }: { datafeedId: string }) { - return http({ + return http({ path: `${basePath()}/datafeeds/${datafeedId}`, method: 'DELETE', }); }, forceDeleteDatafeed({ datafeedId }: { datafeedId: string }) { - return http({ + return http({ path: `${basePath()}/datafeeds/${datafeedId}?force=true`, method: 'DELETE', }); @@ -219,7 +219,7 @@ export const ml = { ...(end !== undefined ? { end } : {}), }); - return http({ + return http({ path: `${basePath()}/datafeeds/${datafeedId}/_start`, method: 'POST', body, @@ -227,14 +227,14 @@ export const ml = { }, stopDatafeed({ datafeedId }: { datafeedId: string }) { - return http({ + return http({ path: `${basePath()}/datafeeds/${datafeedId}/_stop`, method: 'POST', }); }, datafeedPreview({ datafeedId }: { datafeedId: string }) { - return http({ + return http({ path: `${basePath()}/datafeeds/${datafeedId}/_preview`, method: 'GET', }); @@ -242,7 +242,7 @@ export const ml = { validateDetector({ detector }: { detector: Detector }) { const body = JSON.stringify(detector); - return http({ + return http({ path: `${basePath()}/anomaly_detectors/_validate/detector`, method: 'POST', body, @@ -254,7 +254,7 @@ export const ml = { ...(duration !== undefined ? { duration } : {}), }); - return http({ + return http({ path: `${basePath()}/anomaly_detectors/${jobId}/_forecast`, method: 'POST', body, @@ -275,7 +275,7 @@ export const ml = { end: number; }) { const body = JSON.stringify({ topN, bucketSpan, start, end }); - return http({ + return http({ path: `${basePath()}/anomaly_detectors/${jobId}/results/overall_buckets`, method: 'POST', body, @@ -284,29 +284,29 @@ export const ml = { hasPrivileges(obj: any) { const body = JSON.stringify(obj); - return http({ + return http({ path: `${basePath()}/_has_privileges`, method: 'POST', body, }); }, - checkMlPrivileges(): Promise { - return http({ + checkMlPrivileges() { + return http({ path: `${basePath()}/ml_capabilities`, method: 'GET', }); }, - checkManageMLPrivileges(): Promise { - return http({ + checkManageMLPrivileges() { + return http({ path: `${basePath()}/ml_capabilities?ignoreSpaces=true`, method: 'GET', }); }, getNotificationSettings() { - return http({ + return http({ path: `${basePath()}/notification_settings`, method: 'GET', }); @@ -318,7 +318,7 @@ export const ml = { ...(fields !== undefined ? { fields } : {}), }); - return http({ + return http({ path: `${basePath()}/indices/field_caps`, method: 'POST', body, @@ -326,34 +326,34 @@ export const ml = { }, recognizeIndex({ indexPatternTitle }: { indexPatternTitle: string }) { - return http({ + return http({ path: `${basePath()}/modules/recognize/${indexPatternTitle}`, method: 'GET', }); }, listDataRecognizerModules() { - return http({ + return http({ path: `${basePath()}/modules/get_module`, method: 'GET', }); }, - getDataRecognizerModule({ moduleId }: { moduleId: string }) { - return http({ + getDataRecognizerModule({ moduleId }: { moduleId: string }): Promise { + return http({ path: `${basePath()}/modules/get_module/${moduleId}`, method: 'GET', }); }, dataRecognizerModuleJobsExist({ moduleId }: { moduleId: string }) { - return http({ + return http({ path: `${basePath()}/modules/jobs_exist/${moduleId}`, method: 'GET', }); }, - setupDataRecognizerConfig({ + setupDataRecognizerConfig({ moduleId, prefix, groups, @@ -375,7 +375,7 @@ export const ml = { start?: number; end?: number; jobOverrides?: Array>; - }) { + }): Promise { const body = JSON.stringify({ prefix, groups, @@ -388,14 +388,14 @@ export const ml = { jobOverrides, }); - return http({ + return http({ path: `${basePath()}/modules/setup/${moduleId}`, method: 'POST', body, }); }, - getVisualizerFieldStats({ + getVisualizerFieldStats({ indexPatternTitle, query, timeFieldName, @@ -415,7 +415,7 @@ export const ml = { interval?: string; fields?: FieldRequestConfig[]; maxExamples?: number; - }) { + }): Promise { const body = JSON.stringify({ query, timeFieldName, @@ -427,7 +427,7 @@ export const ml = { maxExamples, }); - return http({ + return http({ path: `${basePath()}/data_visualizer/get_field_stats/${indexPatternTitle}`, method: 'POST', body, @@ -463,7 +463,7 @@ export const ml = { nonAggregatableFields, }); - return http({ + return http({ path: `${basePath()}/data_visualizer/get_overall_stats/${indexPatternTitle}`, method: 'POST', body, @@ -475,7 +475,7 @@ export const ml = { * @param obj * @returns {Promise} */ - calendars(obj?: { calendarId?: CalendarId; calendarIds?: CalendarId[] }): Promise { + calendars(obj?: { calendarId?: CalendarId; calendarIds?: CalendarId[] }) { const { calendarId, calendarIds } = obj || {}; let calendarIdsPathComponent = ''; if (calendarId) { @@ -483,7 +483,7 @@ export const ml = { } else if (calendarIds) { calendarIdsPathComponent = `/${calendarIds.join(',')}`; } - return http({ + return http({ path: `${basePath()}/calendars${calendarIdsPathComponent}`, method: 'GET', }); @@ -491,7 +491,7 @@ export const ml = { addCalendar(obj: Calendar) { const body = JSON.stringify(obj); - return http({ + return http({ path: `${basePath()}/calendars`, method: 'PUT', body, @@ -501,7 +501,7 @@ export const ml = { updateCalendar(obj: UpdateCalendar) { const calendarId = obj && obj.calendarId ? `/${obj.calendarId}` : ''; const body = JSON.stringify(obj); - return http({ + return http({ path: `${basePath()}/calendars${calendarId}`, method: 'PUT', body, @@ -509,21 +509,21 @@ export const ml = { }, deleteCalendar({ calendarId }: { calendarId?: string }) { - return http({ + return http({ path: `${basePath()}/calendars/${calendarId}`, method: 'DELETE', }); }, - mlNodeCount(): Promise<{ count: number }> { - return http({ + mlNodeCount() { + return http<{ count: number }>({ path: `${basePath()}/ml_node_count`, method: 'GET', }); }, - mlInfo(): Promise { - return http({ + mlInfo() { + return http({ path: `${basePath()}/info`, method: 'GET', }); @@ -547,7 +547,7 @@ export const ml = { timeFieldName: string; earliestMs: number; latestMs: number; - }): Promise<{ modelMemoryLimit: string }> { + }) { const body = JSON.stringify({ indexPattern, splitFieldName, @@ -559,7 +559,7 @@ export const ml = { latestMs, }); - return http({ + return http<{ modelMemoryLimit: string }>({ path: `${basePath()}/validate/calculate_model_memory_limit`, method: 'POST', body, @@ -583,7 +583,7 @@ export const ml = { }) { const body = JSON.stringify({ index, fieldNames, query, timeFieldName, earliestMs, latestMs }); - return http({ + return http({ path: `${basePath()}/fields_service/field_cardinality`, method: 'POST', body, @@ -598,37 +598,37 @@ export const ml = { index: string; timeFieldName?: string; query: any; - }): Promise { + }) { const body = JSON.stringify({ index, timeFieldName, query }); - return http({ + return http({ path: `${basePath()}/fields_service/time_field_range`, method: 'POST', body, }); }, - esSearch(obj: any): Promise { + esSearch(obj: any) { const body = JSON.stringify(obj); - return http({ + return http({ path: `${basePath()}/es_search`, method: 'POST', body, }); }, - esSearch$(obj: any): Observable { + esSearch$(obj: any) { const body = JSON.stringify(obj); - return http$({ + return http$({ path: `${basePath()}/es_search`, method: 'POST', body, }); }, - getIndices(): Promise> { + getIndices() { const tempBasePath = '/api'; - return http({ + return http>({ path: `${tempBasePath}/index_management/indices`, method: 'GET', }); diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts index 0d3164fb4bfe6..a1833aa8279ed 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts @@ -21,20 +21,18 @@ import { CATEGORY_EXAMPLES_VALIDATION_STATUS } from '../../../../common/constant import { Category } from '../../../../common/types/categories'; export const jobs = { - jobsSummary(jobIds: string[]): Promise { + jobsSummary(jobIds: string[]) { const body = JSON.stringify({ jobIds }); - return http({ + return http({ path: `${basePath()}/jobs/jobs_summary`, method: 'POST', body, }); }, - jobsWithTimerange( - dateFormatTz: string - ): Promise<{ jobs: MlJobWithTimeRange[]; jobsMap: Dictionary }> { + jobsWithTimerange(dateFormatTz: string) { const body = JSON.stringify({ dateFormatTz }); - return http({ + return http<{ jobs: MlJobWithTimeRange[]; jobsMap: Dictionary }>({ path: `${basePath()}/jobs/jobs_with_time_range`, method: 'POST', body, @@ -43,7 +41,7 @@ export const jobs = { jobs(jobIds: string[]) { const body = JSON.stringify({ jobIds }); - return http({ + return http({ path: `${basePath()}/jobs/jobs`, method: 'POST', body, @@ -51,7 +49,7 @@ export const jobs = { }, groups() { - return http({ + return http({ path: `${basePath()}/jobs/groups`, method: 'GET', }); @@ -59,7 +57,7 @@ export const jobs = { updateGroups(updatedJobs: string[]) { const body = JSON.stringify({ updatedJobs }); - return http({ + return http({ path: `${basePath()}/jobs/update_groups`, method: 'POST', body, @@ -73,7 +71,7 @@ export const jobs = { end, }); - return http({ + return http({ path: `${basePath()}/jobs/force_start_datafeeds`, method: 'POST', body, @@ -82,7 +80,7 @@ export const jobs = { stopDatafeeds(datafeedIds: string[]) { const body = JSON.stringify({ datafeedIds }); - return http({ + return http({ path: `${basePath()}/jobs/stop_datafeeds`, method: 'POST', body, @@ -91,7 +89,7 @@ export const jobs = { deleteJobs(jobIds: string[]) { const body = JSON.stringify({ jobIds }); - return http({ + return http({ path: `${basePath()}/jobs/delete_jobs`, method: 'POST', body, @@ -100,17 +98,17 @@ export const jobs = { closeJobs(jobIds: string[]) { const body = JSON.stringify({ jobIds }); - return http({ + return http({ path: `${basePath()}/jobs/close_jobs`, method: 'POST', body, }); }, - jobAuditMessages(jobId: string, from?: number): Promise { + jobAuditMessages(jobId: string, from?: number) { const jobIdString = jobId !== undefined ? `/${jobId}` : ''; const query = from !== undefined ? { from } : {}; - return http({ + return http({ path: `${basePath()}/job_audit_messages/messages${jobIdString}`, method: 'GET', query, @@ -118,7 +116,7 @@ export const jobs = { }, deletingJobTasks() { - return http({ + return http({ path: `${basePath()}/jobs/deleting_jobs_tasks`, method: 'GET', }); @@ -126,7 +124,7 @@ export const jobs = { jobsExist(jobIds: string[]) { const body = JSON.stringify({ jobIds }); - return http({ + return http({ path: `${basePath()}/jobs/jobs_exist`, method: 'POST', body, @@ -135,14 +133,14 @@ export const jobs = { newJobCaps(indexPatternTitle: string, isRollup: boolean = false) { const query = isRollup === true ? { rollup: true } : {}; - return http({ + return http({ path: `${basePath()}/jobs/new_job_caps/${indexPatternTitle}`, method: 'GET', query, }); }, - newJobLineChart( + newJobLineChart( indexPatternTitle: string, timeField: string, start: number, @@ -152,7 +150,7 @@ export const jobs = { aggFieldNamePairs: AggFieldNamePair[], splitFieldName: string | null, splitFieldValue: string | null - ) { + ): Promise { const body = JSON.stringify({ indexPatternTitle, timeField, @@ -164,14 +162,14 @@ export const jobs = { splitFieldName, splitFieldValue, }); - return http({ + return http({ path: `${basePath()}/jobs/new_job_line_chart`, method: 'POST', body, }); }, - newJobPopulationsChart( + newJobPopulationsChart( indexPatternTitle: string, timeField: string, start: number, @@ -180,7 +178,7 @@ export const jobs = { query: any, aggFieldNamePairs: AggFieldNamePair[], splitFieldName: string - ) { + ): Promise { const body = JSON.stringify({ indexPatternTitle, timeField, @@ -191,31 +189,27 @@ export const jobs = { aggFieldNamePairs, splitFieldName, }); - return http({ + return http({ path: `${basePath()}/jobs/new_job_population_chart`, method: 'POST', body, }); }, - getAllJobAndGroupIds(): Promise { - return http({ + getAllJobAndGroupIds() { + return http({ path: `${basePath()}/jobs/all_jobs_and_group_ids`, method: 'GET', }); }, - getLookBackProgress( - jobId: string, - start: number, - end: number - ): Promise<{ progress: number; isRunning: boolean; isJobClosed: boolean }> { + getLookBackProgress(jobId: string, start: number, end: number) { const body = JSON.stringify({ jobId, start, end, }); - return http({ + return http<{ progress: number; isRunning: boolean; isJobClosed: boolean }>({ path: `${basePath()}/jobs/look_back_progress`, method: 'POST', body, @@ -231,12 +225,7 @@ export const jobs = { start: number, end: number, analyzer: CategorizationAnalyzer - ): Promise<{ - examples: CategoryFieldExample[]; - sampleSize: number; - overallValidStatus: CATEGORY_EXAMPLES_VALIDATION_STATUS; - validationChecks: FieldExampleCheck[]; - }> { + ) { const body = JSON.stringify({ indexPatternTitle, query, @@ -247,19 +236,21 @@ export const jobs = { end, analyzer, }); - return http({ + return http<{ + examples: CategoryFieldExample[]; + sampleSize: number; + overallValidStatus: CATEGORY_EXAMPLES_VALIDATION_STATUS; + validationChecks: FieldExampleCheck[]; + }>({ path: `${basePath()}/jobs/categorization_field_examples`, method: 'POST', body, }); }, - topCategories( - jobId: string, - count: number - ): Promise<{ total: number; categories: Array<{ count?: number; category: Category }> }> { + topCategories(jobId: string, count: number) { const body = JSON.stringify({ jobId, count }); - return http({ + return http<{ total: number; categories: Array<{ count?: number; category: Category }> }>({ path: `${basePath()}/jobs/top_categories`, method: 'POST', body, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts index 2e5cc8af04d36..059ef118a0ade 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts @@ -5,8 +5,6 @@ */ // Service for obtaining data for the ML Results dashboards. - -import { Observable } from 'rxjs'; import { http, http$ } from '../http_service'; import { basePath } from './index'; @@ -42,20 +40,20 @@ export const results = { influencersFilterQuery, }); - return http$({ + return http$({ path: `${basePath()}/results/anomalies_table_data`, method: 'POST', body, }); }, - getMaxAnomalyScore(jobIds: string[], earliestMs: number, latestMs: number) { + getMaxAnomalyScore(jobIds: string[], earliestMs: number, latestMs: number): Promise { const body = JSON.stringify({ jobIds, earliestMs, latestMs, }); - return http({ + return http({ path: `${basePath()}/results/max_anomaly_score`, method: 'POST', body, @@ -64,7 +62,7 @@ export const results = { getCategoryDefinition(jobId: string, categoryId: string) { const body = JSON.stringify({ jobId, categoryId }); - return http({ + return http({ path: `${basePath()}/results/category_definition`, method: 'POST', body, @@ -77,7 +75,7 @@ export const results = { categoryIds, maxExamples, }); - return http({ + return http({ path: `${basePath()}/results/category_examples`, method: 'POST', body, @@ -90,9 +88,9 @@ export const results = { criteriaFields: Array<{ fieldName: string; fieldValue: any }>, earliestMs: number, latestMs: number - ): Observable { + ) { const body = JSON.stringify({ jobId, searchTerm, criteriaFields, earliestMs, latestMs }); - return http$({ + return http$({ path: `${basePath()}/results/partition_fields_values`, method: 'POST', body, From 022c93f82b148484dda05c88c4b10403dea4e8a8 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Thu, 12 Mar 2020 09:19:20 +0000 Subject: [PATCH 6/9] removes some generics --- .../index_based/data_loader/data_loader.ts | 2 +- .../new_job/common/chart_loader/chart_loader.ts | 8 ++++---- .../application/jobs/new_job/recognize/page.tsx | 6 ++---- .../anomaly_detection_panel.tsx | 6 +----- .../services/ml_api_service/index.ts | 17 +++++++++-------- .../application/services/ml_api_service/jobs.ts | 12 ++++++------ .../services/ml_api_service/results.ts | 4 ++-- 7 files changed, 25 insertions(+), 30 deletions(-) diff --git a/x-pack/legacy/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/legacy/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts index 931d767f1f1cd..b0d8fa3d4fa88 100644 --- a/x-pack/legacy/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts +++ b/x-pack/legacy/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts @@ -76,7 +76,7 @@ export class DataLoader { fields: FieldRequestConfig[], interval?: string ): Promise { - const stats = await ml.getVisualizerFieldStats({ + const stats = await ml.getVisualizerFieldStats({ indexPatternTitle: this._indexPatternTitle, query, timeFieldName: this._indexPattern.timeFieldName, diff --git a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts index fb2f2099bcc0a..5e92ab67fcc79 100644 --- a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts +++ b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts @@ -24,10 +24,10 @@ export type LineChartData = Record; const eq = (newArgs: any[], lastArgs: any[]) => isEqual(newArgs, lastArgs); -const newJobLineChart = memoizeOne(ml.jobs.newJobLineChart, eq); -const newJobPopulationsChart = memoizeOne(ml.jobs.newJobPopulationsChart, eq); -const getEventRateData = memoizeOne(mlResultsService.getEventRateData, eq); -const getCategoryFields = memoizeOne(getCategoryFieldsOrig, eq); +const newJobLineChart = memoizeOne(ml.jobs.newJobLineChart, eq); +const newJobPopulationsChart = memoizeOne(ml.jobs.newJobPopulationsChart, eq); +const getEventRateData = memoizeOne(mlResultsService.getEventRateData, eq); +const getCategoryFields = memoizeOne(getCategoryFieldsOrig, eq); export class ChartLoader { private _indexPatternTitle: IndexPatternTitle = ''; diff --git a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/recognize/page.tsx b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/recognize/page.tsx index ddaaeaa8566be..50c35ec426acb 100644 --- a/x-pack/legacy/plugins/ml/public/application/jobs/new_job/recognize/page.tsx +++ b/x-pack/legacy/plugins/ml/public/application/jobs/new_job/recognize/page.tsx @@ -26,12 +26,10 @@ import { ml } from '../../../services/ml_api_service'; import { useMlContext } from '../../../contexts/ml'; import { DatafeedResponse, - DataRecognizerConfigResponse, JobOverride, JobResponse, KibanaObject, KibanaObjectResponse, - Module, ModuleJob, } from '../../../../../common/types/modules'; import { mlJobService } from '../../../services/job_service'; @@ -106,7 +104,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { */ const loadModule = async () => { try { - const response = await ml.getDataRecognizerModule({ moduleId }); + const response = await ml.getDataRecognizerModule({ moduleId }); setJobs(response.jobs); const kibanaObjectsResult = await checkForSavedObjects(response.kibana as KibanaObjects); @@ -165,7 +163,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { let jobOverridesPayload: JobOverride[] | null = Object.values(jobOverrides); jobOverridesPayload = jobOverridesPayload.length > 0 ? jobOverridesPayload : null; - const response = await ml.setupDataRecognizerConfig({ + const response = await ml.setupDataRecognizerConfig({ moduleId, prefix: resultJobPrefix, query: tempQuery, diff --git a/x-pack/legacy/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx b/x-pack/legacy/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx index 44356aa169f68..5f5c3f7c28670 100644 --- a/x-pack/legacy/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx +++ b/x-pack/legacy/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx @@ -102,11 +102,7 @@ export const AnomalyDetectionPanel: FC = ({ jobCreationDisabled }) => { const latestTimestamp = group.latest_timestamp; const startMoment = moment(latestTimestamp); const twentyFourHoursAgo = startMoment.subtract(24, 'hours').valueOf(); - return ml.results.getMaxAnomalyScore( - group.jobIds, - twentyFourHoursAgo, - latestTimestamp - ); + return ml.results.getMaxAnomalyScore(group.jobIds, twentyFourHoursAgo, latestTimestamp); }); const results = await Promise.all(promises); diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts index 2c7ff0a0325a8..a2310c591671d 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts @@ -25,6 +25,7 @@ import { } from '../../../../common/types/anomaly_detection_jobs'; import { ES_AGGREGATION } from '../../../../common/constants/aggregation_types'; import { FieldRequestConfig } from '../../datavisualizer/index_based/common'; +import { DataRecognizerConfigResponse, Module } from '../../../../common/types/modules'; export interface MlInfoResponse { defaults: MlServerDefaults; @@ -339,8 +340,8 @@ export const ml = { }); }, - getDataRecognizerModule({ moduleId }: { moduleId: string }): Promise { - return http({ + getDataRecognizerModule({ moduleId }: { moduleId: string }) { + return http({ path: `${basePath()}/modules/get_module/${moduleId}`, method: 'GET', }); @@ -353,7 +354,7 @@ export const ml = { }); }, - setupDataRecognizerConfig({ + setupDataRecognizerConfig({ moduleId, prefix, groups, @@ -375,7 +376,7 @@ export const ml = { start?: number; end?: number; jobOverrides?: Array>; - }): Promise { + }) { const body = JSON.stringify({ prefix, groups, @@ -388,14 +389,14 @@ export const ml = { jobOverrides, }); - return http({ + return http({ path: `${basePath()}/modules/setup/${moduleId}`, method: 'POST', body, }); }, - getVisualizerFieldStats({ + getVisualizerFieldStats({ indexPatternTitle, query, timeFieldName, @@ -415,7 +416,7 @@ export const ml = { interval?: string; fields?: FieldRequestConfig[]; maxExamples?: number; - }): Promise { + }) { const body = JSON.stringify({ query, timeFieldName, @@ -427,7 +428,7 @@ export const ml = { maxExamples, }); - return http({ + return http({ path: `${basePath()}/data_visualizer/get_field_stats/${indexPatternTitle}`, method: 'POST', body, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts index a1833aa8279ed..4010d6a467f5b 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts @@ -140,7 +140,7 @@ export const jobs = { }); }, - newJobLineChart( + newJobLineChart( indexPatternTitle: string, timeField: string, start: number, @@ -150,7 +150,7 @@ export const jobs = { aggFieldNamePairs: AggFieldNamePair[], splitFieldName: string | null, splitFieldValue: string | null - ): Promise { + ) { const body = JSON.stringify({ indexPatternTitle, timeField, @@ -162,14 +162,14 @@ export const jobs = { splitFieldName, splitFieldValue, }); - return http({ + return http({ path: `${basePath()}/jobs/new_job_line_chart`, method: 'POST', body, }); }, - newJobPopulationsChart( + newJobPopulationsChart( indexPatternTitle: string, timeField: string, start: number, @@ -178,7 +178,7 @@ export const jobs = { query: any, aggFieldNamePairs: AggFieldNamePair[], splitFieldName: string - ): Promise { + ) { const body = JSON.stringify({ indexPatternTitle, timeField, @@ -189,7 +189,7 @@ export const jobs = { aggFieldNamePairs, splitFieldName, }); - return http({ + return http({ path: `${basePath()}/jobs/new_job_population_chart`, method: 'POST', body, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts index 059ef118a0ade..830e6fab4163a 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/results.ts @@ -47,13 +47,13 @@ export const results = { }); }, - getMaxAnomalyScore(jobIds: string[], earliestMs: number, latestMs: number): Promise { + getMaxAnomalyScore(jobIds: string[], earliestMs: number, latestMs: number) { const body = JSON.stringify({ jobIds, earliestMs, latestMs, }); - return http({ + return http({ path: `${basePath()}/results/max_anomaly_score`, method: 'POST', body, From 049f0e501e97a9c4eef3c9e50841665dcb18b5c9 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Thu, 12 Mar 2020 09:21:06 +0000 Subject: [PATCH 7/9] update comment --- .../ml/public/application/services/ml_api_service/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts index a2310c591671d..2f6ce24b93e47 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts @@ -474,7 +474,7 @@ export const ml = { /** * Gets a list of calendars * @param obj - * @returns {Promise} + * @returns {Promise} */ calendars(obj?: { calendarId?: CalendarId; calendarIds?: CalendarId[] }) { const { calendarId, calendarIds } = obj || {}; From 3ecbba2cde9aa3d199d979b06f3472cedf3a47f0 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Thu, 12 Mar 2020 09:52:48 +0000 Subject: [PATCH 8/9] updating data frame analytics types --- .../services/ml_api_service/data_frame_analytics.ts | 6 +++--- .../ml/public/application/services/ml_api_service/index.ts | 3 ++- .../ml/public/application/services/ml_api_service/jobs.ts | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts index 9fa595259e062..0d2077e08c35f 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts @@ -52,7 +52,7 @@ export const dataFrameAnalytics = { method: 'GET', }); }, - createDataFrameAnalytics(analyticsId: string, analyticsConfig: any) { + createDataFrameAnalytics(analyticsId: string, analyticsConfig: DataFrameAnalyticsConfig) { const body = JSON.stringify(analyticsConfig); return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}`, @@ -60,7 +60,7 @@ export const dataFrameAnalytics = { body, }); }, - evaluateDataFrameAnalytics(evaluateConfig: any) { + evaluateDataFrameAnalytics(evaluateConfig: DataFrameAnalyticsConfig) { const body = JSON.stringify(evaluateConfig); return http({ path: `${basePath()}/data_frame/_evaluate`, @@ -68,7 +68,7 @@ export const dataFrameAnalytics = { body, }); }, - explainDataFrameAnalytics(jobConfig: any) { + explainDataFrameAnalytics(jobConfig: DataFrameAnalyticsConfig) { const body = JSON.stringify(jobConfig); return http({ path: `${basePath()}/data_frame/analytics/_explain`, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts index 2f6ce24b93e47..36410c6c8ef27 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts @@ -301,8 +301,9 @@ export const ml = { checkManageMLPrivileges() { return http({ - path: `${basePath()}/ml_capabilities?ignoreSpaces=true`, + path: `${basePath()}/ml_capabilities`, method: 'GET', + query: { ignoreSpaces: true }, }); }, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts index 4010d6a467f5b..bcceffb14123e 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/jobs.ts @@ -56,7 +56,7 @@ export const jobs = { }, updateGroups(updatedJobs: string[]) { - const body = JSON.stringify({ updatedJobs }); + const body = JSON.stringify({ jobs: updatedJobs }); return http({ path: `${basePath()}/jobs/update_groups`, method: 'POST', From aa503f48a010ac69a7828d7c89fc1fae6e04bafe Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Thu, 12 Mar 2020 11:30:33 +0000 Subject: [PATCH 9/9] fixing type errors --- .../services/ml_api_service/data_frame_analytics.ts | 10 +++++++--- .../application/services/ml_api_service/index.ts | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts index 0d2077e08c35f..89950a659f609 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/data_frame_analytics.ts @@ -9,6 +9,7 @@ import { http } from '../http_service'; import { basePath } from './index'; import { DataFrameAnalyticsStats } from '../../data_frame_analytics/pages/analytics_management/components/analytics_list/common'; import { DataFrameAnalyticsConfig } from '../../data_frame_analytics/common'; +import { DeepPartial } from '../../../../common/types/common'; export interface GetDataFrameAnalyticsStatsResponseOk { node_failures?: object; @@ -52,7 +53,10 @@ export const dataFrameAnalytics = { method: 'GET', }); }, - createDataFrameAnalytics(analyticsId: string, analyticsConfig: DataFrameAnalyticsConfig) { + createDataFrameAnalytics( + analyticsId: string, + analyticsConfig: DeepPartial + ) { const body = JSON.stringify(analyticsConfig); return http({ path: `${basePath()}/data_frame/analytics/${analyticsId}`, @@ -60,7 +64,7 @@ export const dataFrameAnalytics = { body, }); }, - evaluateDataFrameAnalytics(evaluateConfig: DataFrameAnalyticsConfig) { + evaluateDataFrameAnalytics(evaluateConfig: any) { const body = JSON.stringify(evaluateConfig); return http({ path: `${basePath()}/data_frame/_evaluate`, @@ -68,7 +72,7 @@ export const dataFrameAnalytics = { body, }); }, - explainDataFrameAnalytics(jobConfig: DataFrameAnalyticsConfig) { + explainDataFrameAnalytics(jobConfig: DeepPartial) { const body = JSON.stringify(jobConfig); return http({ path: `${basePath()}/data_frame/analytics/_explain`, diff --git a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts index 36410c6c8ef27..b8e21898a4bb3 100644 --- a/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/legacy/plugins/ml/public/application/services/ml_api_service/index.ts @@ -13,7 +13,7 @@ import { filters } from './filters'; import { results } from './results'; import { jobs } from './jobs'; import { fileDatavisualizer } from './datavisualizer'; -import { MlServerDefaults, MlServerLimits } from '../ml_server_info'; +import { MlServerDefaults, MlServerLimits } from '../../../../common/types/ml_server_info'; import { PrivilegesResponse } from '../../../../common/types/privileges'; import { Calendar, CalendarId, UpdateCalendar } from '../../../../common/types/calendars';