From 1d5ddbb89a571411e4fe787975c6d819253b91cc Mon Sep 17 00:00:00 2001 From: Timothy Sullivan Date: Tue, 31 Aug 2021 16:02:42 -0700 Subject: [PATCH] refactor/reflatten server routes --- .../routes/diagnostic/screenshot.test.ts | 2 +- .../csv_searchsource_immediate.ts | 17 ++- .../{ => generate}/generate_from_jobparams.ts | 29 ++-- .../generation_from_jobparams.test.ts} | 12 +- .../reporting/server/routes/generate/index.ts | 10 ++ .../server/routes/{ => generate}/legacy.ts | 33 +++-- .../reporting/server/routes/generation.ts | 92 ------------ .../plugins/reporting/server/routes/index.ts | 23 ++- .../server/routes/lib/get_document_payload.ts | 2 +- .../server/routes/lib/handle_request.test.ts | 133 ++++++++++++++++++ .../server/routes/lib/handle_request.ts | 100 +++++++++++++ .../server/routes/lib/job_response_handler.ts | 1 + .../reporting/server/routes/lib/jobs_query.ts | 9 +- .../server/routes/management/index.ts | 8 ++ .../routes/{ => management}/jobs.test.ts | 12 +- .../server/routes/{ => management}/jobs.ts | 18 +-- .../reporting/server/routes/types.d.ts | 35 ----- 17 files changed, 330 insertions(+), 206 deletions(-) rename x-pack/plugins/reporting/server/routes/{ => generate}/csv_searchsource_immediate.ts (88%) rename x-pack/plugins/reporting/server/routes/{ => generate}/generate_from_jobparams.ts (81%) rename x-pack/plugins/reporting/server/routes/{generation.test.ts => generate/generation_from_jobparams.test.ts} (94%) create mode 100644 x-pack/plugins/reporting/server/routes/generate/index.ts rename x-pack/plugins/reporting/server/routes/{ => generate}/legacy.ts (72%) delete mode 100644 x-pack/plugins/reporting/server/routes/generation.ts create mode 100644 x-pack/plugins/reporting/server/routes/lib/handle_request.test.ts create mode 100644 x-pack/plugins/reporting/server/routes/lib/handle_request.ts create mode 100644 x-pack/plugins/reporting/server/routes/management/index.ts rename x-pack/plugins/reporting/server/routes/{ => management}/jobs.test.ts (98%) rename x-pack/plugins/reporting/server/routes/{ => management}/jobs.ts (91%) delete mode 100644 x-pack/plugins/reporting/server/routes/types.d.ts diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.test.ts b/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.test.ts index 6c5d548e77020..6d844f9637a0b 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.test.ts +++ b/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.test.ts @@ -36,7 +36,7 @@ describe('POST /diagnose/screenshot', () => { toPromise: () => (resp instanceof Error ? Promise.reject(resp) : Promise.resolve(resp)), }), })); - (generatePngObservableFactory as any).mockResolvedValue(generateMock); + (generatePngObservableFactory as jest.Mock).mockResolvedValue(generateMock); }; const config = createMockConfigSchema({ queue: { timeout: 120000 } }); diff --git a/x-pack/plugins/reporting/server/routes/csv_searchsource_immediate.ts b/x-pack/plugins/reporting/server/routes/generate/csv_searchsource_immediate.ts similarity index 88% rename from x-pack/plugins/reporting/server/routes/csv_searchsource_immediate.ts rename to x-pack/plugins/reporting/server/routes/generate/csv_searchsource_immediate.ts index efdb91d948536..b492ee456483d 100644 --- a/x-pack/plugins/reporting/server/routes/csv_searchsource_immediate.ts +++ b/x-pack/plugins/reporting/server/routes/generate/csv_searchsource_immediate.ts @@ -5,16 +5,16 @@ * 2.0. */ -import { Writable } from 'stream'; import { schema } from '@kbn/config-schema'; import { KibanaRequest } from 'src/core/server'; -import { ReportingCore } from '../'; -import { runTaskFnFactory } from '../export_types/csv_searchsource_immediate/execute_job'; -import { JobParamsDownloadCSV } from '../export_types/csv_searchsource_immediate/types'; -import { LevelLogger as Logger } from '../lib'; -import { TaskRunResult } from '../lib/tasks'; -import { authorizedUserPreRouting } from './lib/authorized_user_pre_routing'; -import { HandlerErrorFunction } from './types'; +import { Writable } from 'stream'; +import { ReportingCore } from '../../'; +import { runTaskFnFactory } from '../../export_types/csv_searchsource_immediate/execute_job'; +import { JobParamsDownloadCSV } from '../../export_types/csv_searchsource_immediate/types'; +import { LevelLogger as Logger } from '../../lib'; +import { TaskRunResult } from '../../lib/tasks'; +import { authorizedUserPreRouting } from '../lib/authorized_user_pre_routing'; +import { handleError } from '../lib/handle_request'; const API_BASE_URL_V1 = '/api/reporting/v1'; const API_BASE_GENERATE_V1 = `${API_BASE_URL_V1}/generate`; @@ -32,7 +32,6 @@ export type CsvFromSavedObjectRequest = KibanaRequest>; diff --git a/x-pack/plugins/reporting/server/routes/generate/index.ts b/x-pack/plugins/reporting/server/routes/generate/index.ts new file mode 100644 index 0000000000000..0df9b4a725768 --- /dev/null +++ b/x-pack/plugins/reporting/server/routes/generate/index.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { registerGenerateCsvFromSavedObjectImmediate } from './csv_searchsource_immediate'; // FIXME: should not need to register each immediate export type separately +export { registerJobGenerationRoutes } from './generate_from_jobparams'; +export { registerLegacy } from './legacy'; diff --git a/x-pack/plugins/reporting/server/routes/legacy.ts b/x-pack/plugins/reporting/server/routes/generate/legacy.ts similarity index 72% rename from x-pack/plugins/reporting/server/routes/legacy.ts rename to x-pack/plugins/reporting/server/routes/generate/legacy.ts index 79f1b7f17c2da..e3868316d87f2 100644 --- a/x-pack/plugins/reporting/server/routes/legacy.ts +++ b/x-pack/plugins/reporting/server/routes/generate/legacy.ts @@ -6,21 +6,16 @@ */ import { schema } from '@kbn/config-schema'; -import querystring from 'querystring'; -import { authorizedUserPreRouting } from './lib/authorized_user_pre_routing'; -import { API_BASE_URL } from '../../common/constants'; -import { HandlerErrorFunction, HandlerFunction } from './types'; -import { ReportingCore } from '../core'; -import { LevelLogger } from '../lib'; +import querystring, { ParsedUrlQueryInput } from 'querystring'; +import { API_BASE_URL } from '../../../common/constants'; +import { ReportingCore } from '../../core'; +import { LevelLogger } from '../../lib'; +import { authorizedUserPreRouting } from '../lib/authorized_user_pre_routing'; +import { handleError, handleGenerateRequest } from '../lib/handle_request'; const BASE_GENERATE = `${API_BASE_URL}/generate`; -export function registerLegacy( - reporting: ReportingCore, - handler: HandlerFunction, - handleError: HandlerErrorFunction, - logger: LevelLogger -) { +export function registerLegacy(reporting: ReportingCore, logger: LevelLogger) { const { router } = reporting.getPluginSetupDeps(); function createLegacyPdfRoute({ path, objectType }: { path: string; objectType: string }) { @@ -32,8 +27,10 @@ export function registerLegacy( validate: { params: schema.object({ savedObjectId: schema.string({ minLength: 3 }), + title: schema.string(), + browserTimezone: schema.string(), }), - query: schema.any(), + query: schema.maybe(schema.string()), }, }, @@ -46,10 +43,11 @@ export function registerLegacy( title, savedObjectId, browserTimezone, - }: { title: string; savedObjectId: string; browserTimezone: string } = req.params as any; - const queryString = querystring.stringify(req.query as any); + }: { title: string; savedObjectId: string; browserTimezone: string } = req.params; + const queryString = querystring.stringify(req.query as ParsedUrlQueryInput | undefined); - return await handler( + return await handleGenerateRequest( + reporting, user, exportTypeId, { @@ -62,7 +60,8 @@ export function registerLegacy( }, context, req, - res + res, + logger ); } catch (err) { throw handleError(res, err); diff --git a/x-pack/plugins/reporting/server/routes/generation.ts b/x-pack/plugins/reporting/server/routes/generation.ts deleted file mode 100644 index adbfbda727af2..0000000000000 --- a/x-pack/plugins/reporting/server/routes/generation.ts +++ /dev/null @@ -1,92 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import Boom from '@hapi/boom'; -import { kibanaResponseFactory } from 'src/core/server'; -import { ReportingCore } from '../'; -import { API_BASE_URL } from '../../common/constants'; -import { LevelLogger as Logger } from '../lib'; -import { enqueueJob } from '../lib/enqueue_job'; -import { registerGenerateCsvFromSavedObjectImmediate } from './csv_searchsource_immediate'; -import { registerGenerateFromJobParams } from './generate_from_jobparams'; -import { registerLegacy } from './legacy'; -import { HandlerFunction } from './types'; - -const getDownloadBaseUrl = (reporting: ReportingCore) => { - const config = reporting.getConfig(); - return config.kbnConfig.get('server', 'basePath') + `${API_BASE_URL}/jobs/download`; -}; - -export function registerJobGenerationRoutes(reporting: ReportingCore, logger: Logger) { - /* - * Generates enqueued job details to use in responses - */ - const handler: HandlerFunction = async (user, exportTypeId, jobParams, context, req, res) => { - // ensure the async dependencies are loaded - if (!context.reporting) { - return res.custom({ statusCode: 503, body: 'Not Available' }); - } - - const licenseInfo = await reporting.getLicenseInfo(); - const licenseResults = licenseInfo[exportTypeId]; - - if (!licenseResults) { - return res.badRequest({ body: `Invalid export-type of ${exportTypeId}` }); - } - - if (!licenseResults.enableLinks) { - return res.forbidden({ body: licenseResults.message }); - } - - try { - const report = await enqueueJob( - reporting, - req, - context, - user, - exportTypeId, - jobParams, - logger - ); - - // return task manager's task information and the download URL - const downloadBaseUrl = getDownloadBaseUrl(reporting); - - return res.ok({ - headers: { - 'content-type': 'application/json', - }, - body: { - path: `${downloadBaseUrl}/${report._id}`, - job: report.toApiJSON(), - }, - }); - } catch (err) { - logger.error(err); - throw err; - } - }; - - /* - * Error should already have been logged by the time we get here - */ - function handleError(res: typeof kibanaResponseFactory, err: Error | Boom.Boom) { - if (err instanceof Boom.Boom) { - return res.customError({ - statusCode: err.output.statusCode, - body: err.output.payload.message, - }); - } - - // unknown error, can't convert to 4xx - throw err; - } - - registerGenerateFromJobParams(reporting, handler, handleError); - registerGenerateCsvFromSavedObjectImmediate(reporting, handleError, logger); - registerLegacy(reporting, handler, handleError, logger); -} diff --git a/x-pack/plugins/reporting/server/routes/index.ts b/x-pack/plugins/reporting/server/routes/index.ts index a462da3849083..14a16e563ccbb 100644 --- a/x-pack/plugins/reporting/server/routes/index.ts +++ b/x-pack/plugins/reporting/server/routes/index.ts @@ -5,23 +5,22 @@ * 2.0. */ -import { LevelLogger as Logger } from '../lib'; +import { ReportingCore } from '..'; +import { LevelLogger } from '../lib'; import { registerDeprecationsRoutes } from './deprecations'; import { registerDiagnosticRoutes } from './diagnostic'; -import { registerJobGenerationRoutes } from './generation'; -import { registerJobInfoRoutes } from './jobs'; -import { ReportingCore } from '../core'; +import { + registerGenerateCsvFromSavedObjectImmediate, + registerJobGenerationRoutes, + registerLegacy, +} from './generate'; +import { registerJobInfoRoutes } from './management'; -export function registerRoutes(reporting: ReportingCore, logger: Logger) { +export function registerRoutes(reporting: ReportingCore, logger: LevelLogger) { registerDeprecationsRoutes(reporting, logger); registerDiagnosticRoutes(reporting, logger); + registerGenerateCsvFromSavedObjectImmediate(reporting, logger); registerJobGenerationRoutes(reporting, logger); + registerLegacy(reporting, logger); registerJobInfoRoutes(reporting); } - -export interface ReportingRequestPre { - management: { - jobTypes: string[]; - }; - user: string; -} diff --git a/x-pack/plugins/reporting/server/routes/lib/get_document_payload.ts b/x-pack/plugins/reporting/server/routes/lib/get_document_payload.ts index c083849686ff0..89e6fcf7df21d 100644 --- a/x-pack/plugins/reporting/server/routes/lib/get_document_payload.ts +++ b/x-pack/plugins/reporting/server/routes/lib/get_document_payload.ts @@ -24,7 +24,7 @@ interface Payload { statusCode: number; content: string | Stream | ErrorFromPayload; contentType: string | null; - headers: Record; + headers: Record; } type TaskRunResult = Required['output']; diff --git a/x-pack/plugins/reporting/server/routes/lib/handle_request.test.ts b/x-pack/plugins/reporting/server/routes/lib/handle_request.test.ts new file mode 100644 index 0000000000000..7cfd3870002f5 --- /dev/null +++ b/x-pack/plugins/reporting/server/routes/lib/handle_request.test.ts @@ -0,0 +1,133 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { KibanaRequest, KibanaResponseFactory } from 'kibana/server'; +import { coreMock, httpServerMock } from 'src/core/server/mocks'; +import { ReportingCore } from '../..'; +import { + createMockConfigSchema, + createMockLevelLogger, + createMockReportingCore, +} from '../../test_helpers'; +import { BaseParams, ReportingRequestHandlerContext, ReportingSetup } from '../../types'; +import { handleGenerateRequest } from './handle_request'; + +jest.mock('../../lib/enqueue_job', () => ({ + enqueueJob: () => ({ + _id: 'id-of-this-test-report', + toApiJSON: () => JSON.stringify({ id: 'id-of-this-test-report' }), + }), +})); + +const getMockContext = () => + (({ + core: coreMock.createRequestHandlerContext(), + } as unknown) as ReportingRequestHandlerContext); + +const getMockRequest = () => + ({ + url: { port: '5601', search: '', pathname: '/foo' }, + route: { path: '/foo', options: {} }, + } as KibanaRequest); + +const getMockResponseFactory = () => + (({ + ...httpServerMock.createResponseFactory(), + forbidden: (obj: unknown) => obj, + unauthorized: (obj: unknown) => obj, + } as unknown) as KibanaResponseFactory); + +const mockLogger = createMockLevelLogger(); + +describe('Handle request to generate', () => { + let reportingCore: ReportingCore; + let mockContext: ReturnType; + let mockRequest: ReturnType; + let mockResponseFactory: ReturnType; + + const mockJobParams = {} as BaseParams; + + beforeEach(async () => { + reportingCore = await createMockReportingCore(createMockConfigSchema({})); + mockRequest = getMockRequest(); + + mockResponseFactory = getMockResponseFactory(); + (mockResponseFactory.ok as jest.Mock) = jest.fn((args: unknown) => args); + (mockResponseFactory.forbidden as jest.Mock) = jest.fn((args: unknown) => args); + (mockResponseFactory.badRequest as jest.Mock) = jest.fn((args: unknown) => args); + + mockContext = getMockContext(); + mockContext.reporting = {} as ReportingSetup; + }); + + test('disallows invalid export type', async () => { + expect( + await handleGenerateRequest( + reportingCore, + { username: 'testymcgee' }, + 'neanderthals', + mockJobParams, + mockContext, + mockRequest, + mockResponseFactory, + mockLogger + ) + ).toMatchInlineSnapshot(` + Object { + "body": "Invalid export-type of neanderthals", + } + `); + }); + + test('disallows unsupporting license', async () => { + (reportingCore.getLicenseInfo as jest.Mock) = jest.fn(() => ({ + csv: { enableLinks: false, message: `seeing this means the license isn't supported` }, + })); + + expect( + await handleGenerateRequest( + reportingCore, + { username: 'testymcgee' }, + 'csv', + mockJobParams, + mockContext, + mockRequest, + mockResponseFactory, + mockLogger + ) + ).toMatchInlineSnapshot(` + Object { + "body": "seeing this means the license isn't supported", + } + `); + }); + + test('generates the download path', async () => { + expect( + await handleGenerateRequest( + reportingCore, + { username: 'testymcgee' }, + 'csv', + mockJobParams, + mockContext, + mockRequest, + mockResponseFactory, + mockLogger + ) + ).toMatchInlineSnapshot(` + Object { + "body": Object { + "job": "{\\"id\\":\\"id-of-this-test-report\\"}", + "path": "undefined/api/reporting/jobs/download/id-of-this-test-report", + }, + "headers": Object { + "content-type": "application/json", + }, + } + `); + }); +}); diff --git a/x-pack/plugins/reporting/server/routes/lib/handle_request.ts b/x-pack/plugins/reporting/server/routes/lib/handle_request.ts new file mode 100644 index 0000000000000..824aa3ad8c683 --- /dev/null +++ b/x-pack/plugins/reporting/server/routes/lib/handle_request.ts @@ -0,0 +1,100 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import Boom from '@hapi/boom'; +import { IKibanaResponse, KibanaRequest, KibanaResponseFactory } from 'kibana/server'; +import { ReportingCore } from '../..'; +import { API_BASE_URL } from '../../../common/constants'; +import { JobParamsPDFLegacy } from '../../export_types/printable_pdf/types'; +import { LevelLogger } from '../../lib'; +import { enqueueJob } from '../../lib/enqueue_job'; +import { BaseParams, ReportingRequestHandlerContext, ReportingUser } from '../../types'; + +export const handleUnavailable = (res: KibanaResponseFactory) => { + return res.custom({ statusCode: 503, body: 'Not Available' }); +}; + +const getDownloadBaseUrl = (reporting: ReportingCore) => { + const config = reporting.getConfig(); + return config.kbnConfig.get('server', 'basePath') + `${API_BASE_URL}/jobs/download`; +}; + +export type HandlerFunction = ( + reporting: ReportingCore, + user: ReportingUser, + exportType: string, + jobParams: BaseParams | JobParamsPDFLegacy, + context: ReportingRequestHandlerContext, + req: KibanaRequest, + res: KibanaResponseFactory, + logger: LevelLogger +) => Promise; + +export type HandleErrorFunction = (res: KibanaResponseFactory, err: Error) => IKibanaResponse; + +export const handleGenerateRequest: HandlerFunction = async ( + reporting, + user, + exportTypeId, + jobParams, + context, + req, + res, + logger +) => { + // ensure the async dependencies are loaded + if (!context.reporting) { + return handleUnavailable(res); + } + + const licenseInfo = await reporting.getLicenseInfo(); + const licenseResults = licenseInfo[exportTypeId]; + + if (!licenseResults) { + return res.badRequest({ body: `Invalid export-type of ${exportTypeId}` }); + } + + if (!licenseResults.enableLinks) { + return res.forbidden({ body: licenseResults.message }); + } + + try { + const report = await enqueueJob(reporting, req, context, user, exportTypeId, jobParams, logger); + + // return task manager's task information and the download URL + const downloadBaseUrl = getDownloadBaseUrl(reporting); + + return res.ok({ + headers: { 'content-type': 'application/json' }, + body: { + path: `${downloadBaseUrl}/${report._id}`, + job: report.toApiJSON(), + }, + }); + } catch (err) { + logger.error(err); + throw err; + } +}; + +/* + * Error should already have been logged by the time we get here + */ +export const handleError: HandleErrorFunction = ( + res: KibanaResponseFactory, + err: Error | Boom.Boom +) => { + if (err instanceof Boom.Boom) { + return res.customError({ + statusCode: err.output.statusCode, + body: err.output.payload.message, + }); + } + + // unknown error, can't convert to 4xx + throw err; +}; diff --git a/x-pack/plugins/reporting/server/routes/lib/job_response_handler.ts b/x-pack/plugins/reporting/server/routes/lib/job_response_handler.ts index 5b63b2627f931..4033b317bef62 100644 --- a/x-pack/plugins/reporting/server/routes/lib/job_response_handler.ts +++ b/x-pack/plugins/reporting/server/routes/lib/job_response_handler.ts @@ -60,6 +60,7 @@ export async function downloadJobResponseHandler( } catch (err) { const { logger } = reporting.getPluginSetupDeps(); logger.error(err); + throw err; } } diff --git a/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts b/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts index e15fa01362e97..afa83ed331672 100644 --- a/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts +++ b/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts @@ -11,9 +11,10 @@ import { ResponseError } from '@elastic/elasticsearch/lib/errors'; import { i18n } from '@kbn/i18n'; import { UnwrapPromise } from '@kbn/utility-types'; import { ElasticsearchClient } from 'src/core/server'; +import { PromiseType } from 'utility-types'; import { ReportingCore } from '../../'; -import { statuses } from '../../lib/statuses'; import { ReportApiJSON, ReportSource } from '../../../common/types'; +import { statuses } from '../../lib/statuses'; import { Report } from '../../lib/store'; import { ReportingUser } from '../../types'; @@ -58,9 +59,9 @@ export function jobsQueryFactory(reportingCore: ReportingCore): JobsQueryFactory return `${config.get('index')}-*`; } - async function execQuery any>( - callback: T - ): Promise> | undefined> { + async function execQuery< + T extends (client: ElasticsearchClient) => Promise> | undefined> + >(callback: T): Promise> | undefined> { try { const { asInternalUser: client } = await reportingCore.getEsClient(); diff --git a/x-pack/plugins/reporting/server/routes/management/index.ts b/x-pack/plugins/reporting/server/routes/management/index.ts new file mode 100644 index 0000000000000..0c31b2b0d6a0c --- /dev/null +++ b/x-pack/plugins/reporting/server/routes/management/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { registerJobInfoRoutes } from './jobs'; diff --git a/x-pack/plugins/reporting/server/routes/jobs.test.ts b/x-pack/plugins/reporting/server/routes/management/jobs.test.ts similarity index 98% rename from x-pack/plugins/reporting/server/routes/jobs.test.ts rename to x-pack/plugins/reporting/server/routes/management/jobs.test.ts index 883970bd45a74..c14976f616c7b 100644 --- a/x-pack/plugins/reporting/server/routes/jobs.test.ts +++ b/x-pack/plugins/reporting/server/routes/management/jobs.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -jest.mock('../lib/content_stream', () => ({ +jest.mock('../../lib/content_stream', () => ({ getContentStream: jest.fn(), })); @@ -16,15 +16,15 @@ import { of } from 'rxjs'; import { ElasticsearchClient } from 'kibana/server'; import { setupServer } from 'src/core/server/test_utils'; import supertest from 'supertest'; -import { ReportingCore } from '..'; -import { ReportingInternalSetup } from '../core'; -import { ContentStream, ExportTypesRegistry, getContentStream } from '../lib'; +import { ReportingCore } from '../..'; +import { ReportingInternalSetup } from '../../core'; +import { ContentStream, ExportTypesRegistry, getContentStream } from '../../lib'; import { createMockConfigSchema, createMockPluginSetup, createMockReportingCore, -} from '../test_helpers'; -import { ExportTypeDefinition, ReportingRequestHandlerContext } from '../types'; +} from '../../test_helpers'; +import { ExportTypeDefinition, ReportingRequestHandlerContext } from '../../types'; import { registerJobInfoRoutes } from './jobs'; type SetupServerReturn = UnwrapPromise>; diff --git a/x-pack/plugins/reporting/server/routes/jobs.ts b/x-pack/plugins/reporting/server/routes/management/jobs.ts similarity index 91% rename from x-pack/plugins/reporting/server/routes/jobs.ts rename to x-pack/plugins/reporting/server/routes/management/jobs.ts index 6086c1b9eb872..1cf4787218520 100644 --- a/x-pack/plugins/reporting/server/routes/jobs.ts +++ b/x-pack/plugins/reporting/server/routes/management/jobs.ts @@ -6,20 +6,16 @@ */ import { schema } from '@kbn/config-schema'; -import Boom from '@hapi/boom'; -import { ROUTE_TAG_CAN_REDIRECT } from '../../../security/server'; -import { ReportingCore } from '../'; -import { API_BASE_URL } from '../../common/constants'; -import { authorizedUserPreRouting } from './lib/authorized_user_pre_routing'; -import { jobsQueryFactory } from './lib/jobs_query'; -import { deleteJobResponseHandler, downloadJobResponseHandler } from './lib/job_response_handler'; +import { ReportingCore } from '../../'; +import { ROUTE_TAG_CAN_REDIRECT } from '../../../../security/server'; +import { API_BASE_URL } from '../../../common/constants'; +import { authorizedUserPreRouting } from '../lib/authorized_user_pre_routing'; +import { handleUnavailable } from '../lib/handle_request'; +import { jobsQueryFactory } from '../lib/jobs_query'; +import { deleteJobResponseHandler, downloadJobResponseHandler } from '../lib/job_response_handler'; const MAIN_ENTRY = `${API_BASE_URL}/jobs`; -const handleUnavailable = (res: any) => { - return res.custom({ statusCode: 503, body: 'Not Available' }); -}; - export function registerJobInfoRoutes(reporting: ReportingCore) { const setupDeps = reporting.getPluginSetupDeps(); const { router } = setupDeps; diff --git a/x-pack/plugins/reporting/server/routes/types.d.ts b/x-pack/plugins/reporting/server/routes/types.d.ts deleted file mode 100644 index 336605e6ff9b9..0000000000000 --- a/x-pack/plugins/reporting/server/routes/types.d.ts +++ /dev/null @@ -1,35 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { KibanaRequest, KibanaResponseFactory } from 'src/core/server'; -import type { - BaseParams, - BaseParamsLegacyPDF, - BasePayload, - ReportingRequestHandlerContext, - ReportingUser, -} from '../types'; - -export type HandlerFunction = ( - user: ReportingUser, - exportType: string, - jobParams: BaseParams | BaseParamsLegacyPDF, - context: ReportingRequestHandlerContext, - req: KibanaRequest, - res: KibanaResponseFactory -) => any; - -export type HandlerErrorFunction = (res: KibanaResponseFactory, err: Error) => any; - -export interface QueuedJobPayload { - error?: boolean; - source: { - job: { - payload: BasePayload; - }; - }; -}