diff --git a/.eslintrc.js b/.eslintrc.js index 106724c323d30..e01632815bc68 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -209,13 +209,6 @@ module.exports = { 'react-hooks/rules-of-hooks': 'off', }, }, - { - files: ['x-pack/legacy/plugins/watcher/**/*.{js,ts,tsx}'], - rules: { - 'react-hooks/rules-of-hooks': 'off', - 'react-hooks/exhaustive-deps': 'off', - }, - }, /** * Prettier diff --git a/src/legacy/ui/public/time_buckets/index.d.ts b/src/legacy/ui/public/time_buckets/index.d.ts new file mode 100644 index 0000000000000..70b9495b81f0e --- /dev/null +++ b/src/legacy/ui/public/time_buckets/index.d.ts @@ -0,0 +1,22 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +declare module 'ui/time_buckets' { + export const TimeBuckets: any; +} diff --git a/src/plugins/es_ui_shared/public/request/np_ready_request.ts b/src/plugins/es_ui_shared/public/request/np_ready_request.ts index 48c7904661e51..5a3f28ed76486 100644 --- a/src/plugins/es_ui_shared/public/request/np_ready_request.ts +++ b/src/plugins/es_ui_shared/public/request/np_ready_request.ts @@ -19,11 +19,12 @@ import { useEffect, useState, useRef } from 'react'; -import { HttpServiceBase } from '../../../../../src/core/public'; +import { HttpServiceBase, HttpFetchQuery } from '../../../../../src/core/public'; export interface SendRequestConfig { path: string; method: 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head'; + query?: HttpFetchQuery; body?: any; } @@ -48,10 +49,10 @@ export interface UseRequestResponse { export const sendRequest = async ( httpClient: HttpServiceBase, - { path, method, body }: SendRequestConfig + { path, method, body, query }: SendRequestConfig ): Promise => { try { - const response = await httpClient[method](path, { body }); + const response = await httpClient[method](path, { body, query }); return { data: response.data ? response.data : response, @@ -70,6 +71,7 @@ export const useRequest = ( { path, method, + query, body, pollIntervalMs, initialData, @@ -112,6 +114,7 @@ export const useRequest = ( const requestBody = { path, method, + query, body, }; diff --git a/x-pack/dev-tools/jest/create_jest_config.js b/x-pack/dev-tools/jest/create_jest_config.js index 255b8a5e03981..b26c1c9e226cc 100644 --- a/x-pack/dev-tools/jest/create_jest_config.js +++ b/x-pack/dev-tools/jest/create_jest_config.js @@ -20,7 +20,8 @@ export function createJestConfig({ kibanaDirectory, xPackKibanaDirectory }) { 'uiExports/(.*)': fileMockPath, '^src/core/(.*)': `${kibanaDirectory}/src/core/$1`, '^src/legacy/(.*)': `${kibanaDirectory}/src/legacy/$1`, - '^plugins/watcher/models/(.*)': `${xPackKibanaDirectory}/legacy/plugins/watcher/public/models/$1`, + '^plugins/watcher/np_ready/application/models/(.*)': + `${xPackKibanaDirectory}/legacy/plugins/watcher/public/np_ready/application/models/$1`, '^plugins/([^/.]*)(.*)': `${kibanaDirectory}/src/legacy/core_plugins/$1/public$2`, '^plugins/xpack_main/(.*);': `${xPackKibanaDirectory}/legacy/plugins/xpack_main/public/$1`, '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': fileMockPath, diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx new file mode 100644 index 0000000000000..de285ee15b59d --- /dev/null +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx @@ -0,0 +1,50 @@ +/* + * 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 React from 'react'; +import { ComponentType } from 'enzyme'; +import { + chromeServiceMock, + docLinksServiceMock, + uiSettingsServiceMock, + notificationServiceMock, + httpServiceMock, +} from '../../../../../../../src/core/public/mocks'; +import { AppContextProvider } from '../../../public/np_ready/application/app_context'; + +export const mockContextValue = { + docLinks: docLinksServiceMock.createStartContract(), + chrome: chromeServiceMock.createStartContract(), + legacy: { + TimeBuckets: class MockTimeBuckets { + setBounds(_domain: any) { + return {}; + } + getInterval() { + return { + expression: {}, + }; + } + }, + MANAGEMENT_BREADCRUMB: { text: 'test' }, + licenseStatus: {}, + }, + uiSettings: uiSettingsServiceMock.createSetupContract(), + toasts: notificationServiceMock.createSetupContract().toasts, + euiUtils: { + useChartsTheme: jest.fn(), + }, + // For our test harness, we don't use this mocked out http service + http: httpServiceMock.createSetupContract(), +}; + +export const withAppContext = (Component: ComponentType) => (props: any) => { + return ( + + + + ); +}; diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/fields/index.js b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/body_response.ts similarity index 56% rename from x-pack/legacy/plugins/watcher/server/routes/api/fields/index.js rename to x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/body_response.ts index 8474f8a614bfb..3b3df5fd6f879 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/fields/index.js +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/body_response.ts @@ -4,4 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -export { registerFieldsRoutes } from './register_fields_routes'; +export const wrapBodyResponse = (obj: object) => JSON.stringify({ body: JSON.stringify(obj) }); + +export const unwrapBodyResponse = (string: string) => JSON.parse(JSON.parse(string).body); diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts index 2170559dace5a..7d9c1e4163d7b 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts @@ -34,7 +34,7 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { const defaultResponse = { watchHistoryItems: [] }; server.respondWith( 'GET', - `${API_ROOT}/watch/:id/history?startTime=*`, + `${API_ROOT}/watch/:id/history`, mockResponse(defaultResponse, response) ); }; diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/index.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/index.ts index ad005078db0a8..814028fe599ff 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/index.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/index.ts @@ -11,7 +11,7 @@ import { setup as watchCreateThresholdSetup } from './watch_create_threshold.hel import { setup as watchEditSetup } from './watch_edit.helpers'; export { nextTick, getRandomString, findTestSubject, TestBed } from '../../../../../../test_utils'; - +export { wrapBodyResponse, unwrapBodyResponse } from './body_response'; export { setupEnvironment } from './setup_environment'; export const pageHelpers = { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts index 806840a7821fd..7e748073c1c6b 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts @@ -7,9 +7,17 @@ import axios from 'axios'; import axiosXhrAdapter from 'axios/lib/adapters/xhr'; import { init as initHttpRequests } from './http_requests'; -import { setHttpClient, setSavedObjectsClient } from '../../../public/lib/api'; +import { setHttpClient, setSavedObjectsClient } from '../../../public/np_ready/application/lib/api'; const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); +mockHttpClient.interceptors.response.use( + res => { + return res.data; + }, + rej => { + return Promise.reject(rej); + } +); const mockSavedObjectsClient = () => { return { @@ -23,7 +31,7 @@ export const setupEnvironment = () => { // @ts-ignore setHttpClient(mockHttpClient); - setSavedObjectsClient(mockSavedObjectsClient()); + setSavedObjectsClient(mockSavedObjectsClient() as any); return { server, diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts index bea215281a4bc..dafcf3a7070d2 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts @@ -3,10 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { withAppContext } from './app_context.mock'; import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils'; -import { WatchEdit } from '../../../public/sections/watch_edit/components/watch_edit'; +import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit'; import { ROUTES, WATCH_TYPES } from '../../../common/constants'; -import { registerRouter } from '../../../public/lib/navigation'; +import { registerRouter } from '../../../public/np_ready/application/lib/navigation'; const testBedConfig: TestBedConfig = { memoryRouter: { @@ -17,7 +18,7 @@ const testBedConfig: TestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(WatchEdit, testBedConfig); +const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig); export interface WatchCreateJsonTestBed extends TestBed { actions: { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts index e33ae02036224..8cebe8ce26229 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts @@ -4,9 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils'; -import { WatchEdit } from '../../../public/sections/watch_edit/components/watch_edit'; +import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit'; import { ROUTES, WATCH_TYPES } from '../../../common/constants'; -import { registerRouter } from '../../../public/lib/navigation'; +import { registerRouter } from '../../../public/np_ready/application/lib/navigation'; +import { withAppContext } from './app_context.mock'; const testBedConfig: TestBedConfig = { memoryRouter: { @@ -17,7 +18,7 @@ const testBedConfig: TestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(WatchEdit, testBedConfig); +const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig); export interface WatchCreateThresholdTestBed extends TestBed { actions: { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts index d0b458e30c70e..187f4dcaa0a76 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts @@ -4,10 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils'; -import { WatchEdit } from '../../../public/sections/watch_edit/components/watch_edit'; +import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit'; import { ROUTES } from '../../../common/constants'; -import { registerRouter } from '../../../public/lib/navigation'; +import { registerRouter } from '../../../public/np_ready/application/lib/navigation'; import { WATCH_ID } from './constants'; +import { withAppContext } from './app_context.mock'; const testBedConfig: TestBedConfig = { memoryRouter: { @@ -18,7 +19,7 @@ const testBedConfig: TestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(WatchEdit, testBedConfig); +const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig); export interface WatchEditTestBed extends TestBed { actions: { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts index 0d3ecaa7a2b9a..e33327ea42ffe 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts @@ -13,8 +13,9 @@ import { TestBedConfig, nextTick, } from '../../../../../../test_utils'; -import { WatchList } from '../../../public/sections/watch_list/components/watch_list'; +import { WatchList } from '../../../public/np_ready/application/sections/watch_list/components/watch_list'; import { ROUTES } from '../../../common/constants'; +import { withAppContext } from './app_context.mock'; const testBedConfig: TestBedConfig = { memoryRouter: { @@ -23,7 +24,7 @@ const testBedConfig: TestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(WatchList, testBedConfig); +const initTestBed = registerTestBed(withAppContext(WatchList), testBedConfig); export interface WatchListTestBed extends TestBed { actions: { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts index 22d57f255ebe6..e7bffe8924e31 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts @@ -13,9 +13,10 @@ import { TestBedConfig, nextTick, } from '../../../../../../test_utils'; -import { WatchStatus } from '../../../public/sections/watch_status/components/watch_status'; +import { WatchStatus } from '../../../public/np_ready/application/sections/watch_status/components/watch_status'; import { ROUTES } from '../../../common/constants'; import { WATCH_ID } from './constants'; +import { withAppContext } from './app_context.mock'; const testBedConfig: TestBedConfig = { memoryRouter: { @@ -25,7 +26,7 @@ const testBedConfig: TestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(WatchStatus, testBedConfig); +const initTestBed = registerTestBed(withAppContext(WatchStatus), testBedConfig); export interface WatchStatusTestBed extends TestBed { actions: { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts index f45dbe156723b..4c893978ee5cb 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts @@ -4,22 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ import { act } from 'react-dom/test-utils'; -import { setupEnvironment, pageHelpers, nextTick } from './helpers'; +import { setupEnvironment, pageHelpers, nextTick, wrapBodyResponse } from './helpers'; import { WatchCreateJsonTestBed } from './helpers/watch_create_json.helpers'; import { WATCH } from './helpers/constants'; -import defaultWatchJson from '../../public/models/watch/default_watch.json'; +import defaultWatchJson from '../../public/np_ready/application/models/watch/default_watch.json'; import { getExecuteDetails } from '../../test/fixtures'; -jest.mock('ui/chrome', () => ({ - breadcrumbs: { set: () => {} }, - addBasePath: (path: string) => path || '/api/watcher', -})); - -jest.mock('ui/time_buckets', () => {}); - const { setup } = pageHelpers.watchCreateJson; -describe.skip(' create route', () => { +describe(' create route', () => { const { server, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchCreateJsonTestBed; @@ -107,7 +100,7 @@ describe.skip(' create route', () => { 'There are {{ctx.payload.hits.total}} documents in your index. Threshold is 10.'; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ id: watch.id, name: watch.name, type: watch.type, @@ -194,7 +187,7 @@ describe.skip(' create route', () => { }; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ actionModes, }), @@ -258,7 +251,7 @@ describe.skip(' create route', () => { const scheduledTime = `now+${SCHEDULED_TIME}s`; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ triggerData: { triggeredTime, diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx index 62cfd92182091..36a5c150eead7 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx @@ -7,7 +7,13 @@ import React from 'react'; import { act } from 'react-dom/test-utils'; import axiosXhrAdapter from 'axios/lib/adapters/xhr'; import axios from 'axios'; -import { setupEnvironment, pageHelpers, nextTick } from './helpers'; +import { + setupEnvironment, + pageHelpers, + nextTick, + wrapBodyResponse, + unwrapBodyResponse, +} from './helpers'; import { WatchCreateThresholdTestBed } from './helpers/watch_create_threshold.helpers'; import { getExecuteDetails } from '../../test/fixtures'; import { WATCH_TYPES } from '../../common/constants'; @@ -42,31 +48,8 @@ const WATCH_VISUALIZE_DATA = { const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); -jest.mock('ui/chrome', () => ({ - breadcrumbs: { set: () => {} }, - addBasePath: (path: string) => path || '/api/watcher', - getUiSettingsClient: () => ({ - get: () => {}, - isDefault: () => true, - }), -})); - -jest.mock('ui/time_buckets', () => { - class MockTimeBuckets { - setBounds(_domain: any) { - return {}; - } - getInterval() { - return { - expression: {}, - }; - } - } - return { TimeBuckets: MockTimeBuckets }; -}); - -jest.mock('../../public/lib/api', () => ({ - ...jest.requireActual('../../public/lib/api'), +jest.mock('../../public/np_ready/application/lib/api', () => ({ + ...jest.requireActual('../../public/np_ready/application/lib/api'), loadIndexPatterns: async () => { const INDEX_PATTERNS = [ { attributes: { title: 'index1' } }, @@ -85,7 +68,7 @@ jest.mock('@elastic/eui', () => ({ EuiComboBox: (props: any) => ( { + onChange={(syntheticEvent: any) => { props.onChange([syntheticEvent['0']]); }} /> @@ -94,7 +77,7 @@ jest.mock('@elastic/eui', () => ({ const { setup } = pageHelpers.watchCreateThreshold; -describe.skip(' create route', () => { +describe(' create route', () => { const { server, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchCreateThresholdTestBed; @@ -105,12 +88,9 @@ describe.skip(' create route', () => { describe('on component mount', () => { beforeEach(async () => { testBed = await setup(); - - await act(async () => { - const { component } = testBed; - await nextTick(); - component.update(); - }); + const { component } = testBed; + await nextTick(); + component.update(); }); test('should set the correct page title', () => { @@ -125,13 +105,6 @@ describe.skip(' create route', () => { httpRequestsMockHelpers.setLoadEsFieldsResponse({ fields: ES_FIELDS }); httpRequestsMockHelpers.setLoadSettingsResponse(SETTINGS); httpRequestsMockHelpers.setLoadWatchVisualizeResponse(WATCH_VISUALIZE_DATA); - - testBed = await setup(); - - await act(async () => { - await nextTick(); - testBed.component.update(); - }); }); describe('form validation', () => { @@ -173,7 +146,7 @@ describe.skip(' create route', () => { expect(find('saveWatchButton').props().disabled).toEqual(true); }); - test('it should enable the Create button and render additonal content with valid fields', async () => { + test('it should enable the Create button and render additional content with valid fields', async () => { const { form, find, component, exists } = testBed; form.setInputValue('nameInput', 'my_test_watch'); @@ -192,39 +165,30 @@ describe.skip(' create route', () => { expect(exists('watchActionsPanel')).toBe(true); }); - describe('watch conditions', () => { - beforeEach(async () => { - const { form, find, component } = testBed; + // Looks like there is an issue with using 'mockComboBox'. + describe.skip('watch conditions', () => { + beforeEach(() => { + const { form, find } = testBed; // Name, index and time fields are required before the watch condition expression renders form.setInputValue('nameInput', 'my_test_watch'); - find('mockComboBox').simulate('change', [{ label: 'index1', value: 'index1' }]); // Using mocked EuiComboBox - form.setInputValue('watchTimeFieldSelect', '@timestamp'); - - await act(async () => { - await nextTick(); - component.update(); + act(() => { + find('mockComboBox').simulate('change', [{ label: 'index1', value: 'index1' }]); // Using mocked EuiComboBox }); + form.setInputValue('watchTimeFieldSelect', '@timestamp'); }); - test('should require a threshold value', async () => { - const { form, find, component } = testBed; - - find('watchThresholdButton').simulate('click'); + test('should require a threshold value', () => { + const { form, find } = testBed; - // Provide invalid value - form.setInputValue('watchThresholdInput', ''); - - expect(form.getErrorsMessages()).toContain('A value is required.'); - - // Provide valid value - form.setInputValue('watchThresholdInput', '0'); - - await act(async () => { - await nextTick(); - component.update(); + act(() => { + find('watchThresholdButton').simulate('click'); + // Provide invalid value + form.setInputValue('watchThresholdInput', ''); + // Provide valid value + form.setInputValue('watchThresholdInput', '0'); }); - + expect(form.getErrorsMessages()).toContain('A value is required.'); expect(form.getErrorsMessages().length).toEqual(0); }); }); @@ -273,7 +237,7 @@ describe.skip(' create route', () => { const latestRequest = server.requests[server.requests.length - 1]; const thresholdWatch = { - id: JSON.parse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -300,7 +264,7 @@ describe.skip(' create route', () => { }; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ actionModes: { logging_1: 'force_execute', @@ -341,7 +305,7 @@ describe.skip(' create route', () => { const latestRequest = server.requests[server.requests.length - 1]; const thresholdWatch = { - id: JSON.parse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -367,7 +331,7 @@ describe.skip(' create route', () => { }; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ actionModes: { index_1: 'force_execute', @@ -401,7 +365,7 @@ describe.skip(' create route', () => { const latestRequest = server.requests[server.requests.length - 1]; const thresholdWatch = { - id: JSON.parse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -430,7 +394,7 @@ describe.skip(' create route', () => { }; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ actionModes: { slack_1: 'force_execute', @@ -471,7 +435,7 @@ describe.skip(' create route', () => { const latestRequest = server.requests[server.requests.length - 1]; const thresholdWatch = { - id: JSON.parse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -504,7 +468,7 @@ describe.skip(' create route', () => { }; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ actionModes: { email_1: 'force_execute', @@ -559,7 +523,7 @@ describe.skip(' create route', () => { const latestRequest = server.requests[server.requests.length - 1]; const thresholdWatch = { - id: JSON.parse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -594,7 +558,7 @@ describe.skip(' create route', () => { }; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ actionModes: { webhook_1: 'force_execute', @@ -645,7 +609,7 @@ describe.skip(' create route', () => { const latestRequest = server.requests[server.requests.length - 1]; const thresholdWatch = { - id: JSON.parse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -682,7 +646,7 @@ describe.skip(' create route', () => { }; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ actionModes: { jira_1: 'force_execute', @@ -723,7 +687,7 @@ describe.skip(' create route', () => { const latestRequest = server.requests[server.requests.length - 1]; const thresholdWatch = { - id: JSON.parse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -750,7 +714,7 @@ describe.skip(' create route', () => { }; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ executeDetails: getExecuteDetails({ actionModes: { pagerduty_1: 'force_execute', @@ -784,7 +748,7 @@ describe.skip(' create route', () => { const latestRequest = server.requests[server.requests.length - 1]; const thresholdWatch = { - id: JSON.parse(latestRequest.requestBody).id, // watch ID is created dynamically + id: unwrapBodyResponse(latestRequest.requestBody).id, // watch ID is created dynamically name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -801,7 +765,7 @@ describe.skip(' create route', () => { threshold: 1000, }; - expect(latestRequest.requestBody).toEqual(JSON.stringify(thresholdWatch)); + expect(latestRequest.requestBody).toEqual(wrapBodyResponse(thresholdWatch)); }); }); }); diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_edit.test.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_edit.test.ts index fb9ad934249e9..1eee3d3b7e6ee 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_edit.test.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_edit.test.ts @@ -6,36 +6,17 @@ import { act } from 'react-dom/test-utils'; import axiosXhrAdapter from 'axios/lib/adapters/xhr'; import axios from 'axios'; -import { setupEnvironment, pageHelpers, nextTick } from './helpers'; +import { setupEnvironment, pageHelpers, nextTick, wrapBodyResponse } from './helpers'; import { WatchEditTestBed } from './helpers/watch_edit.helpers'; import { WATCH } from './helpers/constants'; -import defaultWatchJson from '../../public/models/watch/default_watch.json'; +import defaultWatchJson from '../../public/np_ready/application/models/watch/default_watch.json'; import { getWatch } from '../../test/fixtures'; import { getRandomString } from '../../../../../test_utils'; const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); -jest.mock('ui/chrome', () => ({ - breadcrumbs: { set: () => {} }, - addBasePath: (path: string) => path || '/api/watcher', -})); - -jest.mock('ui/time_buckets', () => { - class MockTimeBuckets { - setBounds(_domain: any) { - return {}; - } - getInterval() { - return { - expression: {}, - }; - } - } - return { TimeBuckets: MockTimeBuckets }; -}); - -jest.mock('../../public/lib/api', () => ({ - ...jest.requireActual('../../public/lib/api'), +jest.mock('../../public/np_ready/application/lib/api', () => ({ + ...jest.requireActual('../../public/np_ready/application/lib/api'), loadIndexPatterns: async () => { const INDEX_PATTERNS = [ { attributes: { title: 'index1' } }, @@ -49,7 +30,7 @@ jest.mock('../../public/lib/api', () => ({ const { setup } = pageHelpers.watchEdit; -describe.skip('', () => { +describe('', () => { const { server, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchEditTestBed; @@ -110,7 +91,7 @@ describe.skip('', () => { 'There are {{ctx.payload.hits.total}} documents in your index. Threshold is 10.'; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ id: watch.id, name: EDITED_WATCH_NAME, type: watch.type, @@ -202,7 +183,7 @@ describe.skip('', () => { } = watch; expect(latestRequest.requestBody).toEqual( - JSON.stringify({ + wrapBodyResponse({ id, name: EDITED_WATCH_NAME, type, diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_list.test.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_list.test.ts index bc2eadb7d9be9..a0327c6dfa1db 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_list.test.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_list.test.ts @@ -18,16 +18,9 @@ import { ROUTES } from '../../common/constants'; const { API_ROOT } = ROUTES; -jest.mock('ui/chrome', () => ({ - breadcrumbs: { set: () => {} }, - addBasePath: (path: string) => path || '/api/watcher', -})); - -jest.mock('ui/time_buckets', () => {}); - const { setup } = pageHelpers.watchList; -describe.skip('', () => { +describe('', () => { const { server, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchListTestBed; diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_status.test.ts b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_status.test.ts index e12acd2e32ccf..973c14893f342 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_status.test.ts +++ b/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_status.test.ts @@ -14,13 +14,6 @@ import { WATCH_STATES, ACTION_STATES } from '../../common/constants'; const { API_ROOT } = ROUTES; -jest.mock('ui/chrome', () => ({ - breadcrumbs: { set: () => {} }, - addBasePath: (path: string) => path || '/api/watcher', -})); - -jest.mock('ui/time_buckets', () => {}); - const { setup } = pageHelpers.watchStatus; const watchHistory1 = getWatchHistory({ startTime: '2019-06-04T01:11:11.294' }); @@ -45,7 +38,7 @@ const watch = { }, }; -describe.skip('', () => { +describe('', () => { const { server, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchStatusTestBed; diff --git a/x-pack/legacy/plugins/watcher/kibana.json b/x-pack/legacy/plugins/watcher/kibana.json new file mode 100644 index 0000000000000..ccec8a1b77683 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/kibana.json @@ -0,0 +1,9 @@ +{ + "id": "watcher", + "version": "kibana", + "requiredPlugins": [ + "home" + ], + "server": true, + "ui": true +} diff --git a/x-pack/legacy/plugins/watcher/plugin_definition.js b/x-pack/legacy/plugins/watcher/plugin_definition.js deleted file mode 100644 index 4a5946cc4974d..0000000000000 --- a/x-pack/legacy/plugins/watcher/plugin_definition.js +++ /dev/null @@ -1,46 +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 { resolve } from 'path'; -import { i18n } from '@kbn/i18n'; -import { registerFieldsRoutes } from './server/routes/api/fields'; -import { registerSettingsRoutes } from './server/routes/api/settings'; -import { registerHistoryRoutes } from './server/routes/api/history'; -import { registerIndicesRoutes } from './server/routes/api/indices'; -import { registerLicenseRoutes } from './server/routes/api/license'; -import { registerWatchesRoutes } from './server/routes/api/watches'; -import { registerWatchRoutes } from './server/routes/api/watch'; -import { registerLicenseChecker } from '../../server/lib/register_license_checker'; -import { PLUGIN } from './common/constants'; - -export const pluginDefinition = { - id: PLUGIN.ID, - configPrefix: 'xpack.watcher', - publicDir: resolve(__dirname, 'public'), - require: ['kibana', 'elasticsearch', 'xpack_main'], - uiExports: { - styleSheetPaths: resolve(__dirname, 'public/index.scss'), - managementSections: ['plugins/watcher'], - home: ['plugins/watcher/register_feature'], - }, - init: function (server) { - // Register license checker - registerLicenseChecker( - server, - PLUGIN.ID, - PLUGIN.getI18nName(i18n), - PLUGIN.MINIMUM_LICENSE_REQUIRED - ); - - registerFieldsRoutes(server); - registerHistoryRoutes(server); - registerIndicesRoutes(server); - registerLicenseRoutes(server); - registerSettingsRoutes(server); - registerWatchesRoutes(server); - registerWatchRoutes(server); - }, -}; diff --git a/x-pack/legacy/plugins/watcher/plugin_definition.ts b/x-pack/legacy/plugins/watcher/plugin_definition.ts new file mode 100644 index 0000000000000..2da05253fdb32 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/plugin_definition.ts @@ -0,0 +1,32 @@ +/* + * 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 { resolve } from 'path'; +import { plugin } from './server/np_ready'; +import { PLUGIN } from './common/constants'; + +export const pluginDefinition = { + id: PLUGIN.ID, + configPrefix: 'xpack.watcher', + publicDir: resolve(__dirname, 'public'), + require: ['kibana', 'elasticsearch', 'xpack_main'], + uiExports: { + styleSheetPaths: resolve(__dirname, 'public/np_ready/application/index.scss'), + managementSections: ['plugins/watcher/legacy'], + home: ['plugins/watcher/register_feature'], + }, + init(server: any) { + plugin({} as any).setup(server.newPlatform.setup.core, { + __LEGACY: { + route: server.route.bind(server), + plugins: { + watcher: server.plugins[PLUGIN.ID], + xpack_main: server.plugins.xpack_main, + }, + }, + }); + }, +}; diff --git a/x-pack/legacy/plugins/watcher/public/app.html b/x-pack/legacy/plugins/watcher/public/app.html deleted file mode 100644 index 8c7c3eb946aef..0000000000000 --- a/x-pack/legacy/plugins/watcher/public/app.html +++ /dev/null @@ -1,3 +0,0 @@ - -
-
\ No newline at end of file diff --git a/x-pack/legacy/plugins/watcher/public/legacy.ts b/x-pack/legacy/plugins/watcher/public/legacy.ts new file mode 100644 index 0000000000000..d7b85ccfeb7b4 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/public/legacy.ts @@ -0,0 +1,146 @@ +/* + * 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 { CoreSetup, App, AppUnmount } from 'src/core/public'; +import { i18n } from '@kbn/i18n'; + +/* Legacy UI imports */ +import { npSetup, npStart } from 'ui/new_platform'; +import routes from 'ui/routes'; +import { management, MANAGEMENT_BREADCRUMB } from 'ui/management'; +import { TimeBuckets } from 'ui/time_buckets'; +// @ts-ignore +import { xpackInfo } from 'plugins/xpack_main/services/xpack_info'; +/* Legacy UI imports */ + +import { plugin } from './np_ready'; +import { PLUGIN } from '../common/constants'; +import { LICENSE_STATUS_INVALID, LICENSE_STATUS_UNAVAILABLE } from '../../../common/constants'; +import { manageAngularLifecycle } from './manage_angular_lifecycle'; + +const template = ` +
+
`; + +let elem: HTMLElement; +let mountApp: () => AppUnmount | Promise; +let unmountApp: AppUnmount | Promise; +routes.when('/management/elasticsearch/watcher/:param1?/:param2?/:param3?/:param4?', { + template, + controller: class WatcherController { + constructor($injector: any, $scope: any) { + const $route = $injector.get('$route'); + const licenseStatus = xpackInfo.get(`features.${PLUGIN.ID}`); + const shimCore: CoreSetup = { + ...npSetup.core, + application: { + ...npSetup.core.application, + register(app: App): void { + mountApp = () => + app.mount(npStart as any, { + element: elem, + appBasePath: '/management/elasticsearch/watcher/', + }); + }, + }, + }; + + // clean up previously rendered React app if one exists + // this happens because of React Router redirects + if (elem) { + ((unmountApp as unknown) as AppUnmount)(); + } + + $scope.$$postDigest(() => { + elem = document.getElementById('watchReactRoot')!; + const instance = plugin(); + instance.setup(shimCore, { + ...(npSetup.plugins as typeof npSetup.plugins & { eui_utils: any }), + __LEGACY: { + MANAGEMENT_BREADCRUMB, + TimeBuckets, + licenseStatus, + }, + }); + + instance.start(npStart.core, npStart.plugins); + + (mountApp() as Promise).then(fn => (unmountApp = fn)); + + manageAngularLifecycle($scope, $route, elem); + }); + } + } as any, + // @ts-ignore + controllerAs: 'watchRoute', +}); + +routes.defaults(/\/management/, { + resolve: { + watcherManagementSection: () => { + const watchesSection = management.getSection('elasticsearch/watcher'); + const licenseStatus = xpackInfo.get(`features.${PLUGIN.ID}`); + const { status } = licenseStatus; + + if (status === LICENSE_STATUS_INVALID || status === LICENSE_STATUS_UNAVAILABLE) { + return watchesSection.hide(); + } + + watchesSection.show(); + }, + }, +}); + +management.getSection('elasticsearch').register('watcher', { + display: i18n.translate('xpack.watcher.sections.watchList.managementSection.watcherDisplayName', { + defaultMessage: 'Watcher', + }), + order: 6, + url: '#/management/elasticsearch/watcher/', +} as any); + +management.getSection('elasticsearch/watcher').register('watches', { + display: i18n.translate('xpack.watcher.sections.watchList.managementSection.watchesDisplayName', { + defaultMessage: 'Watches', + }), + order: 1, +} as any); + +management.getSection('elasticsearch/watcher').register('watch', { + visible: false, +} as any); + +management.getSection('elasticsearch/watcher/watch').register('status', { + display: i18n.translate('xpack.watcher.sections.watchList.managementSection.statusDisplayName', { + defaultMessage: 'Status', + }), + order: 1, + visible: false, +} as any); + +management.getSection('elasticsearch/watcher/watch').register('edit', { + display: i18n.translate('xpack.watcher.sections.watchList.managementSection.editDisplayName', { + defaultMessage: 'Edit', + }), + order: 2, + visible: false, +} as any); + +management.getSection('elasticsearch/watcher/watch').register('new', { + display: i18n.translate( + 'xpack.watcher.sections.watchList.managementSection.newWatchDisplayName', + { + defaultMessage: 'New Watch', + } + ), + order: 1, + visible: false, +} as any); + +management.getSection('elasticsearch/watcher/watch').register('history-item', { + order: 1, + visible: false, +} as any); diff --git a/x-pack/legacy/plugins/watcher/public/lib/documentation_links/documentation_links.ts b/x-pack/legacy/plugins/watcher/public/lib/documentation_links/documentation_links.ts deleted file mode 100644 index 88f23465d33e8..0000000000000 --- a/x-pack/legacy/plugins/watcher/public/lib/documentation_links/documentation_links.ts +++ /dev/null @@ -1,24 +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 { ELASTIC_WEBSITE_URL, DOC_LINK_VERSION } from 'ui/documentation_links'; -import { ACTION_TYPES } from '../../../common/constants'; - -const elasticDocLinkBase = `${ELASTIC_WEBSITE_URL}guide/en/`; - -const esBase = `${elasticDocLinkBase}elasticsearch/reference/${DOC_LINK_VERSION}`; -const esStackBase = `${elasticDocLinkBase}elastic-stack-overview/${DOC_LINK_VERSION}`; -const kibanaBase = `${elasticDocLinkBase}kibana/${DOC_LINK_VERSION}`; - -export const putWatchApiUrl = `${esBase}/watcher-api-put-watch.html`; -export const executeWatchApiUrl = `${esBase}/watcher-api-execute-watch.html#watcher-api-execute-watch-action-mode`; -export const watcherGettingStartedUrl = `${kibanaBase}/watcher-ui.html`; - -export const watchActionsConfigurationMap = { - [ACTION_TYPES.SLACK]: `${esStackBase}/actions-slack.html#configuring-slack`, - [ACTION_TYPES.PAGERDUTY]: `${esStackBase}/actions-pagerduty.html#configuring-pagerduty`, - [ACTION_TYPES.JIRA]: `${esStackBase}/actions-jira.html#configuring-jira`, -}; diff --git a/x-pack/legacy/plugins/watcher/public/lib/manage_angular_lifecycle.js b/x-pack/legacy/plugins/watcher/public/manage_angular_lifecycle.ts similarity index 75% rename from x-pack/legacy/plugins/watcher/public/lib/manage_angular_lifecycle.js rename to x-pack/legacy/plugins/watcher/public/manage_angular_lifecycle.ts index 3813e632a0a73..efd40eaf83daa 100644 --- a/x-pack/legacy/plugins/watcher/public/lib/manage_angular_lifecycle.js +++ b/x-pack/legacy/plugins/watcher/public/manage_angular_lifecycle.ts @@ -6,7 +6,7 @@ import { unmountComponentAtNode } from 'react-dom'; -export const manageAngularLifecycle = ($scope, $route, elem) => { +export const manageAngularLifecycle = ($scope: any, $route: any, elem: HTMLElement) => { const lastRoute = $route.current; const deregister = $scope.$on('$locationChangeSuccess', () => { @@ -17,7 +17,12 @@ export const manageAngularLifecycle = ($scope, $route, elem) => { }); $scope.$on('$destroy', () => { - deregister && deregister(); - elem && unmountComponentAtNode(elem); + if (deregister) { + deregister(); + } + + if (elem) { + unmountComponentAtNode(elem); + } }); }; diff --git a/x-pack/legacy/plugins/watcher/public/models/index.d.ts b/x-pack/legacy/plugins/watcher/public/models/index.d.ts deleted file mode 100644 index d96d8d192e166..0000000000000 --- a/x-pack/legacy/plugins/watcher/public/models/index.d.ts +++ /dev/null @@ -1,42 +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. - */ -declare module 'plugins/watcher/models/visualize_options' { - export const VisualizeOptions: any; -} - -declare module 'plugins/watcher/models/watch' { - export const Watch: any; -} - -declare module 'plugins/watcher/models/watch/threshold_watch' { - export const ThresholdWatch: any; -} - -declare module 'plugins/watcher/models/watch/json_watch' { - export const JsonWatch: any; -} - -declare module 'plugins/watcher/models/execute_details/execute_details' { - export const ExecuteDetails: any; -} - -declare module 'plugins/watcher/models/watch_history_item' { - export const WatchHistoryItem: any; -} - -declare module 'plugins/watcher/models/watch_status' { - export const WatchStatus: any; -} - -declare module 'plugins/watcher/models/settings' { - export const Settings: any; -} -declare module 'plugins/watcher/models/action' { - export const Action: any; -} -declare module 'ui/time_buckets' { - export const TimeBuckets: any; -} diff --git a/x-pack/legacy/plugins/watcher/public/app.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/app.tsx similarity index 60% rename from x-pack/legacy/plugins/watcher/public/app.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/app.tsx index b206348547966..36fa1cce9d6dd 100644 --- a/x-pack/legacy/plugins/watcher/public/app.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/app.tsx @@ -4,54 +4,61 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { Component } from 'react'; -import PropTypes from 'prop-types'; -import { HashRouter, Switch, Route, Redirect } from 'react-router-dom'; +import React from 'react'; +import { + ChromeStart, + DocLinksStart, + HttpSetup, + ToastsSetup, + IUiSettingsClient, +} from 'src/core/public'; + +import { EuiCallOut, EuiLink } from '@elastic/eui'; +import { + HashRouter, + Switch, + Route, + Redirect, + withRouter, + RouteComponentProps, +} from 'react-router-dom'; import { FormattedMessage } from '@kbn/i18n/react'; import { WatchStatus } from './sections/watch_status/components/watch_status'; import { WatchEdit } from './sections/watch_edit/components/watch_edit'; import { WatchList } from './sections/watch_list/components/watch_list'; import { registerRouter } from './lib/navigation'; import { BASE_PATH } from './constants'; -import { LICENSE_STATUS_VALID } from '../../../common/constants'; -import { EuiCallOut, EuiLink } from '@elastic/eui'; +import { LICENSE_STATUS_VALID } from '../../../../../common/constants'; +import { AppContextProvider } from './app_context'; +import { LegacyDependencies } from '../types'; -class ShareRouter extends Component { - static contextTypes = { - router: PropTypes.shape({ - history: PropTypes.shape({ - push: PropTypes.func.isRequired, - createHref: PropTypes.func.isRequired - }).isRequired - }).isRequired - } - constructor(...args) { - super(...args); - this.registerRouter(); - } +const ShareRouter = withRouter(({ children, history }: RouteComponentProps & { children: any }) => { + registerRouter({ history }); + return children; +}); - registerRouter() { - // Share the router with the app without requiring React or context. - const { router } = this.context; - registerRouter(router); - } - - render() { - return this.props.children; - } +export interface AppDeps { + chrome: ChromeStart; + docLinks: DocLinksStart; + toasts: ToastsSetup; + http: HttpSetup; + uiSettings: IUiSettingsClient; + legacy: LegacyDependencies; + euiUtils: any; } -export const App = ({ licenseStatus }) => { - const { status, message } = licenseStatus; + +export const App = (deps: AppDeps) => { + const { status, message } = deps.legacy.licenseStatus; if (status !== LICENSE_STATUS_VALID) { return ( - )} + } color="warning" iconType="help" > @@ -69,7 +76,9 @@ export const App = ({ licenseStatus }) => { return ( - + + + ); @@ -81,7 +90,11 @@ export const AppWithoutRouter = () => ( - + ); diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/app_context.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/app_context.tsx new file mode 100644 index 0000000000000..5696ab3cb91ba --- /dev/null +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/app_context.tsx @@ -0,0 +1,65 @@ +/* + * 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 React, { createContext, useContext } from 'react'; +import { DocLinksStart } from 'src/core/public'; +import { ACTION_TYPES } from '../../../common/constants'; +import { AppDeps } from './app'; + +interface ContextValue extends Omit { + links: ReturnType; +} + +const AppContext = createContext(null as any); + +const generateDocLinks = ({ ELASTIC_WEBSITE_URL, DOC_LINK_VERSION }: DocLinksStart) => { + const elasticDocLinkBase = `${ELASTIC_WEBSITE_URL}guide/en/`; + const esBase = `${elasticDocLinkBase}elasticsearch/reference/${DOC_LINK_VERSION}`; + const kibanaBase = `${elasticDocLinkBase}kibana/${DOC_LINK_VERSION}`; + const putWatchApiUrl = `${esBase}/watcher-api-put-watch.html`; + const executeWatchApiUrl = `${esBase}/watcher-api-execute-watch.html#watcher-api-execute-watch-action-mode`; + const watcherGettingStartedUrl = `${kibanaBase}/watcher-ui.html`; + const watchActionsConfigurationMap = { + [ACTION_TYPES.SLACK]: `${esBase}/actions-slack.html#configuring-slack`, + [ACTION_TYPES.PAGERDUTY]: `${esBase}/actions-pagerduty.html#configuring-pagerduty`, + [ACTION_TYPES.JIRA]: `${esBase}/actions-jira.html#configuring-jira`, + }; + + return { + putWatchApiUrl, + executeWatchApiUrl, + watcherGettingStartedUrl, + watchActionsConfigurationMap, + }; +}; + +export const AppContextProvider = ({ + children, + value, +}: { + value: AppDeps; + children: React.ReactNode; +}) => { + const { docLinks, ...rest } = value; + return ( + + {children} + + ); +}; + +export const useAppContext = () => { + const ctx = useContext(AppContext); + if (!ctx) { + throw new Error('"useAppContext" can only be called inside of AppContext.Provider!'); + } + return ctx; +}; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/boot.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/boot.tsx new file mode 100644 index 0000000000000..3f2a10f004649 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/boot.tsx @@ -0,0 +1,35 @@ +/* + * 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 React from 'react'; +import { render, unmountComponentAtNode } from 'react-dom'; +import { SavedObjectsClientContract } from 'src/core/public'; + +import { App, AppDeps } from './app'; +import { setHttpClient, setSavedObjectsClient } from './lib/api'; +import { LegacyDependencies } from '../types'; + +interface BootDeps extends AppDeps { + element: HTMLElement; + savedObjects: SavedObjectsClientContract; + I18nContext: any; + legacy: LegacyDependencies; +} + +export const boot = (bootDeps: BootDeps) => { + const { I18nContext, element, legacy, savedObjects, ...appDeps } = bootDeps; + + setHttpClient(appDeps.http); + setSavedObjectsClient(savedObjects); + + render( + + + , + element + ); + return () => unmountComponentAtNode(element); +}; diff --git a/x-pack/legacy/plugins/watcher/public/components/confirm_watches_modal.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/confirm_watches_modal.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/components/confirm_watches_modal.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/confirm_watches_modal.tsx diff --git a/x-pack/legacy/plugins/watcher/public/components/delete_watches_modal.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/delete_watches_modal.tsx similarity index 95% rename from x-pack/legacy/plugins/watcher/public/components/delete_watches_modal.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/delete_watches_modal.tsx index 6d75495cbfc20..363185f3457d8 100644 --- a/x-pack/legacy/plugins/watcher/public/components/delete_watches_modal.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/delete_watches_modal.tsx @@ -6,8 +6,8 @@ import { EuiConfirmModal, EuiOverlayMask } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { toastNotifications } from 'ui/notify'; import { deleteWatches } from '../lib/api'; +import { useAppContext } from '../app_context'; export const DeleteWatchesModal = ({ watchesToDelete, @@ -16,6 +16,7 @@ export const DeleteWatchesModal = ({ watchesToDelete: string[]; callback: (deleted?: string[]) => void; }) => { + const { toasts } = useAppContext(); const numWatchesToDelete = watchesToDelete.length; if (!numWatchesToDelete) { return null; @@ -54,7 +55,7 @@ export const DeleteWatchesModal = ({ const numErrors = errors.length; callback(successes); if (numSuccesses > 0) { - toastNotifications.addSuccess( + toasts.addSuccess( i18n.translate( 'xpack.watcher.sections.watchList.deleteSelectedWatchesSuccessNotification.descriptionText', { @@ -67,7 +68,7 @@ export const DeleteWatchesModal = ({ } if (numErrors > 0) { - toastNotifications.addDanger( + toasts.addDanger( i18n.translate( 'xpack.watcher.sections.watchList.deleteSelectedWatchesErrorNotification.descriptionText', { diff --git a/x-pack/legacy/plugins/watcher/public/components/form_errors.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/form_errors.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/components/form_errors.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/form_errors.tsx diff --git a/x-pack/legacy/plugins/watcher/public/components/index.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/components/index.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/components/page_error/index.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/components/page_error/index.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/components/page_error/page_error.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/components/page_error/page_error.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error.tsx diff --git a/x-pack/legacy/plugins/watcher/public/components/page_error/page_error_forbidden.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error_forbidden.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/components/page_error/page_error_forbidden.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error_forbidden.tsx diff --git a/x-pack/legacy/plugins/watcher/public/components/page_error/page_error_not_exist.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error_not_exist.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/components/page_error/page_error_not_exist.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error_not_exist.tsx diff --git a/x-pack/legacy/plugins/watcher/public/components/section_error.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_error.tsx similarity index 80% rename from x-pack/legacy/plugins/watcher/public/components/section_error.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_error.tsx index 8951b95b75078..1c77cf2b49ae2 100644 --- a/x-pack/legacy/plugins/watcher/public/components/section_error.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_error.tsx @@ -8,6 +8,18 @@ import { EuiCallOut, EuiSpacer } from '@elastic/eui'; import React, { Fragment } from 'react'; export interface Error { + error: string; + + /** + * wrapEsError() on the server adds a "cause" array + */ + cause?: string[]; + + message?: string; + + /** + * @deprecated + */ data: { error: string; cause?: string[]; @@ -21,11 +33,9 @@ interface Props { } export const SectionError: React.FunctionComponent = ({ title, error, ...rest }) => { - const { - error: errorString, - cause, // wrapEsError() on the server adds a "cause" array - message, - } = error.data; + const data = error.data || error; + + const { error: errorString, cause, message } = data; return ( diff --git a/x-pack/legacy/plugins/watcher/public/components/section_loading.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_loading.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/components/section_loading.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_loading.tsx diff --git a/x-pack/legacy/plugins/watcher/public/components/watch_status.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/watch_status.tsx similarity index 95% rename from x-pack/legacy/plugins/watcher/public/components/watch_status.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/components/watch_status.tsx index 39e6a5247b4a6..8afd174f8561e 100644 --- a/x-pack/legacy/plugins/watcher/public/components/watch_status.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/components/watch_status.tsx @@ -6,7 +6,7 @@ import React from 'react'; import { EuiIcon, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; -import { ACTION_STATES, WATCH_STATES } from '../../common/constants'; +import { ACTION_STATES, WATCH_STATES } from '../../../../common/constants'; function StatusIcon({ status }: { status: string }) { switch (status) { diff --git a/x-pack/legacy/plugins/watcher/public/constants/base_path.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/constants/base_path.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/constants/base_path.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/constants/base_path.ts diff --git a/x-pack/legacy/plugins/watcher/public/constants/index.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/constants/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/constants/index.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/constants/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/index.scss b/x-pack/legacy/plugins/watcher/public/np_ready/application/index.scss similarity index 100% rename from x-pack/legacy/plugins/watcher/public/index.scss rename to x-pack/legacy/plugins/watcher/public/np_ready/application/index.scss diff --git a/x-pack/legacy/plugins/watcher/public/lib/api.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/api.ts similarity index 61% rename from x-pack/legacy/plugins/watcher/public/lib/api.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/lib/api.ts index d5c430f9244c4..c08545904e351 100644 --- a/x-pack/legacy/plugins/watcher/public/lib/api.ts +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/api.ts @@ -3,20 +3,20 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { Settings } from 'plugins/watcher/models/settings'; -import { Watch } from 'plugins/watcher/models/watch'; -import { WatchHistoryItem } from 'plugins/watcher/models/watch_history_item'; -import { WatchStatus } from 'plugins/watcher/models/watch_status'; - -import { __await } from 'tslib'; -import chrome from 'ui/chrome'; -import { ROUTES } from '../../common/constants'; -import { BaseWatch, ExecutedWatchDetails } from '../../common/types/watch_types'; +import { HttpSetup, SavedObjectsClientContract } from 'src/core/public'; +import { Settings } from 'plugins/watcher/np_ready/application/models/settings'; +import { Watch } from 'plugins/watcher/np_ready/application/models/watch'; +import { WatchHistoryItem } from 'plugins/watcher/np_ready/application/models/watch_history_item'; +import { WatchStatus } from 'plugins/watcher/np_ready/application/models/watch_status'; + +import { BaseWatch, ExecutedWatchDetails } from '../../../../common/types/watch_types'; import { useRequest, sendRequest } from './use_request'; -let httpClient: ng.IHttpService; +import { ROUTES } from '../../../../common/constants'; + +let httpClient: HttpSetup; -export const setHttpClient = (anHttpClient: ng.IHttpService) => { +export const setHttpClient = (anHttpClient: HttpSetup) => { httpClient = anHttpClient; }; @@ -24,19 +24,17 @@ export const getHttpClient = () => { return httpClient; }; -let savedObjectsClient: any; +let savedObjectsClient: SavedObjectsClientContract; -export const setSavedObjectsClient = (aSavedObjectsClient: any) => { +export const setSavedObjectsClient = (aSavedObjectsClient: SavedObjectsClientContract) => { savedObjectsClient = aSavedObjectsClient; }; -export const getSavedObjectsClient = () => { - return savedObjectsClient; -}; +export const getSavedObjectsClient = () => savedObjectsClient; -const basePath = chrome.addBasePath(ROUTES.API_ROOT); +const basePath = ROUTES.API_ROOT; -export const loadWatches = (pollIntervalMs: number) => { +export const useLoadWatches = (pollIntervalMs: number) => { return useRequest({ path: `${basePath}/watches`, method: 'get', @@ -47,7 +45,7 @@ export const loadWatches = (pollIntervalMs: number) => { }); }; -export const loadWatchDetail = (id: string) => { +export const useLoadWatchDetail = (id: string) => { return useRequest({ path: `${basePath}/watch/${id}`, method: 'get', @@ -55,15 +53,10 @@ export const loadWatchDetail = (id: string) => { }); }; -export const loadWatchHistory = (id: string, startTime: string) => { - let path = `${basePath}/watch/${id}/history`; - - if (startTime) { - path += `?startTime=${startTime}`; - } - +export const useLoadWatchHistory = (id: string, startTime: string) => { return useRequest({ - path, + query: startTime ? { startTime } : undefined, + path: `${basePath}/watch/${id}/history`, method: 'get', deserializer: ({ watchHistoryItems = [] }: { watchHistoryItems: any }) => { return watchHistoryItems.map((historyItem: any) => @@ -73,7 +66,7 @@ export const loadWatchHistory = (id: string, startTime: string) => { }); }; -export const loadWatchHistoryDetail = (id: string | undefined) => { +export const useLoadWatchHistoryDetail = (id: string | undefined) => { return useRequest({ path: !id ? '' : `${basePath}/history/${id}`, method: 'get', @@ -83,12 +76,10 @@ export const loadWatchHistoryDetail = (id: string | undefined) => { }; export const deleteWatches = async (watchIds: string[]) => { - const body = { + const body = JSON.stringify({ watchIds, - }; - const { - data: { results }, - } = await getHttpClient().post(`${basePath}/watches/delete`, body); + }); + const { results } = await getHttpClient().post(`${basePath}/watches/delete`, { body }); return results; }; @@ -107,8 +98,8 @@ export const activateWatch = async (id: string) => { }; export const loadWatch = async (id: string) => { - const { data: watch } = await getHttpClient().get(`${basePath}/watch/${id}`); - return Watch.fromUpstreamJson(watch.watch); + const { watch } = await getHttpClient().get(`${basePath}/watch/${id}`); + return Watch.fromUpstreamJson(watch); }; export const getMatchingIndices = async (pattern: string) => { @@ -118,32 +109,32 @@ export const getMatchingIndices = async (pattern: string) => { if (!pattern.endsWith('*')) { pattern = `${pattern}*`; } - const { - data: { indices }, - } = await getHttpClient().post(`${basePath}/indices`, { pattern }); + const body = JSON.stringify({ pattern }); + const { indices } = await getHttpClient().post(`${basePath}/indices`, { body }); return indices; }; export const fetchFields = async (indexes: string[]) => { - const { - data: { fields }, - } = await getHttpClient().post(`${basePath}/fields`, { indexes }); + const { fields } = await getHttpClient().post(`${basePath}/fields`, { + body: JSON.stringify({ indexes }), + }); return fields; }; export const createWatch = async (watch: BaseWatch) => { - const { data } = await getHttpClient().put(`${basePath}/watch/${watch.id}`, watch.upstreamJson); - return data; + return await getHttpClient().put(`${basePath}/watch/${watch.id}`, { + body: JSON.stringify(watch.upstreamJson), + }); }; export const executeWatch = async (executeWatchDetails: ExecutedWatchDetails, watch: BaseWatch) => { return sendRequest({ path: `${basePath}/watch/execute`, method: 'put', - body: { + body: JSON.stringify({ executeDetails: executeWatchDetails.upstreamJson, watch: watch.upstreamJson, - }, + }), }); }; @@ -156,19 +147,19 @@ export const loadIndexPatterns = async () => { return savedObjects; }; -export const getWatchVisualizationData = (watchModel: BaseWatch, visualizeOptions: any) => { +export const useGetWatchVisualizationData = (watchModel: BaseWatch, visualizeOptions: any) => { return useRequest({ path: `${basePath}/watch/visualize`, method: 'post', - body: { + body: JSON.stringify({ watch: watchModel.upstreamJson, options: visualizeOptions.upstreamJson, - }, + }), deserializer: ({ visualizeData }: { visualizeData: any }) => visualizeData, }); }; -export const loadSettings = () => { +export const useLoadSettings = () => { return useRequest({ path: `${basePath}/settings`, method: 'get', @@ -183,11 +174,8 @@ export const loadSettings = () => { }; export const ackWatchAction = async (watchId: string, actionId: string) => { - const { - data: { watchStatus }, - } = await getHttpClient().put( - `${basePath}/watch/${watchId}/action/${actionId}/acknowledge`, - null + const { watchStatus } = await getHttpClient().put( + `${basePath}/watch/${watchId}/action/${actionId}/acknowledge` ); return WatchStatus.fromUpstreamJson(watchStatus); }; diff --git a/x-pack/legacy/plugins/watcher/public/lib/breadcrumbs.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/breadcrumbs.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/lib/breadcrumbs.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/lib/breadcrumbs.ts diff --git a/x-pack/legacy/plugins/watcher/public/lib/format_date.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/format_date.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/lib/format_date.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/lib/format_date.ts diff --git a/x-pack/legacy/plugins/watcher/public/lib/get_search_value.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_search_value.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/lib/get_search_value.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_search_value.ts diff --git a/x-pack/legacy/plugins/watcher/public/lib/get_time_unit_label.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_time_unit_label.ts similarity index 95% rename from x-pack/legacy/plugins/watcher/public/lib/get_time_unit_label.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_time_unit_label.ts index 35bd19e7007c6..ce3b96ac17def 100644 --- a/x-pack/legacy/plugins/watcher/public/lib/get_time_unit_label.ts +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_time_unit_label.ts @@ -5,7 +5,7 @@ */ import { i18n } from '@kbn/i18n'; -import { TIME_UNITS } from '../../common/constants'; +import { TIME_UNITS } from '../../../../common/constants'; export function getTimeUnitLabel(timeUnit = TIME_UNITS.SECOND, timeValue = '0') { switch (timeUnit) { diff --git a/x-pack/legacy/plugins/watcher/public/lib/navigation.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/navigation.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/lib/navigation.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/lib/navigation.ts diff --git a/x-pack/legacy/plugins/watcher/public/lib/use_request.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/use_request.ts similarity index 99% rename from x-pack/legacy/plugins/watcher/public/lib/use_request.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/lib/use_request.ts index 4788b655d9e88..572403b14b9df 100644 --- a/x-pack/legacy/plugins/watcher/public/lib/use_request.ts +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/use_request.ts @@ -11,6 +11,7 @@ import { sendRequest as _sendRequest, useRequest as _useRequest, } from '../shared_imports'; + import { getHttpClient } from './api'; export const sendRequest = (config: SendRequestConfig): Promise => { diff --git a/x-pack/legacy/plugins/watcher/public/models/action/action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/action.js similarity index 95% rename from x-pack/legacy/plugins/watcher/public/models/action/action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/action.js index 2f1850c3a434c..4e6ec21703b96 100644 --- a/x-pack/legacy/plugins/watcher/public/models/action/action.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/action.js @@ -5,7 +5,7 @@ */ import { get, set } from 'lodash'; -import { ACTION_TYPES } from '../../../common/constants'; +import { ACTION_TYPES } from '../../../../../common/constants'; import { EmailAction } from './email_action'; import { LoggingAction } from './logging_action'; import { SlackAction } from './slack_action'; diff --git a/x-pack/legacy/plugins/watcher/public/models/action/base_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/base_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/base_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/base_action.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action/email_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/email_action.js similarity index 80% rename from x-pack/legacy/plugins/watcher/public/models/action/email_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/email_action.js index 3e267c53af21f..b85258e3da7d3 100644 --- a/x-pack/legacy/plugins/watcher/public/models/action/email_action.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/email_action.js @@ -7,23 +7,20 @@ import { get, isArray } from 'lodash'; import { BaseAction } from './base_action'; import { i18n } from '@kbn/i18n'; -import chrome from 'ui/chrome'; export class EmailAction extends BaseAction { constructor(props = {}) { super(props); - const uiSettings = chrome.getUiSettingsClient(); - const defaultToEmail = uiSettings.get('xPack:defaultAdminEmail'); - const toArray = get(props, 'to', defaultToEmail); + const toArray = get(props, 'to'); - this.to = isArray(toArray) ? toArray : toArray && [ toArray ]; + this.to = isArray(toArray) ? toArray : toArray && [toArray]; const defaultSubject = i18n.translate('xpack.watcher.models.emailAction.defaultSubjectText', { defaultMessage: 'Watch [{context}] has exceeded the threshold', values: { context: '{{ctx.metadata.name}}', - } + }, }); this.subject = get(props, 'subject', props.ignoreDefaults ? null : defaultSubject); @@ -38,9 +35,12 @@ export class EmailAction extends BaseAction { if (!this.to || !this.to.length) { errors.to.push( - i18n.translate('xpack.watcher.watchActions.email.emailRecipientIsRequiredValidationMessage', { - defaultMessage: '"To" email address is required.', - }) + i18n.translate( + 'xpack.watcher.watchActions.email.emailRecipientIsRequiredValidationMessage', + { + defaultMessage: '"To" email address is required.', + } + ) ); } @@ -60,7 +60,7 @@ export class EmailAction extends BaseAction { body: { text: this.body, }, - } + }, }); return result; @@ -71,8 +71,8 @@ export class EmailAction extends BaseAction { return i18n.translate('xpack.watcher.models.emailAction.simulateMessage', { defaultMessage: 'Sample email sent to {toList}', values: { - toList - } + toList, + }, }); } @@ -81,8 +81,8 @@ export class EmailAction extends BaseAction { return i18n.translate('xpack.watcher.models.emailAction.simulateFailMessage', { defaultMessage: 'Failed to send email to {toList}.', values: { - toList - } + toList, + }, }); } @@ -98,6 +98,6 @@ export class EmailAction extends BaseAction { defaultMessage: 'Send an email from your server.', }); static simulatePrompt = i18n.translate('xpack.watcher.models.emailAction.simulateButtonLabel', { - defaultMessage: 'Send test email' + defaultMessage: 'Send test email', }); } diff --git a/x-pack/legacy/plugins/watcher/public/models/action/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action/index_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/index_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/index_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/index_action.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action/jira_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/jira_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/jira_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/jira_action.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action/logging_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/logging_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/logging_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/logging_action.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action/pagerduty_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/pagerduty_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/pagerduty_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/pagerduty_action.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action/slack_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/slack_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/slack_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/slack_action.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action/unknown_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/unknown_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/unknown_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/unknown_action.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action/webhook_action.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/webhook_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action/webhook_action.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/webhook_action.js diff --git a/x-pack/legacy/plugins/watcher/public/models/action_status/action_status.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/action_status.js similarity index 95% rename from x-pack/legacy/plugins/watcher/public/models/action_status/action_status.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/action_status.js index fa9e056554ab0..b177eb5bb2291 100644 --- a/x-pack/legacy/plugins/watcher/public/models/action_status/action_status.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/action_status.js @@ -5,7 +5,7 @@ */ import { get } from 'lodash'; -import { getMoment } from '../../../common/lib/get_moment'; +import { getMoment } from '../../../../../common/lib/get_moment'; export class ActionStatus { constructor(props = {}) { diff --git a/x-pack/legacy/plugins/watcher/public/models/action_status/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/action_status/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/execute_details/execute_details.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/execute_details/execute_details.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/execute_details/execute_details.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/execute_details/execute_details.js diff --git a/x-pack/legacy/plugins/watcher/public/models/execute_details/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/execute_details/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/execute_details/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/execute_details/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/index.d.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/index.d.ts new file mode 100644 index 0000000000000..a8ddb6ca2b76d --- /dev/null +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/index.d.ts @@ -0,0 +1,39 @@ +/* + * 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. + */ +declare module 'plugins/watcher/np_ready/application/models/visualize_options' { + export const VisualizeOptions: any; +} + +declare module 'plugins/watcher/np_ready/application/models/watch' { + export const Watch: any; +} + +declare module 'plugins/watcher/np_ready/application/models/watch/threshold_watch' { + export const ThresholdWatch: any; +} + +declare module 'plugins/watcher/np_ready/application/models/watch/json_watch' { + export const JsonWatch: any; +} + +declare module 'plugins/watcher/np_ready/application/models/execute_details/execute_details' { + export const ExecuteDetails: any; +} + +declare module 'plugins/watcher/np_ready/application/models/watch_history_item' { + export const WatchHistoryItem: any; +} + +declare module 'plugins/watcher/np_ready/application/models/watch_status' { + export const WatchStatus: any; +} + +declare module 'plugins/watcher/np_ready/application/models/settings' { + export const Settings: any; +} +declare module 'plugins/watcher/np_ready/application/models/action' { + export const Action: any; +} diff --git a/x-pack/legacy/plugins/watcher/public/models/settings/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/settings/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/settings/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/settings/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/settings/settings.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/settings/settings.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/settings/settings.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/settings/settings.js diff --git a/x-pack/legacy/plugins/watcher/public/models/visualize_options/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/visualize_options/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/visualize_options/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/visualize_options/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/visualize_options/visualize_options.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/visualize_options/visualize_options.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/visualize_options/visualize_options.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/visualize_options/visualize_options.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/agg_types.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/agg_types.ts similarity index 94% rename from x-pack/legacy/plugins/watcher/public/models/watch/agg_types.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/agg_types.ts index 65ab537889ea4..cefaaa3b1abd3 100644 --- a/x-pack/legacy/plugins/watcher/public/models/watch/agg_types.ts +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/agg_types.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { AGG_TYPES } from '../../../common/constants'; +import { AGG_TYPES } from '../../../../../common/constants'; export interface AggType { text: string; diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/base_watch.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/base_watch.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch/base_watch.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/base_watch.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/comparators.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/comparators.ts similarity index 96% rename from x-pack/legacy/plugins/watcher/public/models/watch/comparators.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/comparators.ts index b636cdaf14c18..edc3a03c25227 100644 --- a/x-pack/legacy/plugins/watcher/public/models/watch/comparators.ts +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/comparators.ts @@ -6,7 +6,7 @@ import { i18n } from '@kbn/i18n'; -import { COMPARATORS } from '../../../common/constants'; +import { COMPARATORS } from '../../../../../common/constants'; export interface Comparator { text: string; diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/default_watch.json b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/default_watch.json similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch/default_watch.json rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/default_watch.json diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/group_by_types.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/group_by_types.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch/group_by_types.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/group_by_types.ts diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/json_watch.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/json_watch.js similarity index 98% rename from x-pack/legacy/plugins/watcher/public/models/watch/json_watch.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/json_watch.js index 3dd7af759970e..2e2ee47640cf0 100644 --- a/x-pack/legacy/plugins/watcher/public/models/watch/json_watch.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/json_watch.js @@ -7,7 +7,7 @@ import uuid from 'uuid'; import { get } from 'lodash'; import { BaseWatch } from './base_watch'; -import { ACTION_TYPES, WATCH_TYPES } from '../../../common/constants'; +import { ACTION_TYPES, WATCH_TYPES } from '../../../../../common/constants'; import defaultWatchJson from './default_watch.json'; import { i18n } from '@kbn/i18n'; diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/lib/check_action_id_collision/check_action_id_collision.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/check_action_id_collision/check_action_id_collision.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch/lib/check_action_id_collision/check_action_id_collision.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/check_action_id_collision/check_action_id_collision.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/lib/check_action_id_collision/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/check_action_id_collision/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch/lib/check_action_id_collision/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/check_action_id_collision/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/lib/create_action_id/create_action_id.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/create_action_id/create_action_id.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch/lib/create_action_id/create_action_id.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/create_action_id/create_action_id.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/lib/create_action_id/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/create_action_id/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch/lib/create_action_id/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/create_action_id/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/monitoring_watch.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/monitoring_watch.js similarity index 92% rename from x-pack/legacy/plugins/watcher/public/models/watch/monitoring_watch.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/monitoring_watch.js index a0873934e1759..3269fcbe459d2 100644 --- a/x-pack/legacy/plugins/watcher/public/models/watch/monitoring_watch.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/monitoring_watch.js @@ -5,7 +5,7 @@ */ import { BaseWatch } from './base_watch'; -import { WATCH_TYPES } from '../../../common/constants'; +import { WATCH_TYPES } from '../../../../../common/constants'; /** * {@code MonitoringWatch} system defined watches created by the Monitoring plugin. diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/threshold_watch.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/threshold_watch.js similarity index 99% rename from x-pack/legacy/plugins/watcher/public/models/watch/threshold_watch.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/threshold_watch.js index af995d6594a38..02fa99e7f3e16 100644 --- a/x-pack/legacy/plugins/watcher/public/models/watch/threshold_watch.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/threshold_watch.js @@ -6,7 +6,7 @@ import { BaseWatch } from './base_watch'; import uuid from 'uuid'; -import { WATCH_TYPES, SORT_ORDERS, COMPARATORS } from '../../../common/constants'; +import { WATCH_TYPES, SORT_ORDERS, COMPARATORS } from '../../../../../common/constants'; import { getTimeUnitLabel } from '../../lib/get_time_unit_label'; import { i18n } from '@kbn/i18n'; import { aggTypes } from './agg_types'; diff --git a/x-pack/legacy/plugins/watcher/public/models/watch/watch.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/watch.js similarity index 93% rename from x-pack/legacy/plugins/watcher/public/models/watch/watch.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/watch.js index d58a7799c6516..2723fed920675 100644 --- a/x-pack/legacy/plugins/watcher/public/models/watch/watch.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/watch.js @@ -5,7 +5,7 @@ */ import { get, set } from 'lodash'; -import { WATCH_TYPES } from '../../../common/constants'; +import { WATCH_TYPES } from '../../../../../common/constants'; import { JsonWatch } from './json_watch'; import { ThresholdWatch } from './threshold_watch'; import { MonitoringWatch } from './monitoring_watch'; diff --git a/x-pack/legacy/plugins/watcher/public/models/watch_errors/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_errors/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch_errors/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_errors/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch_errors/watch_errors.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_errors/watch_errors.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch_errors/watch_errors.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_errors/watch_errors.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch_history_item/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch_history_item/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch_history_item/watch_history_item.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/watch_history_item.js similarity index 91% rename from x-pack/legacy/plugins/watcher/public/models/watch_history_item/watch_history_item.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/watch_history_item.js index a5918cec2764b..785f9d19b23dd 100644 --- a/x-pack/legacy/plugins/watcher/public/models/watch_history_item/watch_history_item.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/watch_history_item.js @@ -6,7 +6,7 @@ import 'moment-duration-format'; import { get } from 'lodash'; -import { getMoment } from '../../../common/lib/get_moment'; +import { getMoment } from '../../../../../common/lib/get_moment'; import { WatchStatus } from '../watch_status'; export class WatchHistoryItem { diff --git a/x-pack/legacy/plugins/watcher/public/models/watch_status/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/models/watch_status/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/index.js diff --git a/x-pack/legacy/plugins/watcher/public/models/watch_status/watch_status.js b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/watch_status.js similarity index 94% rename from x-pack/legacy/plugins/watcher/public/models/watch_status/watch_status.js rename to x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/watch_status.js index f213032a93c27..77007ea190386 100644 --- a/x-pack/legacy/plugins/watcher/public/models/watch_status/watch_status.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/watch_status.js @@ -5,7 +5,7 @@ */ import { get } from 'lodash'; -import { getMoment } from '../../../common/lib/get_moment'; +import { getMoment } from '../../../../../common/lib/get_moment'; import { ActionStatus } from '../action_status'; export class WatchStatus { diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/index.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/index.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx similarity index 92% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx index 9c4b16e301b38..010e430c0719a 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx @@ -16,10 +16,10 @@ import { EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { ExecuteDetails } from 'plugins/watcher/models/execute_details/execute_details'; -import { getActionType } from '../../../../../common/lib/get_action_type'; -import { BaseWatch, ExecutedWatchDetails } from '../../../../../common/types/watch_types'; -import { ACTION_MODES, TIME_UNITS } from '../../../../../common/constants'; +import { ExecuteDetails } from 'plugins/watcher/np_ready/application/models/execute_details/execute_details'; +import { getActionType } from '../../../../../../../common/lib/get_action_type'; +import { BaseWatch, ExecutedWatchDetails } from '../../../../../../../common/types/watch_types'; +import { ACTION_MODES, TIME_UNITS } from '../../../../../../../common/constants'; import { JsonWatchEditForm } from './json_watch_edit_form'; import { JsonWatchEditSimulate } from './json_watch_edit_simulate'; import { WatchContext } from '../../watch_context'; diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx index 02a54fc9b9279..376aeb205b855 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx @@ -20,15 +20,20 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { serializeJsonWatch } from '../../../../../common/lib/serialization'; -import { ErrableFormRow, SectionError } from '../../../../components'; -import { putWatchApiUrl } from '../../../../lib/documentation_links'; +import { serializeJsonWatch } from '../../../../../../../common/lib/serialization'; +import { ErrableFormRow, SectionError, Error as ServerError } from '../../../../components'; import { onWatchSave } from '../../watch_edit_actions'; import { WatchContext } from '../../watch_context'; import { goToWatchList } from '../../../../lib/navigation'; import { RequestFlyout } from '../request_flyout'; +import { useAppContext } from '../../../../app_context'; export const JsonWatchEditForm = () => { + const { + links: { putWatchApiUrl }, + toasts, + } = useAppContext(); + const { watch, setWatchProperty } = useContext(WatchContext); const { errors } = watch.validate(); @@ -37,9 +42,7 @@ export const JsonWatchEditForm = () => { const [validationError, setValidationError] = useState(null); const [isRequestVisible, setIsRequestVisible] = useState(false); - const [serverError, setServerError] = useState<{ - data: { nessage: string; error: string }; - } | null>(null); + const [serverError, setServerError] = useState(null); const [isSaving, setIsSaving] = useState(false); @@ -192,7 +195,7 @@ export const JsonWatchEditForm = () => { isDisabled={hasErrors} onClick={async () => { setIsSaving(true); - const savedWatch = await onWatchSave(watch); + const savedWatch = await onWatchSave(watch, toasts); if (savedWatch && savedWatch.error) { const { data } = savedWatch.error; setIsSaving(false); diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx similarity index 96% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx index e57a875aa4356..7c5de3d8e9298 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx @@ -24,19 +24,19 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ExecuteDetails } from 'plugins/watcher/models/execute_details/execute_details'; -import { WatchHistoryItem } from 'plugins/watcher/models/watch_history_item'; -import { ACTION_MODES, TIME_UNITS } from '../../../../../common/constants'; +import { ExecuteDetails } from 'plugins/watcher/np_ready/application/models/execute_details/execute_details'; +import { WatchHistoryItem } from 'plugins/watcher/np_ready/application/models/watch_history_item'; +import { ACTION_MODES, TIME_UNITS } from '../../../../../../../common/constants'; import { ExecutedWatchDetails, ExecutedWatchResults, -} from '../../../../../common/types/watch_types'; +} from '../../../../../../../common/types/watch_types'; import { ErrableFormRow } from '../../../../components/form_errors'; import { executeWatch } from '../../../../lib/api'; -import { executeWatchApiUrl } from '../../../../lib/documentation_links'; import { WatchContext } from '../../watch_context'; import { JsonWatchEditSimulateResults } from './json_watch_edit_simulate_results'; import { getTimeUnitLabel } from '../../../../lib/get_time_unit_label'; +import { useAppContext } from '../../../../app_context'; const actionModeOptions = Object.keys(ACTION_MODES).map(mode => ({ text: ACTION_MODES[mode], @@ -70,6 +70,9 @@ export const JsonWatchEditSimulate = ({ type: string; }>; }) => { + const { + links: { executeWatchApiUrl }, + } = useAppContext(); const { watch } = useContext(WatchContext); // hooks diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx similarity index 99% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx index 1b2b4ab935e8c..4b630f5bc81b4 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx @@ -21,7 +21,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { ExecutedWatchDetails, ExecutedWatchResults, -} from '../../../../../common/types/watch_types'; +} from '../../../../../../../common/types/watch_types'; import { getTypeFromAction } from '../../watch_edit_actions'; import { WatchContext } from '../../watch_context'; import { WatchStatus, SectionError } from '../../../../components'; diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/monitoring_watch_edit/index.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/monitoring_watch_edit/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/monitoring_watch_edit/index.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/monitoring_watch_edit/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/monitoring_watch_edit/monitoring_watch_edit.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/monitoring_watch_edit/monitoring_watch_edit.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/monitoring_watch_edit/monitoring_watch_edit.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/monitoring_watch_edit/monitoring_watch_edit.tsx diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/request_flyout.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/request_flyout.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/request_flyout.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/request_flyout.tsx diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx similarity index 97% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx index 060b3a270c6e4..3b742102a8ebc 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx @@ -8,7 +8,7 @@ import React, { Fragment } from 'react'; import { EuiComboBox, EuiFieldText, EuiFormRow, EuiTextArea } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { EmailAction } from '../../../../../../common/types/action_types'; +import { EmailAction } from '../../../../../../../../common/types/action_types'; interface Props { action: EmailAction; diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/index.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/index.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx index 1cafb08ca4060..b7ab76d9890bc 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { IndexAction } from '../../../../../../common/types/action_types'; +import { IndexAction } from '../../../../../../../../common/types/action_types'; interface Props { action: IndexAction; diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx similarity index 97% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx index b8bdeaff90821..c09b3c44fde65 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx @@ -8,7 +8,7 @@ import React, { Fragment } from 'react'; import { EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { JiraAction } from '../../../../../../common/types/action_types'; +import { JiraAction } from '../../../../../../../../common/types/action_types'; interface Props { action: JiraAction; diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx index b70e504519ae5..7da2a22ecd6c4 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { LoggingAction } from '../../../../../../common/types/action_types'; +import { LoggingAction } from '../../../../../../../../common/types/action_types'; interface Props { action: LoggingAction; diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx similarity index 95% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx index b2b670bf6b91f..3287bdefa08aa 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx @@ -7,7 +7,7 @@ import React, { Fragment } from 'react'; import { EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { PagerDutyAction } from '../../../../../../common/types/action_types'; +import { PagerDutyAction } from '../../../../../../../../common/types/action_types'; interface Props { action: PagerDutyAction; diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx similarity index 96% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx index 7b5a598c97eb7..a72cf232d8d09 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx @@ -6,7 +6,7 @@ import React, { Fragment } from 'react'; import { EuiComboBox, EuiTextArea, EuiFormRow } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { SlackAction } from '../../../../../../common/types/action_types'; +import { SlackAction } from '../../../../../../../../common/types/action_types'; interface Props { action: SlackAction; diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx similarity index 98% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx index c3784e1ca5516..bdc6f0bcbb717 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx @@ -18,7 +18,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { WebhookAction } from '../../../../../../common/types/action_types'; +import { WebhookAction } from '../../../../../../../../common/types/action_types'; interface Props { action: WebhookAction; @@ -39,7 +39,7 @@ export const WebhookActionFields: React.FunctionComponent = ({ useEffect(() => { editAction({ key: 'contentType', value: 'application/json' }); // set content-type for threshold watch to json by default - }, []); + }, [editAction]); return ( diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/index.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/index.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx similarity index 91% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx index 8b72eb7f19456..4fca772a18217 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx @@ -21,13 +21,12 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ExecuteDetails } from 'plugins/watcher/models/execute_details/execute_details'; -import { Action } from 'plugins/watcher/models/action'; -import { toastNotifications } from 'ui/notify'; -import { WatchHistoryItem } from 'plugins/watcher/models/watch_history_item'; -import { ThresholdWatch } from 'plugins/watcher/models/watch/threshold_watch'; -import { ActionType } from '../../../../../common/types/action_types'; -import { ACTION_TYPES, ACTION_MODES } from '../../../../../common/constants'; +import { ExecuteDetails } from 'plugins/watcher/np_ready/application/models/execute_details/execute_details'; +import { Action } from 'plugins/watcher/np_ready/application/models/action'; +import { WatchHistoryItem } from 'plugins/watcher/np_ready/application/models/watch_history_item'; +import { ThresholdWatch } from 'plugins/watcher/np_ready/application/models/watch/threshold_watch'; +import { ActionType } from '../../../../../../../common/types/action_types'; +import { ACTION_TYPES, ACTION_MODES } from '../../../../../../../common/constants'; import { WatchContext } from '../../watch_context'; import { WebhookActionFields, @@ -39,8 +38,8 @@ import { JiraActionFields, } from './action_fields'; import { executeWatch } from '../../../../lib/api'; -import { watchActionsConfigurationMap } from '../../../../lib/documentation_links'; import { SectionError } from '../../../../components'; +import { useAppContext } from '../../../../app_context'; const actionFieldsComponentMap = { [ACTION_TYPES.LOGGING]: LoggingActionFields, @@ -71,6 +70,10 @@ export const WatchActionsAccordion: React.FunctionComponent = ({ settings, actionErrors, }) => { + const { + links: { watchActionsConfigurationMap }, + toasts, + } = useAppContext(); const { watch, setWatchProperty } = useContext(WatchContext); const { actions } = watch; @@ -238,9 +241,9 @@ export const WatchActionsAccordion: React.FunctionComponent = ({ if (actionStatus && actionStatus.lastExecutionSuccessful === false) { const message = actionStatus.lastExecutionReason || action.simulateFailMessage; - return toastNotifications.addDanger(message); + return toasts.addDanger(message); } - return toastNotifications.addSuccess(action.simulateMessage); + return toasts.addSuccess(action.simulateMessage); }} > {action.simulatePrompt} diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx similarity index 96% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx index 82f3352b4e023..d92cccfa00f14 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx @@ -16,9 +16,9 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useContext, useState } from 'react'; -import { Action } from 'plugins/watcher/models/action'; +import { Action } from 'plugins/watcher/np_ready/application/models/action'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ACTION_TYPES } from '../../../../../common/constants'; +import { ACTION_TYPES } from '../../../../../../../common/constants'; import { WatchContext } from '../../watch_context'; const disabledMessage = i18n.translate( diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx similarity index 93% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx index a2e46652429ea..6072f93e53cf6 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx @@ -6,7 +6,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiTitle, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useContext } from 'react'; -import { loadSettings } from '../../../../lib/api'; +import { useLoadSettings } from '../../../../lib/api'; import { WatchActionsDropdown } from './threshold_watch_action_dropdown'; import { WatchActionsAccordion } from './threshold_watch_action_accordion'; import { WatchContext } from '../../watch_context'; @@ -22,7 +22,7 @@ interface Props { export const WatchActionsPanel: React.FunctionComponent = ({ actionErrors }) => { const { watch } = useContext(WatchContext); - const { data: settings, isLoading } = loadSettings(); + const { data: settings, isLoading } = useLoadSettings(); return (
diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx similarity index 95% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx index 910d4f1e0b15c..f1b5d2c9eab7b 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx @@ -26,9 +26,9 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { TIME_UNITS } from '../../../../../common/constants'; -import { serializeThresholdWatch } from '../../../../../common/lib/serialization'; -import { ErrableFormRow, SectionError } from '../../../../components'; +import { TIME_UNITS } from '../../../../../../../common/constants'; +import { serializeThresholdWatch } from '../../../../../../../common/lib/serialization'; +import { ErrableFormRow, SectionError, Error as ServerError } from '../../../../components'; import { fetchFields, getMatchingIndices, loadIndexPatterns } from '../../../../lib/api'; import { aggTypes } from '../../../../models/watch/agg_types'; import { groupByTypes } from '../../../../models/watch/group_by_types'; @@ -40,6 +40,7 @@ import { WatchActionsPanel } from './threshold_watch_action_panel'; import { getTimeUnitLabel } from '../../../../lib/get_time_unit_label'; import { goToWatchList } from '../../../../lib/navigation'; import { RequestFlyout } from '../request_flyout'; +import { useAppContext } from '../../../../app_context'; const expressionFieldsWithValidation = [ 'aggField', @@ -104,7 +105,7 @@ const getTimeFieldOptions = (fields: any) => { }; interface IOption { label: string; - options: Array<{ value: string; label: string }>; + options: Array<{ value: string; label: string; key?: string }>; } const getIndexOptions = async (patternString: string, indexPatterns: string[]) => { @@ -129,12 +130,14 @@ const getIndexOptions = async (patternString: string, indexPatterns: string[]) = defaultMessage: 'Based on your indices and index patterns', } ), - options: matchingOptions.map(match => { - return { - label: match, - value: match, - }; - }), + options: matchingOptions + .map(match => { + return { + label: match, + value: match, + }; + }) + .sort((a, b) => String(a.label).localeCompare(b.label)), }); } @@ -144,6 +147,7 @@ const getIndexOptions = async (patternString: string, indexPatterns: string[]) = }), options: [ { + key: 'UNIQUE_CHOOSE_KEY', value: patternString, label: patternString, }, @@ -155,7 +159,8 @@ const getIndexOptions = async (patternString: string, indexPatterns: string[]) = export const ThresholdWatchEdit = ({ pageTitle }: { pageTitle: string }) => { // hooks - const [indexPatterns, setIndexPatterns] = useState([]); + const { toasts } = useAppContext(); + const [indexPatterns, setIndexPatterns] = useState([]); const [esFields, setEsFields] = useState([]); const [indexOptions, setIndexOptions] = useState([]); const [timeFieldOptions, setTimeFieldOptions] = useState([firstFieldOption]); @@ -165,34 +170,33 @@ export const ThresholdWatchEdit = ({ pageTitle }: { pageTitle: string }) => { const [watchThresholdPopoverOpen, setWatchThresholdPopoverOpen] = useState(false); const [watchDurationPopoverOpen, setWatchDurationPopoverOpen] = useState(false); const [aggTypePopoverOpen, setAggTypePopoverOpen] = useState(false); - const [serverError, setServerError] = useState<{ - data: { nessage: string; error: string }; - } | null>(null); + const [serverError, setServerError] = useState(null); const [isSaving, setIsSaving] = useState(false); const [isIndiciesLoading, setIsIndiciesLoading] = useState(false); const [isRequestVisible, setIsRequestVisible] = useState(false); const { watch, setWatchProperty } = useContext(WatchContext); - const getIndexPatterns = async () => { - const indexPatternObjects = await loadIndexPatterns(); - const titles = indexPatternObjects.map((indexPattern: any) => indexPattern.attributes.title); - setIndexPatterns(titles); - }; + useEffect(() => { + const getIndexPatterns = async () => { + const indexPatternObjects = await loadIndexPatterns(); + const titles = indexPatternObjects.map((indexPattern: any) => indexPattern.attributes.title); + setIndexPatterns(titles); + }; - const loadData = async () => { - if (watch.index && watch.index.length > 0) { - const allEsFields = await getFields(watch.index); - const timeFields = getTimeFieldOptions(allEsFields); - setEsFields(allEsFields); - setTimeFieldOptions(timeFields); - setWatchProperty('timeFields', timeFields); - } - getIndexPatterns(); - }; + const loadData = async () => { + if (watch.index && watch.index.length > 0) { + const allEsFields = await getFields(watch.index); + const timeFields = getTimeFieldOptions(allEsFields); + setEsFields(allEsFields); + setTimeFieldOptions(timeFields); + setWatchProperty('timeFields', timeFields); + } + getIndexPatterns(); + }; - useEffect(() => { loadData(); + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const { errors } = watch.validate(); @@ -899,7 +903,7 @@ export const ThresholdWatchEdit = ({ pageTitle }: { pageTitle: string }) => { isLoading={isSaving} onClick={async () => { setIsSaving(true); - const savedWatch = await onWatchSave(watch); + const savedWatch = await onWatchSave(watch, toasts); if (savedWatch && savedWatch.error) { setIsSaving(false); return setServerError(savedWatch.error); diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx similarity index 83% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx index 772f3cc024fe8..a3da7d14c8886 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx @@ -18,20 +18,20 @@ import { ScaleType, Settings, } from '@elastic/charts'; -import { TimeBuckets } from 'ui/time_buckets'; import dateMath from '@elastic/datemath'; -import chrome from 'ui/chrome'; import moment from 'moment-timezone'; +import { IUiSettingsClient } from 'src/core/public'; import { EuiCallOut, EuiLoadingChart, EuiSpacer, EuiEmptyPrompt, EuiText } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { VisualizeOptions } from 'plugins/watcher/models/visualize_options'; -import { ThresholdWatch } from 'plugins/watcher/models/watch/threshold_watch'; -import { npStart } from 'ui/new_platform'; -import { getWatchVisualizationData } from '../../../../lib/api'; +import { VisualizeOptions } from 'plugins/watcher/np_ready/application/models/visualize_options'; +import { ThresholdWatch } from 'plugins/watcher/np_ready/application/models/watch/threshold_watch'; + +import { useGetWatchVisualizationData } from '../../../../lib/api'; import { WatchContext } from '../../watch_context'; import { aggTypes } from '../../../../models/watch/agg_types'; import { comparators } from '../../../../models/watch/comparators'; import { SectionError, Error } from '../../../../components'; +import { useAppContext } from '../../../../app_context'; const customTheme = () => { return { @@ -46,8 +46,7 @@ const customTheme = () => { }; }; -const getTimezone = () => { - const config = chrome.getUiSettingsClient(); +const getTimezone = (config: IUiSettingsClient) => { const DATE_FORMAT_CONFIG_KEY = 'dateFormat:tz'; const isCustomTimezone = !config.isDefault(DATE_FORMAT_CONFIG_KEY); if (isCustomTimezone) { @@ -59,8 +58,7 @@ const getTimezone = () => { return detectedTimezone; } // default to UTC if we can't figure out the timezone - const tzOffset = moment().format('Z'); - return tzOffset; + return moment().format('Z'); }; const getDomain = (watch: any) => { @@ -83,16 +81,20 @@ const getThreshold = (watch: any) => { return watch.threshold.slice(0, comparators[watch.thresholdComparator].requiredValues); }; -const getTimeBuckets = (watch: any) => { +const getTimeBuckets = (watch: any, timeBuckets: any) => { const domain = getDomain(watch); - const timeBuckets = new TimeBuckets(); timeBuckets.setBounds(domain); return timeBuckets; }; export const WatchVisualization = () => { + const { + legacy: { TimeBuckets }, + euiUtils, + uiSettings, + } = useAppContext(); const { watch } = useContext(WatchContext); - const chartsTheme = npStart.plugins.eui_utils.useChartsTheme(); + const chartsTheme = euiUtils.useChartsTheme(); const { index, timeField, @@ -117,7 +119,7 @@ export const WatchVisualization = () => { rangeFrom: domain.min, rangeTo: domain.max, interval, - timezone: getTimezone(), + timezone: getTimezone(uiSettings), }); // Fetching visualization data is independent of watch actions @@ -129,30 +131,33 @@ export const WatchVisualization = () => { data: watchVisualizationData, error, sendRequest: reload, - } = getWatchVisualizationData(watchWithoutActions, visualizeOptions); + } = useGetWatchVisualizationData(watchWithoutActions, visualizeOptions); - useEffect(() => { - // Prevent sending a second request on initial render. - if (isInitialRequest) { - return; - } - - reload(); - }, [ - index, - timeField, - triggerIntervalSize, - triggerIntervalUnit, - aggType, - aggField, - termSize, - termField, - thresholdComparator, - timeWindowSize, - timeWindowUnit, - groupBy, - threshold, - ]); + useEffect( + () => { + // Prevent sending a second request on initial render. + if (isInitialRequest) { + return; + } + reload(); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [ + index, + timeField, + triggerIntervalSize, + triggerIntervalUnit, + aggType, + aggField, + termSize, + termField, + thresholdComparator, + timeWindowSize, + timeWindowUnit, + groupBy, + threshold, + ] + ); if (isInitialRequest && isLoading) { return ( @@ -190,7 +195,7 @@ export const WatchVisualization = () => { if (watchVisualizationData) { const watchVisualizationDataKeys = Object.keys(watchVisualizationData); - const timezone = getTimezone(); + const timezone = getTimezone(uiSettings); const actualThreshold = getThreshold(watch); let maxY = actualThreshold[actualThreshold.length - 1]; @@ -204,7 +209,7 @@ export const WatchVisualization = () => { const dateFormatter = (d: number) => { return moment(d) .tz(timezone) - .format(getTimeBuckets(watch).getScaledDateFormat()); + .format(getTimeBuckets(watch, new TimeBuckets()).getScaledDateFormat()); }; const aggLabel = aggTypes[watch.aggType].text; return ( diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/watch_edit.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/watch_edit.tsx similarity index 82% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/watch_edit.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/watch_edit.tsx index 25daf190dc1b1..9f252d3e542e0 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/components/watch_edit.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/watch_edit.tsx @@ -9,13 +9,11 @@ import { isEqual } from 'lodash'; import { EuiPageContent } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import chrome from 'ui/chrome'; -import { MANAGEMENT_BREADCRUMB } from 'ui/management'; -import { Watch } from 'plugins/watcher/models/watch'; +import { Watch } from 'plugins/watcher/np_ready/application/models/watch'; import { FormattedMessage } from '@kbn/i18n/react'; -import { WATCH_TYPES } from '../../../../common/constants'; -import { BaseWatch } from '../../../../common/types/watch_types'; +import { WATCH_TYPES } from '../../../../../../common/constants'; +import { BaseWatch } from '../../../../../../common/types/watch_types'; import { getPageErrorCode, PageError, SectionLoading, SectionError } from '../../../components'; import { loadWatch } from '../../../lib/api'; import { listBreadcrumb, editBreadcrumb, createBreadcrumb } from '../../../lib/breadcrumbs'; @@ -23,6 +21,7 @@ import { JsonWatchEdit } from './json_watch_edit'; import { ThresholdWatchEdit } from './threshold_watch_edit'; import { MonitoringWatchEdit } from './monitoring_watch_edit'; import { WatchContext } from '../watch_context'; +import { useAppContext } from '../../../app_context'; const getTitle = (watch: BaseWatch) => { if (watch.isNew) { @@ -97,6 +96,10 @@ export const WatchEdit = ({ }; }) => { // hooks + const { + legacy: { MANAGEMENT_BREADCRUMB }, + chrome, + } = useAppContext(); const [{ watch, loadError }, dispatch] = useReducer(watchReducer, { watch: null }); const setWatchProperty = (property: string, value: any) => { @@ -107,33 +110,33 @@ export const WatchEdit = ({ dispatch({ command: 'addAction', payload: action }); }; - const getWatch = async () => { - if (id) { - try { - const loadedWatch = await loadWatch(id); - dispatch({ command: 'setWatch', payload: loadedWatch }); - } catch (error) { - dispatch({ command: 'setError', payload: error }); - } - } else if (type) { - const WatchType = Watch.getWatchTypes()[type]; - if (WatchType) { - dispatch({ command: 'setWatch', payload: new WatchType() }); + useEffect(() => { + const getWatch = async () => { + if (id) { + try { + const loadedWatch = await loadWatch(id); + dispatch({ command: 'setWatch', payload: loadedWatch }); + } catch (error) { + dispatch({ command: 'setError', payload: error }); + } + } else if (type) { + const WatchType = Watch.getWatchTypes()[type]; + if (WatchType) { + dispatch({ command: 'setWatch', payload: new WatchType() }); + } } - } - }; + }; - useEffect(() => { getWatch(); - }, []); + }, [id, type]); useEffect(() => { - chrome.breadcrumbs.set([ + chrome.setBreadcrumbs([ MANAGEMENT_BREADCRUMB, listBreadcrumb, id ? editBreadcrumb : createBreadcrumb, ]); - }, [id]); + }, [id, chrome, MANAGEMENT_BREADCRUMB]); const errorCode = getPageErrorCode(loadError); if (errorCode) { diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/watch_context.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_context.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/watch_context.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_context.ts diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/watch_edit_actions.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_edit_actions.ts similarity index 86% rename from x-pack/legacy/plugins/watcher/public/sections/watch_edit/watch_edit_actions.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_edit_actions.ts index 320ba59e0589e..b93c2c510047d 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_edit/watch_edit_actions.ts +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_edit_actions.ts @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ +import { ToastsSetup } from 'src/core/public'; import { i18n } from '@kbn/i18n'; -import { toastNotifications } from 'ui/notify'; import { get } from 'lodash'; -import { ACTION_TYPES, WATCH_TYPES } from '../../../common/constants'; -import { BaseWatch } from '../../../common/types/watch_types'; +import { ACTION_TYPES, WATCH_TYPES } from '../../../../../common/constants'; +import { BaseWatch } from '../../../../../common/types/watch_types'; import { createWatch } from '../../lib/api'; import { goToWatchList } from '../../lib/navigation'; @@ -62,10 +62,10 @@ function createActionsForWatch(watchInstance: BaseWatch) { return watchInstance; } -export async function saveWatch(watch: BaseWatch): Promise { +export async function saveWatch(watch: BaseWatch, toasts: ToastsSetup): Promise { try { await createWatch(watch); - toastNotifications.addSuccess( + toasts.addSuccess( i18n.translate('xpack.watcher.sections.watchEdit.json.saveSuccessNotificationText', { defaultMessage: "Saved '{watchDisplayName}'", values: { @@ -75,11 +75,11 @@ export async function saveWatch(watch: BaseWatch): Promise { ); goToWatchList(); } catch (error) { - return error.response ? { error: error.response } : { error }; + return { error: error?.response.data ?? (error.body || error) }; } } -export async function onWatchSave(watch: BaseWatch): Promise { +export async function onWatchSave(watch: BaseWatch, toasts: ToastsSetup): Promise { const watchActions = watch.watch && watch.watch.actions; const watchData = watchActions ? createActionsForWatch(watch) : watch; @@ -109,7 +109,7 @@ export async function onWatchSave(watch: BaseWatch): Promise { }, }; } - return saveWatch(watchData); + return saveWatch(watchData, toasts); } - return saveWatch(watchData); + return saveWatch(watchData, toasts); } diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_list/components/watch_list.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_list/components/watch_list.tsx similarity index 97% rename from x-pack/legacy/plugins/watcher/public/sections/watch_list/components/watch_list.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_list/components/watch_list.tsx index d5191c56643c2..b2afc0b92509b 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_list/components/watch_list.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_list/components/watch_list.tsx @@ -27,10 +27,8 @@ import { import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { Moment } from 'moment'; -import chrome from 'ui/chrome'; -import { MANAGEMENT_BREADCRUMB } from 'ui/management'; -import { REFRESH_INTERVALS, PAGINATION, WATCH_TYPES } from '../../../../common/constants'; +import { REFRESH_INTERVALS, PAGINATION, WATCH_TYPES } from '../../../../../../common/constants'; import { listBreadcrumb } from '../../../lib/breadcrumbs'; import { getPageErrorCode, @@ -41,12 +39,17 @@ import { SectionLoading, Error, } from '../../../components'; -import { loadWatches } from '../../../lib/api'; -import { watcherGettingStartedUrl } from '../../../lib/documentation_links'; +import { useLoadWatches } from '../../../lib/api'; import { goToCreateThresholdAlert, goToCreateAdvancedWatch } from '../../../lib/navigation'; +import { useAppContext } from '../../../app_context'; export const WatchList = () => { // hooks + const { + chrome, + legacy: { MANAGEMENT_BREADCRUMB }, + links: { watcherGettingStartedUrl }, + } = useAppContext(); const [selection, setSelection] = useState([]); const [watchesToDelete, setWatchesToDelete] = useState([]); // Filter out deleted watches on the client, because the API will return 200 even though some watches @@ -54,10 +57,10 @@ export const WatchList = () => { const [deletedWatches, setDeletedWatches] = useState([]); useEffect(() => { - chrome.breadcrumbs.set([MANAGEMENT_BREADCRUMB, listBreadcrumb]); - }, []); + chrome.setBreadcrumbs([MANAGEMENT_BREADCRUMB, listBreadcrumb]); + }, [chrome, MANAGEMENT_BREADCRUMB]); - const { isLoading: isWatchesLoading, data: watches, error } = loadWatches( + const { isLoading: isWatchesLoading, data: watches, error } = useLoadWatches( REFRESH_INTERVALS.WATCH_LIST ); diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_detail.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_detail.tsx similarity index 96% rename from x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_detail.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_detail.tsx index aba4fd0c52a2e..197342bba4180 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_detail.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_detail.tsx @@ -7,7 +7,6 @@ import React, { Fragment, useState, useEffect, useContext } from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { toastNotifications } from 'ui/notify'; import { EuiInMemoryTable, @@ -21,8 +20,9 @@ import { } from '@elastic/eui'; import { ackWatchAction } from '../../../lib/api'; import { WatchStatus } from '../../../components'; -import { PAGINATION } from '../../../../common/constants'; +import { PAGINATION } from '../../../../../../common/constants'; import { WatchDetailsContext } from '../watch_details_context'; +import { useAppContext } from '../../../app_context'; interface ActionError { code: string; @@ -36,6 +36,7 @@ interface ActionStatus { } export const WatchDetail = () => { + const { toasts } = useAppContext(); const { watchDetail } = useContext(WatchDetailsContext); const [actionStatuses, setActionStatuses] = useState([]); @@ -60,7 +61,7 @@ export const WatchDetail = () => { }; }); setActionStatuses(actionStatusesWithErrors); - }, [watchDetail]); + }, [watchDetail, actionErrors, currentActionStatuses]); const baseColumns = [ { @@ -144,7 +145,7 @@ export const WatchDetail = () => { return setActionStatuses(newActionStatusesWithErrors); } catch (e) { setIsActionStatusLoading(false); - toastNotifications.addDanger( + toasts.addDanger( i18n.translate( 'xpack.watcher.sections.watchDetail.watchTable.ackActionErrorMessage', { diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_history.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_history.tsx similarity index 97% rename from x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_history.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_history.tsx index bf6ca0c6c43a0..2bc1a0cbace18 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_history.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_history.tsx @@ -23,9 +23,9 @@ import { EuiTitle, } from '@elastic/eui'; -import { PAGINATION } from '../../../../common/constants'; +import { PAGINATION } from '../../../../../../common/constants'; import { WatchStatus, SectionError, Error } from '../../../components'; -import { loadWatchHistory, loadWatchHistoryDetail } from '../../../lib/api'; +import { useLoadWatchHistory, useLoadWatchHistoryDetail } from '../../../lib/api'; import { WatchDetailsContext } from '../watch_details_context'; const watchHistoryTimeSpanOptions = [ @@ -83,12 +83,12 @@ export const WatchHistory = () => { setIsActivated(isActive); } - const { error: historyError, data: history, isLoading } = loadWatchHistory( + const { error: historyError, data: history, isLoading } = useLoadWatchHistory( loadedWatch.id, watchHistoryTimeSpan ); - const { error: watchHistoryDetailsError, data: watchHistoryDetails } = loadWatchHistoryDetail( + const { error: watchHistoryDetailsError, data: watchHistoryDetails } = useLoadWatchHistoryDetail( detailWatchId ); diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_status.tsx b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_status.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_status.tsx rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_status.tsx index 413e8f638887b..53817c23e72eb 100644 --- a/x-pack/legacy/plugins/watcher/public/sections/watch_status/components/watch_status.tsx +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_status.tsx @@ -17,15 +17,12 @@ import { EuiBadge, EuiButtonEmpty, } from '@elastic/eui'; -import chrome from 'ui/chrome'; -import { MANAGEMENT_BREADCRUMB } from 'ui/management'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { toastNotifications } from 'ui/notify'; import { WatchDetail } from './watch_detail'; import { WatchHistory } from './watch_history'; import { listBreadcrumb, statusBreadcrumb } from '../../../lib/breadcrumbs'; -import { loadWatchDetail, deactivateWatch, activateWatch } from '../../../lib/api'; +import { useLoadWatchDetail, deactivateWatch, activateWatch } from '../../../lib/api'; import { WatchDetailsContext } from '../watch_details_context'; import { getPageErrorCode, @@ -34,6 +31,7 @@ import { DeleteWatchesModal, } from '../../../components'; import { goToWatchList } from '../../../lib/navigation'; +import { useAppContext } from '../../../app_context'; interface WatchStatusTab { id: string; @@ -69,11 +67,16 @@ export const WatchStatus = ({ }; }; }) => { + const { + chrome, + legacy: { MANAGEMENT_BREADCRUMB }, + toasts, + } = useAppContext(); const { error: watchDetailError, data: watchDetail, isLoading: isWatchDetailLoading, - } = loadWatchDetail(id); + } = useLoadWatchDetail(id); const [selectedTab, setSelectedTab] = useState(WATCH_EXECUTION_HISTORY_TAB); const [isActivated, setIsActivated] = useState(undefined); @@ -81,8 +84,8 @@ export const WatchStatus = ({ const [isTogglingActivation, setIsTogglingActivation] = useState(false); useEffect(() => { - chrome.breadcrumbs.set([MANAGEMENT_BREADCRUMB, listBreadcrumb, statusBreadcrumb]); - }, [id]); + chrome.setBreadcrumbs([MANAGEMENT_BREADCRUMB, listBreadcrumb, statusBreadcrumb]); + }, [id, chrome, MANAGEMENT_BREADCRUMB]); const errorCode = getPageErrorCode(watchDetailError); @@ -148,7 +151,7 @@ export const WatchStatus = ({ defaultMessage: "Couldn't activate watch", } ); - return toastNotifications.addDanger(message); + return toasts.addDanger(message); } setIsActivated(!isActivated); diff --git a/x-pack/legacy/plugins/watcher/public/sections/watch_status/watch_details_context.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/watch_details_context.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/sections/watch_status/watch_details_context.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/watch_details_context.ts diff --git a/x-pack/legacy/plugins/watcher/public/shared_imports.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/shared_imports.ts similarity index 79% rename from x-pack/legacy/plugins/watcher/public/shared_imports.ts rename to x-pack/legacy/plugins/watcher/public/np_ready/application/shared_imports.ts index 3d93b882733ab..60445b00c0985 100644 --- a/x-pack/legacy/plugins/watcher/public/shared_imports.ts +++ b/x-pack/legacy/plugins/watcher/public/np_ready/application/shared_imports.ts @@ -10,4 +10,4 @@ export { UseRequestConfig, sendRequest, useRequest, -} from '../../../../../src/plugins/es_ui_shared/public/request'; +} from '../../../../../../../src/plugins/es_ui_shared/public/request/np_ready_request'; diff --git a/x-pack/legacy/plugins/watcher/public/index.js b/x-pack/legacy/plugins/watcher/public/np_ready/index.ts similarity index 71% rename from x-pack/legacy/plugins/watcher/public/index.js rename to x-pack/legacy/plugins/watcher/public/np_ready/index.ts index c1b84e76d0008..ff635579316e5 100644 --- a/x-pack/legacy/plugins/watcher/public/index.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/index.ts @@ -3,6 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { WatcherUIPlugin } from './plugin'; -import './register_route'; -import './register_management_sections'; +export const plugin = () => new WatcherUIPlugin(); diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/plugin.ts b/x-pack/legacy/plugins/watcher/public/np_ready/plugin.ts new file mode 100644 index 0000000000000..161de9b5fc060 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/public/np_ready/plugin.ts @@ -0,0 +1,62 @@ +/* + * 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 { Plugin, CoreSetup, CoreStart } from 'src/core/public'; + +import { LegacyDependencies } from './types'; + +interface LegacyPlugins { + __LEGACY: LegacyDependencies; +} + +export class WatcherUIPlugin implements Plugin { + /* TODO: Remove this in future. We need this at mount (setup) but it's only available on start plugins. */ + euiUtils: any = null; + + setup({ application, notifications, http, uiSettings }: CoreSetup, { __LEGACY }: LegacyPlugins) { + application.register({ + id: 'watcher', + title: 'Watcher', + mount: async ( + { + core: { + docLinks, + chrome, + // Waiting for types to be updated. + // @ts-ignore + savedObjects, + i18n: { Context: I18nContext }, + }, + }, + { element } + ) => { + const euiUtils = this.euiUtils!; + const { boot } = await import('./application/boot'); + return boot({ + element, + toasts: notifications.toasts, + http, + uiSettings, + docLinks, + chrome, + euiUtils, + savedObjects: savedObjects.client, + I18nContext, + legacy: { + ...__LEGACY, + }, + }); + }, + }); + } + + start(core: CoreStart, { eui_utils }: any) { + // eslint-disable-next-line @typescript-eslint/camelcase + this.euiUtils = eui_utils; + } + + stop() {} +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/fields/register_fields_routes.js b/x-pack/legacy/plugins/watcher/public/np_ready/types.ts similarity index 63% rename from x-pack/legacy/plugins/watcher/server/routes/api/fields/register_fields_routes.js rename to x-pack/legacy/plugins/watcher/public/np_ready/types.ts index 64b9a14f9c438..22109f99c2c48 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/fields/register_fields_routes.js +++ b/x-pack/legacy/plugins/watcher/public/np_ready/types.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { registerListRoute } from './register_list_route'; - -export function registerFieldsRoutes(server) { - registerListRoute(server); +export interface LegacyDependencies { + MANAGEMENT_BREADCRUMB: { text: string; href?: string }; + TimeBuckets: any; + licenseStatus: any; } diff --git a/x-pack/legacy/plugins/watcher/public/register_feature.js b/x-pack/legacy/plugins/watcher/public/register_feature.js deleted file mode 100644 index 5dd4f28f03bc5..0000000000000 --- a/x-pack/legacy/plugins/watcher/public/register_feature.js +++ /dev/null @@ -1,24 +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 { FeatureCatalogueRegistryProvider, FeatureCatalogueCategory } from 'ui/registry/feature_catalogue'; -import { i18n } from '@kbn/i18n'; - -FeatureCatalogueRegistryProvider.register(() => { - return { - id: 'watcher', - title: 'Watcher', // This is a product name so we don't translate it. - description: i18n.translate('xpack.watcher.watcherDescription', { - defaultMessage: 'Detect changes in your data by creating, managing, and monitoring alerts.' - }), - icon: 'watchesApp', - path: '/app/kibana#/management/elasticsearch/watcher/watches', - showOnHomePage: true, - category: FeatureCatalogueCategory.ADMIN - }; -}); diff --git a/x-pack/legacy/plugins/watcher/public/register_feature.ts b/x-pack/legacy/plugins/watcher/public/register_feature.ts new file mode 100644 index 0000000000000..0de41e09f788e --- /dev/null +++ b/x-pack/legacy/plugins/watcher/public/register_feature.ts @@ -0,0 +1,21 @@ +/* + * 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 { i18n } from '@kbn/i18n'; +import { npSetup } from 'ui/new_platform'; +import { FeatureCatalogueCategory } from 'ui/registry/feature_catalogue'; + +npSetup.plugins.home.featureCatalogue.register({ + id: 'watcher', + title: 'Watcher', // This is a product name so we don't translate it. + category: FeatureCatalogueCategory.ADMIN, + description: i18n.translate('xpack.watcher.watcherDescription', { + defaultMessage: 'Detect changes in your data by creating, managing, and monitoring alerts.', + }), + icon: 'watchesApp', + path: '/app/kibana#/management/elasticsearch/watcher/watches', + showOnHomePage: true, +}); diff --git a/x-pack/legacy/plugins/watcher/public/register_management_sections.js b/x-pack/legacy/plugins/watcher/public/register_management_sections.js deleted file mode 100644 index 886ac7d28db64..0000000000000 --- a/x-pack/legacy/plugins/watcher/public/register_management_sections.js +++ /dev/null @@ -1,60 +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 { management } from 'ui/management'; -import { i18n } from '@kbn/i18n'; - -management.getSection('elasticsearch').register('watcher', { - display: i18n.translate('xpack.watcher.sections.watchList.managementSection.watcherDisplayName', { - defaultMessage: 'Watcher', - }), - order: 6, - url: '#/management/elasticsearch/watcher/', -}); - -management.getSection('elasticsearch/watcher').register('watches', { - display: i18n.translate('xpack.watcher.sections.watchList.managementSection.watchesDisplayName', { - defaultMessage: 'Watches', - }), - order: 1, -}); - -management.getSection('elasticsearch/watcher').register('watch', { - visible: false, -}); - -management.getSection('elasticsearch/watcher/watch').register('status', { - display: i18n.translate('xpack.watcher.sections.watchList.managementSection.statusDisplayName', { - defaultMessage: 'Status', - }), - order: 1, - visible: false, -}); - -management.getSection('elasticsearch/watcher/watch').register('edit', { - display: i18n.translate('xpack.watcher.sections.watchList.managementSection.editDisplayName', { - defaultMessage: 'Edit', - }), - order: 2, - visible: false, -}); - -management.getSection('elasticsearch/watcher/watch').register('new', { - display: i18n.translate( - 'xpack.watcher.sections.watchList.managementSection.newWatchDisplayName', - { - defaultMessage: 'New Watch', - } - ), - order: 1, - visible: false, -}); - -management.getSection('elasticsearch/watcher/watch').register('history-item', { - order: 1, - visible: false, -}); diff --git a/x-pack/legacy/plugins/watcher/public/register_route.js b/x-pack/legacy/plugins/watcher/public/register_route.js deleted file mode 100644 index c58be17bc6e75..0000000000000 --- a/x-pack/legacy/plugins/watcher/public/register_route.js +++ /dev/null @@ -1,68 +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 React from 'react'; -import { render, unmountComponentAtNode } from 'react-dom'; -import { SavedObjectsClientProvider } from 'ui/saved_objects'; -import routes from 'ui/routes'; -import { management } from 'ui/management'; -import { xpackInfo } from 'plugins/xpack_main/services/xpack_info'; -import template from './app.html'; -import { App } from './app'; -import { setHttpClient, setSavedObjectsClient } from './lib/api'; -import { I18nContext } from 'ui/i18n'; -import { manageAngularLifecycle } from './lib/manage_angular_lifecycle'; -import { PLUGIN } from '../common/constants'; -import { LICENSE_STATUS_UNAVAILABLE, LICENSE_STATUS_INVALID } from '../../../common/constants'; - -let elem; -const renderReact = async (elem, licenseStatus) => { - render( - - - , - elem - ); -}; -routes.when('/management/elasticsearch/watcher/:param1?/:param2?/:param3?/:param4?', { - template, - controller: class WatcherController { - constructor($injector, $scope, $http, Private) { - const $route = $injector.get('$route'); - const licenseStatus = xpackInfo.get(`features.${PLUGIN.ID}`); - - // clean up previously rendered React app if one exists - // this happens because of React Router redirects - elem && unmountComponentAtNode(elem); - setSavedObjectsClient(Private(SavedObjectsClientProvider)); - // NOTE: We depend upon Angular's $http service because it's decorated with interceptors, - // e.g. to check license status per request. - setHttpClient($http); - $scope.$$postDigest(() => { - elem = document.getElementById('watchReactRoot'); - renderReact(elem, licenseStatus); - manageAngularLifecycle($scope, $route, elem); - }); - } - }, - controllerAs: 'watchRoute', -}); - -routes.defaults(/\/management/, { - resolve: { - watcherManagementSection: () => { - const watchesSection = management.getSection('elasticsearch/watcher'); - const licenseStatus = xpackInfo.get(`features.${PLUGIN.ID}`); - const { status } = licenseStatus; - - if (status === LICENSE_STATUS_INVALID || status === LICENSE_STATUS_UNAVAILABLE) { - return watchesSection.hide(); - } - - watchesSection.show(); - - }, - }, -}); diff --git a/x-pack/legacy/plugins/watcher/server/lib/call_with_internal_user_factory/call_with_internal_user_factory.js b/x-pack/legacy/plugins/watcher/server/lib/call_with_internal_user_factory/call_with_internal_user_factory.js deleted file mode 100644 index b0ca090601062..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/call_with_internal_user_factory/call_with_internal_user_factory.js +++ /dev/null @@ -1,18 +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 { once } from 'lodash'; - -const _callWithInternalUser = once((server) => { - const { callWithInternalUser } = server.plugins.elasticsearch.getCluster('admin'); - return callWithInternalUser; -}); - -export const callWithInternalUserFactory = (server) => { - return (...args) => { - return _callWithInternalUser(server)(...args); - }; -}; diff --git a/x-pack/legacy/plugins/watcher/server/lib/call_with_request_factory/call_with_request_factory.js b/x-pack/legacy/plugins/watcher/server/lib/call_with_request_factory/call_with_request_factory.js deleted file mode 100644 index f60f825b98004..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/call_with_request_factory/call_with_request_factory.js +++ /dev/null @@ -1,21 +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 { once } from 'lodash'; -import { elasticsearchJsPlugin } from '../elasticsearch_js_plugin'; - -const callWithRequest = once((server) => { - const config = { plugins: [ elasticsearchJsPlugin ] }; - const cluster = server.plugins.elasticsearch.createCluster('watcher', config); - - return cluster.callWithRequest; -}); - -export const callWithRequestFactory = (server, request) => { - return (...args) => { - return callWithRequest(server)(request, ...args); - }; -}; diff --git a/x-pack/legacy/plugins/watcher/server/lib/call_with_request_factory/index.js b/x-pack/legacy/plugins/watcher/server/lib/call_with_request_factory/index.js deleted file mode 100644 index 787814d87dff9..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/call_with_request_factory/index.js +++ /dev/null @@ -1,7 +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. - */ - -export { callWithRequestFactory } from './call_with_request_factory'; diff --git a/x-pack/legacy/plugins/watcher/server/lib/elasticsearch_js_plugin/index.js b/x-pack/legacy/plugins/watcher/server/lib/elasticsearch_js_plugin/index.js deleted file mode 100644 index 87b5ff5426c9d..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/elasticsearch_js_plugin/index.js +++ /dev/null @@ -1,7 +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. - */ - -export { elasticsearchJsPlugin } from './elasticsearch_js_plugin'; diff --git a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_custom_error.js b/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_custom_error.js deleted file mode 100644 index f9c102be7a1ff..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_custom_error.js +++ /dev/null @@ -1,21 +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 expect from '@kbn/expect'; -import { wrapCustomError } from '../wrap_custom_error'; - -describe('wrap_custom_error', () => { - describe('#wrapCustomError', () => { - it('should return a Boom object', () => { - const originalError = new Error('I am an error'); - const statusCode = 404; - const wrappedError = wrapCustomError(originalError, statusCode); - - expect(wrappedError.isBoom).to.be(true); - expect(wrappedError.output.statusCode).to.equal(statusCode); - }); - }); -}); diff --git a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_es_error.js b/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_es_error.js deleted file mode 100644 index 467cc4fcdae1f..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_es_error.js +++ /dev/null @@ -1,39 +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 expect from '@kbn/expect'; -import { wrapEsError } from '../wrap_es_error'; - -describe('wrap_es_error', () => { - describe('#wrapEsError', () => { - - let originalError; - beforeEach(() => { - originalError = new Error('I am an error'); - originalError.statusCode = 404; - }); - - it('should return a Boom object', () => { - const wrappedError = wrapEsError(originalError); - - expect(wrappedError.isBoom).to.be(true); - }); - - it('should return the correct Boom object', () => { - const wrappedError = wrapEsError(originalError); - - expect(wrappedError.output.statusCode).to.be(originalError.statusCode); - expect(wrappedError.output.payload.message).to.be(originalError.message); - }); - - it('should return the correct Boom object with custom message', () => { - const wrappedError = wrapEsError(originalError, { 404: 'No encontrado!' }); - - expect(wrappedError.output.statusCode).to.be(originalError.statusCode); - expect(wrappedError.output.payload.message).to.be('No encontrado!'); - }); - }); -}); diff --git a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_unknown_error.js b/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_unknown_error.js deleted file mode 100644 index 85e0b2b3033ad..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/__tests__/wrap_unknown_error.js +++ /dev/null @@ -1,19 +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 expect from '@kbn/expect'; -import { wrapUnknownError } from '../wrap_unknown_error'; - -describe('wrap_unknown_error', () => { - describe('#wrapUnknownError', () => { - it('should return a Boom object', () => { - const originalError = new Error('I am an error'); - const wrappedError = wrapUnknownError(originalError); - - expect(wrappedError.isBoom).to.be(true); - }); - }); -}); diff --git a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/index.js b/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/index.js deleted file mode 100644 index f275f15637091..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/index.js +++ /dev/null @@ -1,9 +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. - */ - -export { wrapCustomError } from './wrap_custom_error'; -export { wrapEsError } from './wrap_es_error'; -export { wrapUnknownError } from './wrap_unknown_error'; diff --git a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_custom_error.js b/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_custom_error.js deleted file mode 100644 index 3295113d38ee5..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_custom_error.js +++ /dev/null @@ -1,18 +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 Boom from 'boom'; - -/** - * Wraps a custom error into a Boom error response and returns it - * - * @param err Object error - * @param statusCode Error status code - * @return Object Boom error response - */ -export function wrapCustomError(err, statusCode) { - return Boom.boomify(err, { statusCode }); -} diff --git a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_es_error.js b/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_es_error.js deleted file mode 100644 index 2df2e4b802e1a..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_es_error.js +++ /dev/null @@ -1,30 +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 Boom from 'boom'; - -/** - * Wraps an error thrown by the ES JS client into a Boom error response and returns it - * - * @param err Object Error thrown by ES JS client - * @param statusCodeToMessageMap Object Optional map of HTTP status codes => error messages - * @return Object Boom error response - */ -export function wrapEsError(err, statusCodeToMessageMap = {}) { - - const statusCode = err.statusCode; - - // If no custom message if specified for the error's status code, just - // wrap the error as a Boom error response and return it - if (!statusCodeToMessageMap[statusCode]) { - return Boom.boomify(err, { statusCode }); - } - - // Otherwise, use the custom message to create a Boom error response and - // return it - const message = statusCodeToMessageMap[statusCode]; - return new Boom(message, { statusCode }); -} diff --git a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_unknown_error.js b/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_unknown_error.js deleted file mode 100644 index ffd915c513362..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/error_wrappers/wrap_unknown_error.js +++ /dev/null @@ -1,17 +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 Boom from 'boom'; - -/** - * Wraps an unknown error into a Boom error response and returns it - * - * @param err Object Unknown error - * @return Object Boom error response - */ -export function wrapUnknownError(err) { - return Boom.boomify(err); -} diff --git a/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/__tests__/is_es_error_factory.js b/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/__tests__/is_es_error_factory.js deleted file mode 100644 index 76fdf7b36c3d0..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/__tests__/is_es_error_factory.js +++ /dev/null @@ -1,48 +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 expect from '@kbn/expect'; -import { isEsErrorFactory } from '../is_es_error_factory'; -import { set } from 'lodash'; - -class MockAbstractEsError {} - -describe('is_es_error_factory', () => { - - let mockServer; - let isEsError; - - beforeEach(() => { - const mockEsErrors = { - _Abstract: MockAbstractEsError - }; - mockServer = {}; - set(mockServer, 'plugins.elasticsearch.getCluster', () => ({ errors: mockEsErrors })); - - isEsError = isEsErrorFactory(mockServer); - }); - - describe('#isEsErrorFactory', () => { - - it('should return a function', () => { - expect(isEsError).to.be.a(Function); - }); - - describe('returned function', () => { - - it('should return true if passed-in err is a known esError', () => { - const knownEsError = new MockAbstractEsError(); - expect(isEsError(knownEsError)).to.be(true); - }); - - it('should return false if passed-in err is not a known esError', () => { - const unknownEsError = {}; - expect(isEsError(unknownEsError)).to.be(false); - - }); - }); - }); -}); diff --git a/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/index.js b/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/index.js deleted file mode 100644 index 441648a8701e0..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/index.js +++ /dev/null @@ -1,7 +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. - */ - -export { isEsErrorFactory } from './is_es_error_factory'; diff --git a/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/is_es_error_factory.js b/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/is_es_error_factory.js deleted file mode 100644 index 80daac5bd496d..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/is_es_error_factory/is_es_error_factory.js +++ /dev/null @@ -1,18 +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 { memoize } from 'lodash'; - -const esErrorsFactory = memoize((server) => { - return server.plugins.elasticsearch.getCluster('admin').errors; -}); - -export function isEsErrorFactory(server) { - const esErrors = esErrorsFactory(server); - return function isEsError(err) { - return err instanceof esErrors._Abstract; - }; -} diff --git a/x-pack/legacy/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.js b/x-pack/legacy/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.js deleted file mode 100644 index 5b34108c9c1c0..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.js +++ /dev/null @@ -1,31 +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 { once } from 'lodash'; -import { wrapCustomError } from '../error_wrappers'; -import { PLUGIN } from '../../../common/constants'; -import { LICENSE_STATUS_VALID } from '../../../../../common/constants/license_status'; - -export const licensePreRoutingFactory = once((server) => { - const xpackMainPlugin = server.plugins.xpack_main; - - // License checking and enable/disable logic - function licensePreRouting() { - const licenseCheckResults = xpackMainPlugin.info.feature(PLUGIN.ID).getLicenseCheckResults(); - const { status } = licenseCheckResults; - - if (status !== LICENSE_STATUS_VALID) { - const error = new Error(licenseCheckResults.message); - const statusCode = 403; - throw wrapCustomError(error, statusCode); - } - - return null; - } - - return licensePreRouting; -}); - diff --git a/x-pack/legacy/plugins/watcher/server/lib/call_with_internal_user_factory/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/index.ts similarity index 55% rename from x-pack/legacy/plugins/watcher/server/lib/call_with_internal_user_factory/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/index.ts index a56a50e2864a5..3f5e1a91209ea 100644 --- a/x-pack/legacy/plugins/watcher/server/lib/call_with_internal_user_factory/index.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/index.ts @@ -3,5 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { PluginInitializerContext } from 'src/core/server'; +import { WatcherServerPlugin } from './plugin'; -export { callWithInternalUserFactory } from './call_with_internal_user_factory'; +export const plugin = (ctx: PluginInitializerContext) => new WatcherServerPlugin(); diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/call_with_request_factory.ts b/x-pack/legacy/plugins/watcher/server/np_ready/lib/call_with_request_factory.ts new file mode 100644 index 0000000000000..eaec9cd91b23c --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/lib/call_with_request_factory.ts @@ -0,0 +1,28 @@ +/* + * 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 { ElasticsearchServiceSetup } from 'src/core/server'; +import { once } from 'lodash'; +import { elasticsearchJsPlugin } from './elasticsearch_js_plugin'; + +const callWithRequest = once((elasticsearchService: ElasticsearchServiceSetup) => { + const config = { plugins: [elasticsearchJsPlugin] }; + return elasticsearchService.createClient('watcher', config); +}); + +export const callWithRequestFactory = ( + elasticsearchService: ElasticsearchServiceSetup, + request: any +) => { + return (...args: any[]) => { + return ( + callWithRequest(elasticsearchService) + .asScoped(request) + // @ts-ignore + .callAsCurrentUser(...args) + ); + }; +}; diff --git a/x-pack/legacy/plugins/watcher/server/lib/elasticsearch_js_plugin/elasticsearch_js_plugin.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/elasticsearch_js_plugin.ts similarity index 84% rename from x-pack/legacy/plugins/watcher/server/lib/elasticsearch_js_plugin/elasticsearch_js_plugin.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/elasticsearch_js_plugin.ts index 4e5353f311249..c592385f72a8a 100644 --- a/x-pack/legacy/plugins/watcher/server/lib/elasticsearch_js_plugin/elasticsearch_js_plugin.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/lib/elasticsearch_js_plugin.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -export const elasticsearchJsPlugin = (Client, config, components) => { // eslint-disable-line no-unused-vars +// eslint-disable-line no-unused-vars +export const elasticsearchJsPlugin = (Client: any, config: any, components: any) => { const ca = components.clientAction.factory; Client.prototype.watcher = components.clientAction.namespaceFactory(); @@ -21,19 +22,19 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint params: { masterTimeout: { name: 'master_timeout', - type: 'duration' - } + type: 'duration', + }, }, url: { fmt: '/_watcher/watch/<%=id%>/_deactivate', req: { id: { type: 'string', - required: true - } - } + required: true, + }, + }, }, - method: 'PUT' + method: 'PUT', }); /** @@ -47,19 +48,19 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint params: { masterTimeout: { name: 'master_timeout', - type: 'duration' - } + type: 'duration', + }, }, url: { fmt: '/_watcher/watch/<%=id%>/_activate', req: { id: { type: 'string', - required: true - } - } + required: true, + }, + }, }, - method: 'PUT' + method: 'PUT', }); /** @@ -74,23 +75,23 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint params: { masterTimeout: { name: 'master_timeout', - type: 'duration' - } + type: 'duration', + }, }, url: { fmt: '/_watcher/watch/<%=id%>/_ack/<%=action%>', req: { id: { type: 'string', - required: true + required: true, }, action: { type: 'string', - required: true - } - } + required: true, + }, + }, }, - method: 'POST' + method: 'POST', }); /** @@ -105,22 +106,22 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint params: { masterTimeout: { name: 'master_timeout', - type: 'duration' + type: 'duration', }, force: { - type: 'boolean' - } + type: 'boolean', + }, }, url: { fmt: '/_watcher/watch/<%=id%>', req: { id: { type: 'string', - required: true - } - } + required: true, + }, + }, }, - method: 'DELETE' + method: 'DELETE', }); /** @@ -132,14 +133,14 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint params: { masterTimeout: { name: 'master_timeout', - type: 'duration' - } + type: 'duration', + }, }, url: { - fmt: '/_watcher/watch/_execute' + fmt: '/_watcher/watch/_execute', }, needBody: true, - method: 'POST' + method: 'POST', }); /** @@ -155,10 +156,10 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint req: { id: { type: 'string', - required: true - } - } - } + required: true, + }, + }, + }, }); /** @@ -172,20 +173,20 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint params: { masterTimeout: { name: 'master_timeout', - type: 'duration' - } + type: 'duration', + }, }, url: { fmt: '/_watcher/watch/<%=id%>', req: { id: { type: 'string', - required: true - } - } + required: true, + }, + }, }, needBody: true, - method: 'PUT' + method: 'PUT', }); /** @@ -196,9 +197,9 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint watcher.restart = ca({ params: {}, url: { - fmt: '/_watcher/_restart' + fmt: '/_watcher/_restart', }, - method: 'PUT' + method: 'PUT', }); /** @@ -209,9 +210,9 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint watcher.start = ca({ params: {}, url: { - fmt: '/_watcher/_start' + fmt: '/_watcher/_start', }, - method: 'PUT' + method: 'PUT', }); /** @@ -222,8 +223,8 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint watcher.stats = ca({ params: {}, url: { - fmt: '/_watcher/stats' - } + fmt: '/_watcher/stats', + }, }); /** @@ -234,8 +235,8 @@ export const elasticsearchJsPlugin = (Client, config, components) => { // eslint watcher.stop = ca({ params: {}, url: { - fmt: '/_watcher/_stop' + fmt: '/_watcher/_stop', }, - method: 'PUT' + method: 'PUT', }); }; diff --git a/x-pack/legacy/plugins/watcher/server/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js diff --git a/x-pack/legacy/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts similarity index 64% rename from x-pack/legacy/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts index eb76d5d3731cf..d762b05f01d79 100644 --- a/x-pack/legacy/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts @@ -5,9 +5,9 @@ */ import { get } from 'lodash'; -import { ES_SCROLL_SETTINGS } from '../../../common/constants'; +import { ES_SCROLL_SETTINGS } from '../../../../common/constants'; -export function fetchAllFromScroll(response, callWithRequest, hits = []) { +export function fetchAllFromScroll(response: any, callWithRequest: any, hits: any[] = []) { const newHits = get(response, 'hits.hits', []); const scrollId = get(response, '_scroll_id'); @@ -17,12 +17,11 @@ export function fetchAllFromScroll(response, callWithRequest, hits = []) { return callWithRequest('scroll', { body: { scroll: ES_SCROLL_SETTINGS.KEEPALIVE, - scroll_id: scrollId - } - }) - .then(innerResponse => { - return fetchAllFromScroll(innerResponse, callWithRequest, hits); - }); + scroll_id: scrollId, + }, + }).then((innerResponse: any) => { + return fetchAllFromScroll(innerResponse, callWithRequest, hits); + }); } return Promise.resolve(hits); diff --git a/x-pack/legacy/plugins/watcher/server/lib/fetch_all_from_scroll/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/lib/fetch_all_from_scroll/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/lib/documentation_links/index.ts b/x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/index.ts similarity index 84% rename from x-pack/legacy/plugins/watcher/public/lib/documentation_links/index.ts rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/index.ts index 81e0c494e28b3..a9a3c61472d8c 100644 --- a/x-pack/legacy/plugins/watcher/public/lib/documentation_links/index.ts +++ b/x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export * from './documentation_links'; +export { isEsError } from './is_es_error'; diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/history/register_history_routes.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/is_es_error.ts similarity index 55% rename from x-pack/legacy/plugins/watcher/server/routes/api/history/register_history_routes.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/is_es_error.ts index bef26fbb9b267..4137293cf39c0 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/history/register_history_routes.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/is_es_error.ts @@ -4,8 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { registerLoadRoute } from './register_load_route'; +import * as legacyElasticsearch from 'elasticsearch'; -export function registerHistoryRoutes(server) { - registerLoadRoute(server); +const esErrorsParent = legacyElasticsearch.errors._Abstract; + +export function isEsError(err: Error) { + return err instanceof esErrorsParent; } diff --git a/x-pack/legacy/plugins/watcher/server/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js similarity index 71% rename from x-pack/legacy/plugins/watcher/server/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js index ed4a51a11b7cd..fc01e42e6fdf2 100644 --- a/x-pack/legacy/plugins/watcher/server/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js @@ -5,8 +5,9 @@ */ import expect from '@kbn/expect'; +import { kibanaResponseFactory } from '../../../../../../../../../src/core/server'; import { licensePreRoutingFactory } from '../license_pre_routing_factory'; -import { LICENSE_STATUS_VALID, LICENSE_STATUS_EXPIRED } from '../../../../../../common/constants/license_status'; +import { LICENSE_STATUS_VALID, LICENSE_STATUS_EXPIRED } from '../../../../../../../common/constants/license_status'; describe('license_pre_routing_factory', () => { describe('#reportingFeaturePreRoutingFactory', () => { @@ -27,13 +28,6 @@ describe('license_pre_routing_factory', () => { }; }); - it('only instantiates one instance per server', () => { - const firstInstance = licensePreRoutingFactory(mockServer); - const secondInstance = licensePreRoutingFactory(mockServer); - - expect(firstInstance).to.be(secondInstance); - }); - describe('status is not valid', () => { beforeEach(() => { mockLicenseCheckResults = { @@ -42,13 +36,10 @@ describe('license_pre_routing_factory', () => { }); it ('replies with 403', () => { - const licensePreRouting = licensePreRoutingFactory(mockServer); + const licensePreRouting = licensePreRoutingFactory(mockServer, () => {}); const stubRequest = {}; - expect(() => licensePreRouting(stubRequest)).to.throwException((response) => { - expect(response).to.be.an(Error); - expect(response.isBoom).to.be(true); - expect(response.output.statusCode).to.be(403); - }); + const response = licensePreRouting({}, stubRequest, kibanaResponseFactory); + expect(response.status).to.be(403); }); }); @@ -60,9 +51,9 @@ describe('license_pre_routing_factory', () => { }); it ('replies with nothing', () => { - const licensePreRouting = licensePreRoutingFactory(mockServer); + const licensePreRouting = licensePreRoutingFactory(mockServer, () => null); const stubRequest = {}; - const response = licensePreRouting(stubRequest); + const response = licensePreRouting({}, stubRequest, kibanaResponseFactory); expect(response).to.be(null); }); }); diff --git a/x-pack/legacy/plugins/watcher/server/lib/license_pre_routing_factory/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/lib/license_pre_routing_factory/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/license_pre_routing_factory.ts b/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/license_pre_routing_factory.ts new file mode 100644 index 0000000000000..d2f4967246104 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/license_pre_routing_factory.ts @@ -0,0 +1,43 @@ +/* + * 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 { + KibanaRequest, + KibanaResponseFactory, + RequestHandler, + RequestHandlerContext, +} from 'src/core/server'; +import { PLUGIN } from '../../../../common/constants'; +import { LICENSE_STATUS_VALID } from '../../../../../../common/constants/license_status'; +import { ServerShim } from '../../types'; + +export const licensePreRoutingFactory = ( + server: ServerShim, + handler: RequestHandler +): RequestHandler => { + const xpackMainPlugin = server.plugins.xpack_main; + + // License checking and enable/disable logic + return function licensePreRouting( + ctx: RequestHandlerContext, + request: KibanaRequest, + response: KibanaResponseFactory + ) { + const licenseCheckResults = xpackMainPlugin.info.feature(PLUGIN.ID).getLicenseCheckResults(); + const { status } = licenseCheckResults; + + if (status !== LICENSE_STATUS_VALID) { + return response.customError({ + body: { + message: licenseCheckResults.messsage, + }, + statusCode: 403, + }); + } + + return handler(ctx, request, response); + }; +}; diff --git a/x-pack/legacy/plugins/watcher/server/lib/normalized_field_types/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/lib/normalized_field_types/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/lib/normalized_field_types/normalized_field_types.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/normalized_field_types.ts similarity index 61% rename from x-pack/legacy/plugins/watcher/server/lib/normalized_field_types/normalized_field_types.js rename to x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/normalized_field_types.ts index 65f2867662bdd..39e82e7db8964 100644 --- a/x-pack/legacy/plugins/watcher/server/lib/normalized_field_types/normalized_field_types.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/normalized_field_types.ts @@ -5,12 +5,12 @@ */ export const normalizedFieldTypes = { - 'long': 'number', - 'integer': 'number', - 'short': 'number', - 'byte': 'number', - 'double': 'number', - 'float': 'number', - 'half_float': 'number', - 'scaled_float': 'number' + long: 'number', + integer: 'number', + short: 'number', + byte: 'number', + double: 'number', + float: 'number', + half_float: 'number', + scaled_float: 'number', }; diff --git a/x-pack/legacy/plugins/watcher/server/models/action_status/__tests__/action_status.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/__tests__/action_status.js similarity index 99% rename from x-pack/legacy/plugins/watcher/server/models/action_status/__tests__/action_status.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/__tests__/action_status.js index 456768c8c02ec..430669ab26c50 100644 --- a/x-pack/legacy/plugins/watcher/server/models/action_status/__tests__/action_status.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/__tests__/action_status.js @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { ActionStatus } from '../action_status'; -import { ACTION_STATES } from '../../../../common/constants'; +import { ACTION_STATES } from '../../../../../common/constants'; import moment from 'moment'; describe('action_status', () => { diff --git a/x-pack/legacy/plugins/watcher/server/models/action_status/action_status.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/action_status.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/models/action_status/action_status.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/action_status.js index eeedf9aefe5f6..7f724cf68211f 100644 --- a/x-pack/legacy/plugins/watcher/server/models/action_status/action_status.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/action_status.js @@ -6,8 +6,8 @@ import { get } from 'lodash'; import { badImplementation, badRequest } from 'boom'; -import { getMoment } from '../../../common/lib/get_moment'; -import { ACTION_STATES } from '../../../common/constants'; +import { getMoment } from '../../../../common/lib/get_moment'; +import { ACTION_STATES } from '../../../../common/constants'; import { i18n } from '@kbn/i18n'; export class ActionStatus { diff --git a/x-pack/legacy/plugins/watcher/server/models/action_status/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/action_status/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/execute_details/__tests__/execute_details.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/__tests__/execute_details.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/execute_details/__tests__/execute_details.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/__tests__/execute_details.js diff --git a/x-pack/legacy/plugins/watcher/server/models/execute_details/execute_details.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/execute_details.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/execute_details/execute_details.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/execute_details.js diff --git a/x-pack/legacy/plugins/watcher/server/models/execute_details/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/execute_details/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/fields/__tests__/fields.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/fields/__tests__/fields.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/fields/__tests__/fields.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/fields/__tests__/fields.js diff --git a/x-pack/legacy/plugins/watcher/server/models/fields/fields.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/fields/fields.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/fields/fields.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/fields/fields.js diff --git a/x-pack/legacy/plugins/watcher/server/models/fields/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/fields/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/fields/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/fields/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/settings/__tests__/settings.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/settings/__tests__/settings.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/settings/__tests__/settings.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/settings/__tests__/settings.js diff --git a/x-pack/legacy/plugins/watcher/server/models/settings/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/settings/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/settings/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/settings/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/settings/settings.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/settings/settings.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/models/settings/settings.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/settings/settings.js index 95a1db7533f41..55622117efedf 100644 --- a/x-pack/legacy/plugins/watcher/server/models/settings/settings.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/settings/settings.js @@ -5,7 +5,7 @@ */ import { merge } from 'lodash'; -import { ACTION_TYPES } from '../../../common/constants'; +import { ACTION_TYPES } from '../../../../common/constants'; function isEnabledByDefault(actionType) { switch (actionType) { diff --git a/x-pack/legacy/plugins/watcher/server/models/visualize_options/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/visualize_options/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/visualize_options/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/visualize_options/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/visualize_options/visualize_options.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/visualize_options/visualize_options.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/visualize_options/visualize_options.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/visualize_options/visualize_options.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/base_watch.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.js similarity index 98% rename from x-pack/legacy/plugins/watcher/server/models/watch/base_watch.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.js index f96274594872a..6a6df7d6f7f74 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/base_watch.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.js @@ -6,7 +6,7 @@ import { get, map, pick } from 'lodash'; import { badRequest } from 'boom'; -import { Action } from '../../../common/models/action'; +import { Action } from '../../../../common/models/action'; import { WatchStatus } from '../watch_status'; import { i18n } from '@kbn/i18n'; import { WatchErrors } from '../watch_errors'; diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/base_watch.test.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/base_watch.test.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.test.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/json_watch.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.js similarity index 93% rename from x-pack/legacy/plugins/watcher/server/models/watch/json_watch.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.js index e319cc1bc277b..0b011ca33a76b 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/json_watch.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.js @@ -6,8 +6,8 @@ import { isEmpty, cloneDeep, has, merge } from 'lodash'; import { BaseWatch } from './base_watch'; -import { WATCH_TYPES } from '../../../common/constants'; -import { serializeJsonWatch } from '../../../common/lib/serialization'; +import { WATCH_TYPES } from '../../../../common/constants'; +import { serializeJsonWatch } from '../../../../common/lib/serialization'; export class JsonWatch extends BaseWatch { // This constructor should not be used directly. diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/json_watch.test.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/json_watch.test.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.test.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/lib/get_watch_type/get_watch_type.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/get_watch_type.js similarity index 88% rename from x-pack/legacy/plugins/watcher/server/models/watch/lib/get_watch_type/get_watch_type.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/get_watch_type.js index 2bdd03e23c6dc..72c725eda2bd1 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/lib/get_watch_type/get_watch_type.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/get_watch_type.js @@ -5,7 +5,7 @@ */ import { get, contains, values } from 'lodash'; -import { WATCH_TYPES } from '../../../../../common/constants'; +import { WATCH_TYPES } from '../../../../../../common/constants'; export function getWatchType(watchJson) { const type = get(watchJson, 'metadata.xpack.type'); diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/lib/get_watch_type/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/lib/get_watch_type/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/monitoring_watch.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/models/watch/monitoring_watch.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.js index 977c62726a038..7f29d41b20fb3 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/monitoring_watch.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.js @@ -7,7 +7,7 @@ import { merge } from 'lodash'; import { badRequest } from 'boom'; import { BaseWatch } from './base_watch'; -import { WATCH_TYPES } from '../../../common/constants'; +import { WATCH_TYPES } from '../../../../common/constants'; import { i18n } from '@kbn/i18n'; export class MonitoringWatch extends BaseWatch { diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/monitoring_watch.test.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/monitoring_watch.test.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.test.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/__tests__/format_visualize_data.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/__tests__/format_visualize_data.js similarity index 99% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/__tests__/format_visualize_data.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/__tests__/format_visualize_data.js index 04239ab6e1b5f..a7524bcc7c4db 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/__tests__/format_visualize_data.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/__tests__/format_visualize_data.js @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect'; -import { AGG_TYPES } from '../../../../../common/constants'; +import { AGG_TYPES } from '../../../../../../common/constants'; import { formatVisualizeData } from '../format_visualize_data'; describe('watch', () => { diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/build_visualize_query.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/build_visualize_query.js similarity index 95% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/build_visualize_query.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/build_visualize_query.js index 8046a765be3f3..83cfcec52c064 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/build_visualize_query.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/build_visualize_query.js @@ -5,8 +5,8 @@ */ import { cloneDeep } from 'lodash'; -import { buildInput } from '../../../../common/lib/serialization'; -import { AGG_TYPES } from '../../../../common/constants'; +import { buildInput } from '../../../../../common/lib/serialization'; +import { AGG_TYPES } from '../../../../../common/constants'; /* input.search.request.body.query.bool.filter.range diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.query.date.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.query.date.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.query.date.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.query.date.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.query.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.query.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.query.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.query.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.query.date.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.query.date.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.query.date.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.query.date.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.query.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.query.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.query.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.query.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.query.date.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.query.date.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.query.date.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.query.date.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.query.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.query.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.query.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.query.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.query.date.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.query.date.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.query.date.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.query.date.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.query.json b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.query.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.query.json rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.query.json diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/format_visualize_data.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/format_visualize_data.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/format_visualize_data.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/format_visualize_data.js index 90cdc9464e8c5..19d41d2491cf5 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/format_visualize_data.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/format_visualize_data.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { AGG_TYPES } from '../../../../common/constants'; +import { AGG_TYPES } from '../../../../../common/constants'; export function formatVisualizeData({ aggType, termField }, results) { if (aggType === AGG_TYPES.COUNT && !Boolean(termField)) { diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.js index cb40c46ac6435..db662902d0f4d 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.js @@ -6,8 +6,8 @@ import { merge } from 'lodash'; import { BaseWatch } from '../base_watch'; -import { WATCH_TYPES, COMPARATORS, SORT_ORDERS } from '../../../../common/constants'; -import { serializeThresholdWatch } from '../../../../common/lib/serialization'; +import { WATCH_TYPES, COMPARATORS, SORT_ORDERS } from '../../../../../common/constants'; +import { serializeThresholdWatch } from '../../../../../common/lib/serialization'; import { buildVisualizeQuery } from './build_visualize_query'; import { formatVisualizeData } from './format_visualize_data'; diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.test.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.test.js similarity index 99% rename from x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.test.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.test.js index 4a0b7b657bbc6..6226a702d7f3c 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.test.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.test.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { COMPARATORS, SORT_ORDERS } from '../../../../common/constants'; +import { COMPARATORS, SORT_ORDERS } from '../../../../../common/constants'; import { WatchErrors } from '../../watch_errors'; import { ThresholdWatch } from './threshold_watch'; diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/watch.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/models/watch/watch.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.js index c75afc62c4c4b..10b021dcbedf6 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/watch.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.js @@ -6,7 +6,7 @@ import { set } from 'lodash'; import { badRequest } from 'boom'; -import { WATCH_TYPES } from '../../../common/constants'; +import { WATCH_TYPES } from '../../../../common/constants'; import { JsonWatch } from './json_watch'; import { MonitoringWatch } from './monitoring_watch'; import { ThresholdWatch } from './threshold_watch'; diff --git a/x-pack/legacy/plugins/watcher/server/models/watch/watch.test.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.test.js similarity index 98% rename from x-pack/legacy/plugins/watcher/server/models/watch/watch.test.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.test.js index 2895c23083def..c419c28561730 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch/watch.test.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.test.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { WATCH_TYPES } from '../../../common/constants'; +import { WATCH_TYPES } from '../../../../common/constants'; import { Watch } from './watch'; import { JsonWatch } from './json_watch'; import { MonitoringWatch } from './monitoring_watch'; diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_errors/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch_errors/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_errors/watch_errors.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/watch_errors.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch_errors/watch_errors.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/watch_errors.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_errors/watch_errors.test.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/watch_errors.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch_errors/watch_errors.test.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/watch_errors.test.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_history_item/__tests__/watch_history_item.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/__tests__/watch_history_item.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch_history_item/__tests__/watch_history_item.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/__tests__/watch_history_item.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_history_item/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch_history_item/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_history_item/watch_history_item.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/watch_history_item.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/models/watch_history_item/watch_history_item.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/watch_history_item.js index 617f758571742..5172e590fc63e 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch_history_item/watch_history_item.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/watch_history_item.js @@ -5,7 +5,7 @@ */ import { badRequest } from 'boom'; -import { getMoment } from '../../../common/lib/get_moment'; +import { getMoment } from '../../../../common/lib/get_moment'; import { get, cloneDeep } from 'lodash'; import { WatchStatus } from '../watch_status'; import { i18n } from '@kbn/i18n'; diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_status/__tests__/watch_status.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/__tests__/watch_status.js similarity index 99% rename from x-pack/legacy/plugins/watcher/server/models/watch_status/__tests__/watch_status.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/__tests__/watch_status.js index e29c8dd2a529e..9a045fa4b5a7f 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch_status/__tests__/watch_status.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/__tests__/watch_status.js @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { WatchStatus } from '../watch_status'; -import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../../../../common/constants'; +import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../../../../../common/constants'; import moment from 'moment'; describe('watch_status', () => { diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_status/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/models/watch_status/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/index.js diff --git a/x-pack/legacy/plugins/watcher/server/models/watch_status/watch_status.js b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/watch_status.js similarity index 98% rename from x-pack/legacy/plugins/watcher/server/models/watch_status/watch_status.js rename to x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/watch_status.js index b7cffe16ca0bc..1e3d1d3064cb4 100644 --- a/x-pack/legacy/plugins/watcher/server/models/watch_status/watch_status.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/watch_status.js @@ -6,9 +6,9 @@ import { get, map, forEach, max } from 'lodash'; import { badRequest } from 'boom'; -import { getMoment } from '../../../common/lib/get_moment'; +import { getMoment } from '../../../../common/lib/get_moment'; import { ActionStatus } from '../action_status'; -import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../../../common/constants'; +import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../../../../common/constants'; import { i18n } from '@kbn/i18n'; function getActionStatusTotals(watchStatus) { diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/plugin.ts b/x-pack/legacy/plugins/watcher/server/np_ready/plugin.ts new file mode 100644 index 0000000000000..2e8c81efa19c0 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/plugin.ts @@ -0,0 +1,51 @@ +/* + * 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 { first } from 'rxjs/operators'; +import { Plugin, CoreSetup } from 'src/core/server'; +import { i18n } from '@kbn/i18n'; +import { PLUGIN } from '../../common/constants'; +import { ServerShim, RouteDependencies } from './types'; + +import { registerLicenseChecker } from '../../../../server/lib/register_license_checker'; +import { registerSettingsRoutes } from './routes/api/settings'; +import { registerIndicesRoutes } from './routes/api/indices'; +import { registerLicenseRoutes } from './routes/api/license'; +import { registerWatchesRoutes } from './routes/api/watches'; +import { registerWatchRoutes } from './routes/api/watch'; +import { registerListFieldsRoute } from './routes/api/register_list_fields_route'; +import { registerLoadHistoryRoute } from './routes/api/register_load_history_route'; + +export class WatcherServerPlugin implements Plugin { + async setup( + { http, elasticsearch: elasticsearchService }: CoreSetup, + { __LEGACY: serverShim }: { __LEGACY: ServerShim } + ) { + const elasticsearch = await elasticsearchService.adminClient$.pipe(first()).toPromise(); + const router = http.createRouter(); + const routeDependencies: RouteDependencies = { + elasticsearch, + elasticsearchService, + router, + }; + // Register license checker + registerLicenseChecker( + serverShim as any, + PLUGIN.ID, + PLUGIN.getI18nName(i18n), + PLUGIN.MINIMUM_LICENSE_REQUIRED + ); + + registerListFieldsRoute(routeDependencies, serverShim); + registerLoadHistoryRoute(routeDependencies, serverShim); + registerIndicesRoutes(routeDependencies, serverShim); + registerLicenseRoutes(routeDependencies, serverShim); + registerSettingsRoutes(routeDependencies, serverShim); + registerWatchesRoutes(routeDependencies, serverShim); + registerWatchRoutes(routeDependencies, serverShim); + } + start() {} + stop() {} +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/indices/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/routes/api/indices/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_get_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_get_route.ts new file mode 100644 index 0000000000000..6b6b643dc4adf --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_get_route.ts @@ -0,0 +1,92 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { reduce, size } from 'lodash'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; + +function getIndexNamesFromAliasesResponse(json: Record) { + return reduce( + json, + (list, { aliases }, indexName) => { + list.push(indexName); + if (size(aliases) > 0) { + list.push(...Object.keys(aliases)); + } + return list; + }, + [] as string[] + ); +} + +function getIndices(callWithRequest: any, pattern: string, limit = 10) { + return callWithRequest('indices.getAlias', { + index: pattern, + ignore: [404], + }).then((aliasResult: any) => { + if (aliasResult.status !== 404) { + const indicesFromAliasResponse = getIndexNamesFromAliasesResponse(aliasResult); + return indicesFromAliasResponse.slice(0, limit); + } + + const params = { + index: pattern, + ignore: [404], + body: { + size: 0, // no hits + aggs: { + indices: { + terms: { + field: '_index', + size: limit, + }, + }, + }, + }, + }; + + return callWithRequest('search', params).then((response: any) => { + if (response.status === 404 || !response.aggregations) { + return []; + } + return response.aggregations.indices.buckets.map((bucket: any) => bucket.key); + }); + }); +} + +export function registerGetRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + const { pattern } = request.body; + + try { + const indices = await getIndices(callWithRequest, pattern); + return response.ok({ body: { indices } }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ statusCode: e.statusCode, body: e }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.post( + { + path: '/api/watcher/indices', + validate: { + body: schema.object({}, { allowUnknowns: true }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/indices/register_indices_routes.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_indices_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/routes/api/indices/register_indices_routes.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_indices_routes.ts index 41b2f8dba7a1f..647a85c311532 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/indices/register_indices_routes.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_indices_routes.ts @@ -5,7 +5,8 @@ */ import { registerGetRoute } from './register_get_route'; +import { RouteDependencies, ServerShim } from '../../../types'; -export function registerIndicesRoutes(server) { - registerGetRoute(server); +export function registerIndicesRoutes(deps: RouteDependencies, legacy: ServerShim) { + registerGetRoute(deps, legacy); } diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/license/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/routes/api/license/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/license/register_license_routes.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_license_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/routes/api/license/register_license_routes.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_license_routes.ts index fe890719a0a7d..c5965d9315b01 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/license/register_license_routes.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_license_routes.ts @@ -5,7 +5,8 @@ */ import { registerRefreshRoute } from './register_refresh_route'; +import { RouteDependencies, ServerShim } from '../../../types'; -export function registerLicenseRoutes(server) { - registerRefreshRoute(server); +export function registerLicenseRoutes(deps: RouteDependencies, legacy: ServerShim) { + registerRefreshRoute(deps, legacy); } diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/license/register_refresh_route.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_refresh_route.ts similarity index 50% rename from x-pack/legacy/plugins/watcher/server/routes/api/license/register_refresh_route.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_refresh_route.ts index cbd5dc7f6631f..08f1f26a84a4f 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/license/register_refresh_route.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_refresh_route.ts @@ -4,7 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; +import { RequestHandler } from 'src/core/server'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; /* In order for the client to have the most up-to-date snapshot of the current license, @@ -12,17 +14,16 @@ it needs to make a round-trip to the kibana server. This refresh endpoint is pro for when the client needs to check the license, but doesn't need to pull data from the server for any reason, i.e., when adding a new watch. */ -export function registerRefreshRoute(server) { - const licensePreRouting = licensePreRoutingFactory(server); +export function registerRefreshRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = (ctx, request, response) => { + return response.ok({ body: { success: true } }); + }; - server.route({ - path: '/api/watcher/license/refresh', - method: 'GET', - handler: () => { - return { success: true }; + deps.router.get( + { + path: '/api/watcher/license/refresh', + validate: false, }, - config: { - pre: [ licensePreRouting ] - } - }); + licensePreRoutingFactory(legacy, handler) + ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_list_fields_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_list_fields_route.ts new file mode 100644 index 0000000000000..f3222d24f0adf --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_list_fields_route.ts @@ -0,0 +1,65 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { callWithRequestFactory } from '../../lib/call_with_request_factory'; +import { isEsError } from '../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../lib/license_pre_routing_factory'; +// @ts-ignore +import { Fields } from '../../models/fields'; +import { RouteDependencies, ServerShim } from '../../types'; + +function fetchFields(callWithRequest: any, indexes: string[]) { + const params = { + index: indexes, + fields: ['*'], + ignoreUnavailable: true, + allowNoIndices: true, + ignore: 404, + }; + + return callWithRequest('fieldCaps', params); +} + +export function registerListFieldsRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + const { indexes } = request.body; + + try { + const fieldsResponse = await fetchFields(callWithRequest, indexes); + const json = fieldsResponse.status === 404 ? { fields: [] } : fieldsResponse; + const fields = Fields.fromUpstreamJson(json); + return response.ok({ body: fields.downstreamJson }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ + statusCode: e.statusCode, + body: { + message: e.message, + }, + }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.post( + { + path: '/api/watcher/fields', + validate: { + body: schema.object({ + indexes: schema.arrayOf(schema.string()), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_load_history_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_load_history_route.ts new file mode 100644 index 0000000000000..d62e4f48c5629 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_load_history_route.ts @@ -0,0 +1,77 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { get } from 'lodash'; +import { RequestHandler } from 'src/core/server'; +import { callWithRequestFactory } from '../../lib/call_with_request_factory'; +import { isEsError } from '../../lib/is_es_error'; +import { INDEX_NAMES } from '../../../../common/constants'; +import { licensePreRoutingFactory } from '../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../types'; +// @ts-ignore +import { WatchHistoryItem } from '../../models/watch_history_item'; + +function fetchHistoryItem(callWithRequest: any, watchHistoryItemId: string) { + return callWithRequest('search', { + index: INDEX_NAMES.WATCHER_HISTORY, + body: { + query: { + bool: { + must: [{ term: { _id: watchHistoryItemId } }], + }, + }, + }, + }); +} + +export function registerLoadHistoryRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + const id = request.params.id; + + try { + const responseFromES = await fetchHistoryItem(callWithRequest, id); + const hit = get(responseFromES, 'hits.hits[0]'); + if (!hit) { + return response.notFound({ body: `Watch History Item with id = ${id} not found` }); + } + const watchHistoryItemJson = get(hit, '_source'); + const watchId = get(hit, '_source.watch_id'); + const json = { + id, + watchId, + watchHistoryItemJson, + includeDetails: true, + }; + + const watchHistoryItem = WatchHistoryItem.fromUpstreamJson(json); + return response.ok({ + body: { watchHistoryItem: watchHistoryItem.downstreamJson }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ statusCode: e.statusCode, body: e }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.get( + { + path: '/api/watcher/history/{id}', + validate: { + params: schema.object({ + id: schema.string(), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/settings/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/routes/api/settings/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_load_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_load_route.ts new file mode 100644 index 0000000000000..710d079d810da --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_load_route.ts @@ -0,0 +1,43 @@ +/* + * 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 { IClusterClient, RequestHandler } from 'src/core/server'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +// @ts-ignore +import { Settings } from '../../../models/settings'; +import { RouteDependencies, ServerShim } from '../../../types'; + +function fetchClusterSettings(client: IClusterClient) { + return client.callAsInternalUser('cluster.getSettings', { + includeDefaults: true, + filterPath: '**.xpack.notification', + }); +} + +export function registerLoadRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + try { + const settings = await fetchClusterSettings(deps.elasticsearch); + return response.ok({ body: Settings.fromUpstreamJson(settings).downstreamJson }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ statusCode: e.statusCode, body: e }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + deps.router.get( + { + path: '/api/watcher/settings', + validate: false, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/settings/register_settings_routes.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_settings_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/routes/api/settings/register_settings_routes.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_settings_routes.ts index eefb320e9b1d9..0b24ec0e90bd4 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/settings/register_settings_routes.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_settings_routes.ts @@ -5,7 +5,8 @@ */ import { registerLoadRoute } from './register_load_route'; +import { RouteDependencies, ServerShim } from '../../../types'; -export function registerSettingsRoutes(server) { - registerLoadRoute(server); +export function registerSettingsRoutes(deps: RouteDependencies, legacy: ServerShim) { + registerLoadRoute(deps, legacy); } diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/action/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/routes/api/watch/action/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_acknowledge_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_acknowledge_route.ts new file mode 100644 index 0000000000000..d0cc0a27e87ff --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_acknowledge_route.ts @@ -0,0 +1,65 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { get } from 'lodash'; +import { RequestHandler } from 'src/core/server'; +import { callWithRequestFactory } from '../../../../lib/call_with_request_factory'; +import { isEsError } from '../../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../../lib/license_pre_routing_factory'; +// @ts-ignore +import { WatchStatus } from '../../../../models/watch_status'; +import { RouteDependencies, ServerShim } from '../../../../types'; + +function acknowledgeAction(callWithRequest: any, watchId: string, actionId: string) { + return callWithRequest('watcher.ackWatch', { + id: watchId, + action: actionId, + }); +} + +export function registerAcknowledgeRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + const { watchId, actionId } = request.params; + + try { + const hit = await acknowledgeAction(callWithRequest, watchId, actionId); + const watchStatusJson = get(hit, 'status'); + const json = { + id: watchId, + watchStatusJson, + }; + + const watchStatus = WatchStatus.fromUpstreamJson(json); + return response.ok({ + body: { watchStatus: watchStatus.downstreamJson }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + const body = e.statusCode === 404 ? `Watch with id = ${watchId} not found` : e; + return response.customError({ statusCode: e.statusCode, body }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.put( + { + path: '/api/watcher/watch/{watchId}/action/{actionId}/acknowledge', + validate: { + params: schema.object({ + watchId: schema.string(), + actionId: schema.string(), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/action/register_action_routes.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_action_routes.ts similarity index 61% rename from x-pack/legacy/plugins/watcher/server/routes/api/watch/action/register_action_routes.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_action_routes.ts index 6f2c86664420b..022c844867938 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/action/register_action_routes.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_action_routes.ts @@ -5,7 +5,8 @@ */ import { registerAcknowledgeRoute } from './register_acknowledge_route'; +import { RouteDependencies, ServerShim } from '../../../../types'; -export function registerActionRoutes(server) { - registerAcknowledgeRoute(server); +export function registerActionRoutes(server: RouteDependencies, legacy: ServerShim) { + registerAcknowledgeRoute(server, legacy); } diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/routes/api/watch/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_activate_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_activate_route.ts new file mode 100644 index 0000000000000..28c482124aaee --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_activate_route.ts @@ -0,0 +1,66 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { get } from 'lodash'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; +// @ts-ignore +import { WatchStatus } from '../../../models/watch_status'; + +function activateWatch(callWithRequest: any, watchId: string) { + return callWithRequest('watcher.activateWatch', { + id: watchId, + }); +} + +export function registerActivateRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + + const { watchId } = request.params; + + try { + const hit = await activateWatch(callWithRequest, watchId); + const watchStatusJson = get(hit, 'status'); + const json = { + id: watchId, + watchStatusJson, + }; + + const watchStatus = WatchStatus.fromUpstreamJson(json); + return response.ok({ + body: { + watchStatus: watchStatus.downstreamJson, + }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + const body = e.statusCode === 404 ? `Watch with id = ${watchId} not found` : e; + return response.customError({ statusCode: e.statusCode, body }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.put( + { + path: '/api/watcher/watch/{watchId}/activate', + validate: { + params: schema.object({ + watchId: schema.string(), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_deactivate_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_deactivate_route.ts new file mode 100644 index 0000000000000..ac87066379a20 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_deactivate_route.ts @@ -0,0 +1,65 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { get } from 'lodash'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; +// @ts-ignore +import { WatchStatus } from '../../../models/watch_status'; + +function deactivateWatch(callWithRequest: any, watchId: string) { + return callWithRequest('watcher.deactivateWatch', { + id: watchId, + }); +} + +export function registerDeactivateRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + + const { watchId } = request.params; + + try { + const hit = await deactivateWatch(callWithRequest, watchId); + const watchStatusJson = get(hit, 'status'); + const json = { + id: watchId, + watchStatusJson, + }; + + const watchStatus = WatchStatus.fromUpstreamJson(json); + return response.ok({ + body: { + watchStatus: watchStatus.downstreamJson, + }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + const body = e.statusCode === 404 ? `Watch with id = ${watchId} not found` : e; + return response.customError({ statusCode: e.statusCode, body }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.put( + { + path: '/api/watcher/watch/{watchId}/deactivate', + validate: { + params: schema.object({ + watchId: schema.string(), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_delete_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_delete_route.ts new file mode 100644 index 0000000000000..3402cc283dba0 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_delete_route.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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; + +function deleteWatch(callWithRequest: any, watchId: string) { + return callWithRequest('watcher.deleteWatch', { + id: watchId, + }); +} + +export function registerDeleteRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + + const { watchId } = request.params; + + try { + await deleteWatch(callWithRequest, watchId); + return response.noContent(); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + const body = e.statusCode === 404 ? `Watch with id = ${watchId} not found` : e; + return response.customError({ statusCode: e.statusCode, body }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.delete( + { + path: '/api/watcher/watch/{watchId}', + validate: { + params: schema.object({ + watchId: schema.string(), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_execute_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_execute_route.ts new file mode 100644 index 0000000000000..f3bce228653fe --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_execute_route.ts @@ -0,0 +1,78 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { get } from 'lodash'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; + +import { RouteDependencies, ServerShim } from '../../../types'; +// @ts-ignore +import { ExecuteDetails } from '../../../models/execute_details'; +// @ts-ignore +import { Watch } from '../../../models/watch'; +// @ts-ignore +import { WatchHistoryItem } from '../../../models/watch_history_item'; + +function executeWatch(callWithRequest: any, executeDetails: any, watchJson: any) { + const body = executeDetails; + body.watch = watchJson; + + return callWithRequest('watcher.executeWatch', { + body, + }); +} + +export function registerExecuteRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + const executeDetails = ExecuteDetails.fromDownstreamJson(request.body.executeDetails); + const watch = Watch.fromDownstreamJson(request.body.watch); + + try { + const hit = await executeWatch(callWithRequest, executeDetails.upstreamJson, watch.watchJson); + const id = get(hit, '_id'); + const watchHistoryItemJson = get(hit, 'watch_record'); + const watchId = get(hit, 'watch_record.watch_id'); + const json = { + id, + watchId, + watchHistoryItemJson, + includeDetails: true, + }; + + const watchHistoryItem = WatchHistoryItem.fromUpstreamJson(json); + return response.ok({ + body: { + watchHistoryItem: watchHistoryItem.downstreamJson, + }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ statusCode: e.statusCode, body: e }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.put( + { + path: '/api/watcher/watch/execute', + validate: { + body: schema.object({ + executeDetails: schema.object({}, { allowUnknowns: true }), + watch: schema.object({}, { allowUnknowns: true }), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_history_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_history_route.ts new file mode 100644 index 0000000000000..e236d7dd642a3 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_history_route.ts @@ -0,0 +1,97 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { get } from 'lodash'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { fetchAllFromScroll } from '../../../lib/fetch_all_from_scroll'; +import { INDEX_NAMES, ES_SCROLL_SETTINGS } from '../../../../../common/constants'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; +// @ts-ignore +import { WatchHistoryItem } from '../../../models/watch_history_item'; + +function fetchHistoryItems(callWithRequest: any, watchId: any, startTime: any) { + const params: any = { + index: INDEX_NAMES.WATCHER_HISTORY, + scroll: ES_SCROLL_SETTINGS.KEEPALIVE, + body: { + size: ES_SCROLL_SETTINGS.PAGE_SIZE, + sort: [{ 'result.execution_time': 'desc' }], + query: { + bool: { + must: [{ term: { watch_id: watchId } }], + }, + }, + }, + }; + + // Add time range clause to query if startTime is specified + if (startTime !== 'all') { + const timeRangeQuery = { range: { 'result.execution_time': { gte: startTime } } }; + params.body.query.bool.must.push(timeRangeQuery); + } + + return callWithRequest('search', params).then((response: any) => + fetchAllFromScroll(response, callWithRequest) + ); +} + +export function registerHistoryRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + const { watchId } = request.params; + const { startTime } = request.query; + + try { + const hits = await fetchHistoryItems(callWithRequest, watchId, startTime); + const watchHistoryItems = hits.map((hit: any) => { + const id = get(hit, '_id'); + const watchHistoryItemJson = get(hit, '_source'); + + const opts = { includeDetails: false }; + return WatchHistoryItem.fromUpstreamJson( + { + id, + watchId, + watchHistoryItemJson, + }, + opts + ); + }); + + return response.ok({ + body: { + watchHistoryItems: watchHistoryItems.map( + (watchHistoryItem: any) => watchHistoryItem.downstreamJson + ), + }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ statusCode: e.statusCode, body: e }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.get( + { + path: '/api/watcher/watch/{watchId}/history', + validate: { + params: schema.object({ + watchId: schema.string(), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_load_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_load_route.ts new file mode 100644 index 0000000000000..7311ad08f73a6 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_load_route.ts @@ -0,0 +1,69 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { get } from 'lodash'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +// @ts-ignore +import { Watch } from '../../../models/watch'; +import { RouteDependencies, ServerShim } from '../../../types'; + +function fetchWatch(callWithRequest: any, watchId: string) { + return callWithRequest('watcher.getWatch', { + id: watchId, + }); +} + +export function registerLoadRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + + const id = request.params.id; + + try { + const hit = await fetchWatch(callWithRequest, id); + const watchJson = get(hit, 'watch'); + const watchStatusJson = get(hit, 'status'); + const json = { + id, + watchJson, + watchStatusJson, + }; + + const watch = Watch.fromUpstreamJson(json, { + throwExceptions: { + Action: false, + }, + }); + return response.ok({ + body: { watch: watch.downstreamJson }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + const body = e.statusCode === 404 ? `Watch with id = ${id} not found` : e; + return response.customError({ statusCode: e.statusCode, body }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + deps.router.get( + { + path: '/api/watcher/watch/{id}', + validate: { + params: schema.object({ + id: schema.string(), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_save_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_save_route.ts new file mode 100644 index 0000000000000..5d22392d49ed8 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_save_route.ts @@ -0,0 +1,104 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { i18n } from '@kbn/i18n'; +import { WATCH_TYPES } from '../../../../../common/constants'; +import { + serializeJsonWatch, + serializeThresholdWatch, +} from '../../../../../common/lib/serialization'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; + +function fetchWatch(callWithRequest: any, watchId: string) { + return callWithRequest('watcher.getWatch', { + id: watchId, + }); +} + +function saveWatch(callWithRequest: any, id: string, body: any) { + return callWithRequest('watcher.putWatch', { + id, + body, + }); +} + +export function registerSaveRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + const { id } = request.params; + const { type, isNew, ...watchConfig } = request.body; + + // For new watches, verify watch with the same ID doesn't already exist + if (isNew) { + try { + const existingWatch = await fetchWatch(callWithRequest, id); + if (existingWatch.found) { + return response.conflict({ + body: { + message: i18n.translate('xpack.watcher.saveRoute.duplicateWatchIdErrorMessage', { + defaultMessage: "There is already a watch with ID '{watchId}'.", + values: { + watchId: id, + }, + }), + }, + }); + } + } catch (e) { + const es404 = isEsError(e) && e.statusCode === 404; + if (!es404) { + return response.internalError({ body: e }); + } + // Else continue... + } + } + + let serializedWatch; + + switch (type) { + case WATCH_TYPES.JSON: + const { name, watch } = watchConfig; + serializedWatch = serializeJsonWatch(name, watch); + break; + + case WATCH_TYPES.THRESHOLD: + serializedWatch = serializeThresholdWatch(watchConfig); + break; + } + + try { + // Create new watch + await saveWatch(callWithRequest, id, serializedWatch); + return response.noContent(); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ statusCode: e.statusCode, body: e }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.put( + { + path: '/api/watcher/watch/{id}', + validate: { + params: schema.object({ + id: schema.string(), + }), + body: schema.object({}, { allowUnknowns: true }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_visualize_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_visualize_route.ts new file mode 100644 index 0000000000000..d07a264b0b2b1 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_visualize_route.ts @@ -0,0 +1,70 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; + +// @ts-ignore +import { Watch } from '../../../models/watch'; +// @ts-ignore +import { VisualizeOptions } from '../../../models/visualize_options'; + +function fetchVisualizeData(callWithRequest: any, index: any, body: any) { + const params = { + index, + body, + ignoreUnavailable: true, + allowNoIndices: true, + ignore: [404], + }; + + return callWithRequest('search', params); +} + +export function registerVisualizeRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + const watch = Watch.fromDownstreamJson(request.body.watch); + const options = VisualizeOptions.fromDownstreamJson(request.body.options); + const body = watch.getVisualizeQuery(options); + + try { + const hits = await fetchVisualizeData(callWithRequest, watch.index, body); + const visualizeData = watch.formatVisualizeData(hits); + + return response.ok({ + body: { + visualizeData, + }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ statusCode: e.statusCode, body: e }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.post( + { + path: '/api/watcher/watch/visualize', + validate: { + body: schema.object({ + watch: schema.object({}, { allowUnknowns: true }), + options: schema.object({}, { allowUnknowns: true }), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_watch_routes.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_watch_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/routes/api/watch/register_watch_routes.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_watch_routes.ts index 8419f6db7f659..5ecbf3e0d2b46 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_watch_routes.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_watch_routes.ts @@ -13,15 +13,16 @@ import { registerActivateRoute } from './register_activate_route'; import { registerDeactivateRoute } from './register_deactivate_route'; import { registerVisualizeRoute } from './register_visualize_route'; import { registerActionRoutes } from './action'; +import { RouteDependencies, ServerShim } from '../../../types'; -export function registerWatchRoutes(server) { - registerDeleteRoute(server); - registerExecuteRoute(server); - registerLoadRoute(server); - registerSaveRoute(server); - registerHistoryRoute(server); - registerActivateRoute(server); - registerDeactivateRoute(server); - registerActionRoutes(server); - registerVisualizeRoute(server); +export function registerWatchRoutes(deps: RouteDependencies, legacy: ServerShim) { + registerDeleteRoute(deps, legacy); + registerExecuteRoute(deps, legacy); + registerLoadRoute(deps, legacy); + registerSaveRoute(deps, legacy); + registerHistoryRoute(deps, legacy); + registerActivateRoute(deps, legacy); + registerDeactivateRoute(deps, legacy); + registerActionRoutes(deps, legacy); + registerVisualizeRoute(deps, legacy); } diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watches/index.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/routes/api/watches/index.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_delete_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_delete_route.ts new file mode 100644 index 0000000000000..29c539a0de138 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_delete_route.ts @@ -0,0 +1,63 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { RequestHandler } from 'src/core/server'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; + +function deleteWatches(callWithRequest: any, watchIds: string[]) { + const deletePromises = watchIds.map(watchId => { + return callWithRequest('watcher.deleteWatch', { + id: watchId, + }) + .then((success: Array<{ _id: string }>) => ({ success })) + .catch((error: Array<{ _id: string }>) => ({ error })); + }); + + return Promise.all(deletePromises).then(results => { + const errors: Error[] = []; + const successes: boolean[] = []; + results.forEach(({ success, error }) => { + if (success) { + successes.push(success._id); + } else if (error) { + errors.push(error._id); + } + }); + + return { + successes, + errors, + }; + }); +} + +export function registerDeleteRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + + try { + const results = await deleteWatches(callWithRequest, request.body.watchIds); + return response.ok({ body: { results } }); + } catch (e) { + return response.internalError({ body: e }); + } + }; + + deps.router.post( + { + path: '/api/watcher/watches/delete', + validate: { + body: schema.object({ + watchIds: schema.arrayOf(schema.string()), + }), + }, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_list_route.ts b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_list_route.ts new file mode 100644 index 0000000000000..b94c29e0f9892 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_list_route.ts @@ -0,0 +1,86 @@ +/* + * 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 { RequestHandler } from 'src/core/server'; +import { get } from 'lodash'; +import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { fetchAllFromScroll } from '../../../lib/fetch_all_from_scroll'; +import { INDEX_NAMES, ES_SCROLL_SETTINGS } from '../../../../../common/constants'; +import { isEsError } from '../../../lib/is_es_error'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; +import { RouteDependencies, ServerShim } from '../../../types'; +// @ts-ignore +import { Watch } from '../../../models/watch'; + +function fetchWatches(callWithRequest: any) { + const params = { + index: INDEX_NAMES.WATCHES, + scroll: ES_SCROLL_SETTINGS.KEEPALIVE, + body: { + size: ES_SCROLL_SETTINGS.PAGE_SIZE, + }, + ignore: [404], + }; + + return callWithRequest('search', params).then((response: any) => + fetchAllFromScroll(response, callWithRequest) + ); +} + +export function registerListRoute(deps: RouteDependencies, legacy: ServerShim) { + const handler: RequestHandler = async (ctx, request, response) => { + const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); + + try { + const hits = await fetchWatches(callWithRequest); + const watches = hits.map((hit: any) => { + const id = get(hit, '_id'); + const watchJson = get(hit, '_source'); + const watchStatusJson = get(hit, '_source.status'); + + return Watch.fromUpstreamJson( + { + id, + watchJson, + watchStatusJson, + }, + { + throwExceptions: { + Action: false, + }, + } + ); + }); + + return response.ok({ + body: { + watches: watches.map((watch: any) => watch.downstreamJson), + }, + }); + } catch (e) { + // Case: Error from Elasticsearch JS client + if (isEsError(e)) { + return response.customError({ + statusCode: e.statusCode, + body: { + message: e.message, + }, + }); + } + + // Case: default + return response.internalError({ body: e }); + } + }; + + deps.router.get( + { + path: '/api/watcher/watches', + validate: false, + }, + licensePreRoutingFactory(legacy, handler) + ); +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watches/register_watches_routes.js b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_watches_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/routes/api/watches/register_watches_routes.js rename to x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_watches_routes.ts index 5f7ae6a5935bd..dd5f55078e591 100644 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watches/register_watches_routes.js +++ b/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_watches_routes.ts @@ -6,8 +6,9 @@ import { registerListRoute } from './register_list_route'; import { registerDeleteRoute } from './register_delete_route'; +import { RouteDependencies, ServerShim } from '../../../types'; -export function registerWatchesRoutes(server) { - registerListRoute(server); - registerDeleteRoute(server); +export function registerWatchesRoutes(deps: RouteDependencies, legacy: ServerShim) { + registerListRoute(deps, legacy); + registerDeleteRoute(deps, legacy); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/types.ts b/x-pack/legacy/plugins/watcher/server/np_ready/types.ts new file mode 100644 index 0000000000000..1b566332befdf --- /dev/null +++ b/x-pack/legacy/plugins/watcher/server/np_ready/types.ts @@ -0,0 +1,22 @@ +/* + * 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 { IRouter, ElasticsearchServiceSetup, IClusterClient } from 'src/core/server'; +import { XPackMainPlugin } from '../../../xpack_main/xpack_main'; + +export interface ServerShim { + route: any; + plugins: { + xpack_main: XPackMainPlugin; + watcher: any; + }; +} + +export interface RouteDependencies { + router: IRouter; + elasticsearchService: ElasticsearchServiceSetup; + elasticsearch: IClusterClient; +} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/fields/register_list_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/fields/register_list_route.js deleted file mode 100644 index 7d45d3a2aa60b..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/fields/register_list_route.js +++ /dev/null @@ -1,60 +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 { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { Fields } from '../../../models/fields'; - -function fetchFields(callWithRequest, indexes) { - const params = { - index: indexes, - fields: ['*'], - ignoreUnavailable: true, - allowNoIndices: true, - ignore: 404 - }; - - return callWithRequest('fieldCaps', params); -} - -export function registerListRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/fields', - method: 'POST', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - const { indexes } = request.payload; - - return fetchFields(callWithRequest, indexes) - .then(response => { - const json = (response.status === 404) - ? { fields: [] } - : response; - - const fields = Fields.fromUpstreamJson(json); - - return fields.downstreamJson; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/history/index.js b/x-pack/legacy/plugins/watcher/server/routes/api/history/index.js deleted file mode 100644 index 9a66353c742bc..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/history/index.js +++ /dev/null @@ -1,7 +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. - */ - -export { registerHistoryRoutes } from './register_history_routes'; diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/history/register_load_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/history/register_load_route.js deleted file mode 100644 index 1d34be56fcefc..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/history/register_load_route.js +++ /dev/null @@ -1,78 +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 { get } from 'lodash'; -import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { WatchHistoryItem } from '../../../models/watch_history_item'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError, wrapCustomError } from '../../../lib/error_wrappers'; -import { INDEX_NAMES } from '../../../../common/constants'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; - -function fetchHistoryItem(callWithRequest, watchHistoryItemId) { - return callWithRequest('search', { - index: INDEX_NAMES.WATCHER_HISTORY, - body: { - query: { - bool: { - must: [ - { term: { '_id': watchHistoryItemId } }, - ] - } - } - } - }); -} - -export function registerLoadRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/history/{id}', - method: 'GET', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - const id = request.params.id; - - return fetchHistoryItem(callWithRequest, id) - .then((responseFromES) => { - const hit = get(responseFromES, 'hits.hits[0]'); - if (!hit) { - throw wrapCustomError( - new Error(`Watch History Item with id = ${id} not found`), 404 - ); - } - - const watchHistoryItemJson = get(hit, '_source'); - const watchId = get(hit, '_source.watch_id'); - const json = { - id, - watchId, - watchHistoryItemJson, - includeDetails: true - }; - - const watchHistoryItem = WatchHistoryItem.fromUpstreamJson(json); - return { - watchHistoryItem: watchHistoryItem.downstreamJson - }; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/indices/register_get_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/indices/register_get_route.js deleted file mode 100644 index 86de6f3da7ad5..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/indices/register_get_route.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. - */ - -import { reduce, size } from 'lodash'; -import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; - -function getIndexNamesFromAliasesResponse(json) { - return reduce(json, (list, { aliases }, indexName) => { - list.push(indexName); - if (size(aliases) > 0) { - list.push(...Object.keys(aliases)); - } - return list; - }, []); -} - -function getIndices(callWithRequest, pattern, limit = 10) { - return callWithRequest('indices.getAlias', { - index: pattern, - ignore: [404] - }) - .then(aliasResult => { - if (aliasResult.status !== 404) { - const indicesFromAliasResponse = getIndexNamesFromAliasesResponse(aliasResult); - return indicesFromAliasResponse.slice(0, limit); - } - - const params = { - index: pattern, - ignore: [404], - body: { - size: 0, // no hits - aggs: { - indices: { - terms: { - field: '_index', - size: limit, - } - } - } - } - }; - - return callWithRequest('search', params) - .then(response => { - if (response.status === 404 || !response.aggregations) { - return []; - } - return response.aggregations.indices.buckets.map(bucket => bucket.key); - }); - }); -} - -export function registerGetRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/indices', - method: 'POST', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - const { pattern } = request.payload; - - return getIndices(callWithRequest, pattern) - .then(indices => { - return { indices }; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/settings/register_load_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/settings/register_load_route.js deleted file mode 100644 index 65c961c8c82f2..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/settings/register_load_route.js +++ /dev/null @@ -1,47 +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 { callWithInternalUserFactory } from '../../../lib/call_with_internal_user_factory'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; -import { Settings } from '../../../models/settings'; - -function fetchClusterSettings(callWithInternalUser) { - return callWithInternalUser('cluster.getSettings', { - includeDefaults: true, - filterPath: '**.xpack.notification' - }); -} - -export function registerLoadRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - const callWithInternalUser = callWithInternalUserFactory(server); - - server.route({ - path: '/api/watcher/settings', - method: 'GET', - handler: () => { - return fetchClusterSettings(callWithInternalUser) - .then((settings) => { - return Settings.fromUpstreamJson(settings).downstreamJson; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/action/register_acknowledge_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/action/register_acknowledge_route.js deleted file mode 100644 index ffecebf805cf6..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/action/register_acknowledge_route.js +++ /dev/null @@ -1,63 +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 { get } from 'lodash'; -import { callWithRequestFactory } from '../../../../lib/call_with_request_factory'; -import { isEsErrorFactory } from '../../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../../lib/error_wrappers'; -import { WatchStatus } from '../../../../models/watch_status'; -import { licensePreRoutingFactory } from'../../../../lib/license_pre_routing_factory'; - -export function registerAcknowledgeRoute(server) { - - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/{watchId}/action/{actionId}/acknowledge', - method: 'PUT', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - const { watchId, actionId } = request.params; - - return acknowledgeAction(callWithRequest, watchId, actionId) - .then(hit => { - const watchStatusJson = get(hit, 'status'); - const json = { - id: watchId, - watchStatusJson: watchStatusJson - }; - - const watchStatus = WatchStatus.fromUpstreamJson(json); - return { - watchStatus: watchStatus.downstreamJson - }; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - const statusCodeToMessageMap = { - 404: `Watch with id = ${watchId} not found` - }; - throw wrapEsError(err, statusCodeToMessageMap); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} - -function acknowledgeAction(callWithRequest, watchId, actionId) { - return callWithRequest('watcher.ackWatch', { - id: watchId, - action: actionId - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_activate_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_activate_route.js deleted file mode 100644 index ea669a16a0172..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_activate_route.js +++ /dev/null @@ -1,63 +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 { get } from 'lodash'; -import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; -import { WatchStatus } from '../../../models/watch_status'; - -function activateWatch(callWithRequest, watchId) { - return callWithRequest('watcher.activateWatch', { - id: watchId - }); -} - -export function registerActivateRoute(server) { - - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/{watchId}/activate', - method: 'PUT', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - - const { watchId } = request.params; - - return activateWatch(callWithRequest, watchId) - .then(hit => { - const watchStatusJson = get(hit, 'status'); - const json = { - id: watchId, - watchStatusJson: watchStatusJson - }; - - const watchStatus = WatchStatus.fromUpstreamJson(json); - return { - watchStatus: watchStatus.downstreamJson - }; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - const statusCodeToMessageMap = { - 404: `Watch with id = ${watchId} not found` - }; - throw wrapEsError(err, statusCodeToMessageMap); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_deactivate_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_deactivate_route.js deleted file mode 100644 index 2411290e2034a..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_deactivate_route.js +++ /dev/null @@ -1,63 +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 { get } from 'lodash'; -import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; -import { WatchStatus } from '../../../models/watch_status'; - -function deactivateWatch(callWithRequest, watchId) { - return callWithRequest('watcher.deactivateWatch', { - id: watchId - }); -} - -export function registerDeactivateRoute(server) { - - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/{watchId}/deactivate', - method: 'PUT', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - - const { watchId } = request.params; - - return deactivateWatch(callWithRequest, watchId) - .then(hit => { - const watchStatusJson = get(hit, 'status'); - const json = { - id: watchId, - watchStatusJson: watchStatusJson - }; - - const watchStatus = WatchStatus.fromUpstreamJson(json); - return { - watchStatus: watchStatus.downstreamJson - }; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - const statusCodeToMessageMap = { - 404: `Watch with id = ${watchId} not found` - }; - throw wrapEsError(err, statusCodeToMessageMap); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_delete_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_delete_route.js deleted file mode 100644 index dc3b015dffa90..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_delete_route.js +++ /dev/null @@ -1,50 +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 { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; - -function deleteWatch(callWithRequest, watchId) { - return callWithRequest('watcher.deleteWatch', { - id: watchId - }); -} - -export function registerDeleteRoute(server) { - - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/{watchId}', - method: 'DELETE', - handler: (request, h) => { - const callWithRequest = callWithRequestFactory(server, request); - - const { watchId } = request.params; - - return deleteWatch(callWithRequest, watchId) - .then(() => h.response().code(204)) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - const statusCodeToMessageMap = { - 404: `Watch with id = ${watchId} not found` - }; - throw wrapEsError(err, statusCodeToMessageMap); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_execute_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_execute_route.js deleted file mode 100644 index f378829147280..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_execute_route.js +++ /dev/null @@ -1,69 +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 { get } from 'lodash'; -import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { ExecuteDetails } from '../../../models/execute_details'; -import { Watch } from '../../../models/watch'; -import { WatchHistoryItem } from '../../../models/watch_history_item'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; - -function executeWatch(callWithRequest, executeDetails, watchJson) { - const body = executeDetails; - body.watch = watchJson; - - return callWithRequest('watcher.executeWatch', { - body - }); -} - -export function registerExecuteRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/execute', - method: 'PUT', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - const executeDetails = ExecuteDetails.fromDownstreamJson(request.payload.executeDetails); - const watch = Watch.fromDownstreamJson(request.payload.watch); - - return executeWatch(callWithRequest, executeDetails.upstreamJson, watch.watchJson) - .then((hit) => { - const id = get(hit, '_id'); - const watchHistoryItemJson = get(hit, 'watch_record'); - const watchId = get(hit, 'watch_record.watch_id'); - const json = { - id, - watchId, - watchHistoryItemJson, - includeDetails: true - }; - - const watchHistoryItem = WatchHistoryItem.fromUpstreamJson(json); - return { - watchHistoryItem: watchHistoryItem.downstreamJson - }; - }) - .catch(err => { - - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_history_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_history_route.js deleted file mode 100644 index 702cf8a2b64e2..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_history_route.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. - */ - -import { get } from 'lodash'; -import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { fetchAllFromScroll } from '../../../lib/fetch_all_from_scroll'; -import { INDEX_NAMES, ES_SCROLL_SETTINGS } from '../../../../common/constants'; -import { WatchHistoryItem } from '../../../models/watch_history_item'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; - -function fetchHistoryItems(callWithRequest, watchId, startTime) { - const params = { - index: INDEX_NAMES.WATCHER_HISTORY, - scroll: ES_SCROLL_SETTINGS.KEEPALIVE, - body: { - size: ES_SCROLL_SETTINGS.PAGE_SIZE, - sort: [ - { 'result.execution_time': 'desc' } - ], - query: { - bool: { - must: [ - { term: { 'watch_id': watchId } }, - ] - } - } - } - }; - - // Add time range clause to query if startTime is specified - if (startTime !== 'all') { - const timeRangeQuery = { range: { 'result.execution_time': { gte: startTime } } }; - params.body.query.bool.must.push(timeRangeQuery); - } - - return callWithRequest('search', params) - .then(response => fetchAllFromScroll(response, callWithRequest)); -} - -export function registerHistoryRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/{watchId}/history', - method: 'GET', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - const { watchId } = request.params; - const { startTime } = request.query; - - return fetchHistoryItems(callWithRequest, watchId, startTime) - .then(hits => { - const watchHistoryItems = hits.map(hit => { - const id = get(hit, '_id'); - const watchHistoryItemJson = get(hit, '_source'); - - const opts = { includeDetails: false }; - return WatchHistoryItem.fromUpstreamJson({ - id, - watchId, - watchHistoryItemJson - }, opts); - }); - - return { - watchHistoryItems: watchHistoryItems.map(watchHistoryItem => watchHistoryItem.downstreamJson) - }; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_load_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_load_route.js deleted file mode 100644 index e5210dbff3567..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_load_route.js +++ /dev/null @@ -1,68 +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 { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { get } from 'lodash'; -import { Watch } from '../../../models/watch'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; - -function fetchWatch(callWithRequest, watchId) { - return callWithRequest('watcher.getWatch', { - id: watchId - }); -} - -export function registerLoadRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/{id}', - method: 'GET', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - - const id = request.params.id; - - return fetchWatch(callWithRequest, id) - .then(hit => { - const watchJson = get(hit, 'watch'); - const watchStatusJson = get(hit, 'status'); - const json = { - id, - watchJson, - watchStatusJson, - }; - - const watch = Watch.fromUpstreamJson(json, { - throwExceptions: { - Action: false, - }, - }); - return { - watch: watch.downstreamJson - }; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - const statusCodeToMessageMap = { - 404: `Watch with id = ${id} not found`, - }; - throw wrapEsError(err, statusCodeToMessageMap); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_save_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_save_route.js deleted file mode 100644 index 3cbb0a4e1cc47..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_save_route.js +++ /dev/null @@ -1,94 +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 { WATCH_TYPES } from '../../../../common/constants'; -import { serializeJsonWatch, serializeThresholdWatch } from '../../../../common/lib/serialization'; -import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError, wrapCustomError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; -import { i18n } from '@kbn/i18n'; - -function fetchWatch(callWithRequest, watchId) { - return callWithRequest('watcher.getWatch', { - id: watchId - }); -} - -function saveWatch(callWithRequest, id, body) { - return callWithRequest('watcher.putWatch', { - id, - body, - }); -} - -export function registerSaveRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/{id}', - method: 'PUT', - handler: async (request) => { - const callWithRequest = callWithRequestFactory(server, request); - const { id, type, isNew, ...watchConfig } = request.payload; - - // For new watches, verify watch with the same ID doesn't already exist - if (isNew) { - const conflictError = wrapCustomError( - new Error(i18n.translate('xpack.watcher.saveRoute.duplicateWatchIdErrorMessage', { - defaultMessage: 'There is already a watch with ID \'{watchId}\'.', - values: { - watchId: id, - } - })), - 409 - ); - - try { - const existingWatch = await fetchWatch(callWithRequest, id); - - if (existingWatch.found) { - throw conflictError; - } - } catch (e) { - // Rethrow conflict error but silently swallow all others - if (e === conflictError) { - throw e; - } - } - } - - let serializedWatch; - - switch (type) { - case WATCH_TYPES.JSON: - const { name, watch } = watchConfig; - serializedWatch = serializeJsonWatch(name, watch); - break; - - case WATCH_TYPES.THRESHOLD: - serializedWatch = serializeThresholdWatch(watchConfig); - break; - } - - // Create new watch - return saveWatch(callWithRequest, id, serializedWatch) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_visualize_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_visualize_route.js deleted file mode 100644 index ff9d8f9775d5e..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watch/register_visualize_route.js +++ /dev/null @@ -1,62 +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 { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { Watch } from '../../../models/watch'; -import { VisualizeOptions } from '../../../models/visualize_options'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; - -function fetchVisualizeData(callWithRequest, index, body) { - const params = { - index, - body, - ignoreUnavailable: true, - allowNoIndices: true, - ignore: [404] - }; - - return callWithRequest('search', params); -} - -export function registerVisualizeRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watch/visualize', - method: 'POST', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - const watch = Watch.fromDownstreamJson(request.payload.watch); - const options = VisualizeOptions.fromDownstreamJson(request.payload.options); - const body = watch.getVisualizeQuery(options); - - return fetchVisualizeData(callWithRequest, watch.index, body) - .then(hits => { - const visualizeData = watch.formatVisualizeData(hits); - - return { - visualizeData - }; - }) - .catch(err => { - - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watches/register_delete_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watches/register_delete_route.js deleted file mode 100644 index a0bbfb954b755..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watches/register_delete_route.js +++ /dev/null @@ -1,58 +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 { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; - -function deleteWatches(callWithRequest, watchIds) { - const deletePromises = watchIds.map(watchId => { - return callWithRequest('watcher.deleteWatch', { - id: watchId, - }) - .then(success => ({ success })) - .catch(error => ({ error })); - }); - - return Promise.all(deletePromises).then(results => { - const errors = []; - const successes = []; - results.forEach(({ success, error }) => { - if (success) { - successes.push(success._id); - } else if (error) { - errors.push(error._id); - } - }); - - return { - successes, - errors, - }; - }); -} - -export function registerDeleteRoute(server) { - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watches/delete', - method: 'POST', - handler: async request => { - const callWithRequest = callWithRequestFactory(server, request); - - try { - const results = await deleteWatches(callWithRequest, request.payload.watchIds); - return { results }; - } catch (err) { - throw wrapUnknownError(err); - } - }, - config: { - pre: [licensePreRouting], - }, - }); -} diff --git a/x-pack/legacy/plugins/watcher/server/routes/api/watches/register_list_route.js b/x-pack/legacy/plugins/watcher/server/routes/api/watches/register_list_route.js deleted file mode 100644 index 2a617e275d1ee..0000000000000 --- a/x-pack/legacy/plugins/watcher/server/routes/api/watches/register_list_route.js +++ /dev/null @@ -1,79 +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 { get } from 'lodash'; -import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; -import { fetchAllFromScroll } from '../../../lib/fetch_all_from_scroll'; -import { INDEX_NAMES, ES_SCROLL_SETTINGS } from '../../../../common/constants'; -import { Watch } from '../../../models/watch'; -import { isEsErrorFactory } from '../../../lib/is_es_error_factory'; -import { wrapEsError, wrapUnknownError } from '../../../lib/error_wrappers'; -import { licensePreRoutingFactory } from'../../../lib/license_pre_routing_factory'; - -function fetchWatches(callWithRequest) { - const params = { - index: INDEX_NAMES.WATCHES, - scroll: ES_SCROLL_SETTINGS.KEEPALIVE, - body: { - size: ES_SCROLL_SETTINGS.PAGE_SIZE, - }, - ignore: [404] - }; - - return callWithRequest('search', params) - .then(response => fetchAllFromScroll(response, callWithRequest)); -} - -export function registerListRoute(server) { - const isEsError = isEsErrorFactory(server); - const licensePreRouting = licensePreRoutingFactory(server); - - server.route({ - path: '/api/watcher/watches', - method: 'GET', - handler: (request) => { - const callWithRequest = callWithRequestFactory(server, request); - - return fetchWatches(callWithRequest) - .then(hits => { - const watches = hits.map(hit => { - const id = get(hit, '_id'); - const watchJson = get(hit, '_source'); - const watchStatusJson = get(hit, '_source.status'); - - return Watch.fromUpstreamJson( - { - id, - watchJson, - watchStatusJson, - }, - { - throwExceptions: { - Action: false, - }, - } - ); - }); - - return { - watches: watches.map(watch => watch.downstreamJson) - }; - }) - .catch(err => { - // Case: Error from Elasticsearch JS client - if (isEsError(err)) { - throw wrapEsError(err); - } - - // Case: default - throw wrapUnknownError(err); - }); - }, - config: { - pre: [ licensePreRouting ] - } - }); -}