diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index fa2a580b4ae83..7055eaa8f98f8 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -518,6 +518,7 @@ packages/kbn-repo-source-classifier @elastic/kibana-operations packages/kbn-repo-source-classifier-cli @elastic/kibana-operations packages/kbn-reporting/common @elastic/appex-sharedux x-pack/examples/reporting_example @elastic/appex-sharedux +x-pack/plugins/reporting_export_types @elastic/appex-sharedux x-pack/plugins/reporting @elastic/appex-sharedux x-pack/test/plugin_functional/plugins/resolver_test @elastic/security-solution examples/response_stream @elastic/ml-ui diff --git a/config/kibana.yml b/config/kibana.yml index 4233bf2882a29..edff747b297b3 100644 --- a/config/kibana.yml +++ b/config/kibana.yml @@ -163,4 +163,4 @@ # Maximum number of documents loaded by each shard to generate autocomplete suggestions. # This value must be a whole number greater than zero. Defaults to 100_000 -#unifiedSearch.autocomplete.valueSuggestions.terminateAfter: 100000 +#unifiedSearch.autocomplete.valueSuggestions.terminateAfter: 100000 \ No newline at end of file diff --git a/docs/developer/plugin-list.asciidoc b/docs/developer/plugin-list.asciidoc index e218387d64341..42fb3f25e2235 100644 --- a/docs/developer/plugin-list.asciidoc +++ b/docs/developer/plugin-list.asciidoc @@ -673,6 +673,10 @@ Elastic. |An awesome Kibana reporting plugin +|{kib-repo}blob/{branch}/x-pack/plugins/reporting_export_types/README.md[reportingExportTypes] +|There are three constructs that interact: the ReportingPlugin, the ExportTypesPlugin and the ExportTypesRegistry. + + |{kib-repo}blob/{branch}/x-pack/plugins/rollup/README.md[rollup] |Welcome to the Kibana rollup plugin! This plugin provides Kibana support for Elasticsearch's rollup feature. Please refer to the Elasticsearch documentation to understand rollup indices and how to create rollup jobs. diff --git a/package.json b/package.json index ce62a3dfe3b58..d94df83ce4ca1 100644 --- a/package.json +++ b/package.json @@ -520,6 +520,7 @@ "@kbn/repo-packages": "link:packages/kbn-repo-packages", "@kbn/reporting-common": "link:packages/kbn-reporting/common", "@kbn/reporting-example-plugin": "link:x-pack/examples/reporting_example", + "@kbn/reporting-export-types": "link:x-pack/plugins/reporting_export_types", "@kbn/reporting-plugin": "link:x-pack/plugins/reporting", "@kbn/resolver-test-plugin": "link:x-pack/test/plugin_functional/plugins/resolver_test", "@kbn/response-stream-plugin": "link:examples/response_stream", diff --git a/packages/kbn-config/src/config.ts b/packages/kbn-config/src/config.ts index cf775bbf3b42b..f1b61ad440141 100644 --- a/packages/kbn-config/src/config.ts +++ b/packages/kbn-config/src/config.ts @@ -31,6 +31,7 @@ export function isConfigPath(value: unknown): value is ConfigPath { * @internal */ export interface Config { + kbnConfig: any; /** * Returns whether or not there is a config value located at the specified path. * @param configPath Path to locate value at. diff --git a/packages/kbn-reporting/common/constants.ts b/packages/kbn-reporting/common/constants.ts index f2bf7e7e99a80..8fcba714ba727 100644 --- a/packages/kbn-reporting/common/constants.ts +++ b/packages/kbn-reporting/common/constants.ts @@ -5,7 +5,13 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ +export const PLUGIN_ID = 'reporting'; + +export const REPORTING_TRANSACTION_TYPE = PLUGIN_ID; + export const UI_SETTINGS_SEARCH_INCLUDE_FROZEN = 'search:includeFrozen'; export const UI_SETTINGS_CUSTOM_PDF_LOGO = 'xpackReporting:customPdfLogo'; export const UI_SETTINGS_DATEFORMAT_TZ = 'dateFormat:tz'; export const CSV_REPORTING_ACTION = 'downloadCsvReport'; + +export const CSV_SEARCHSOURCE_IMMEDIATE_TYPE = 'csv_searchsource_immediate'; diff --git a/tsconfig.base.json b/tsconfig.base.json index 01e7276e6bb86..6fb25e1dbbc39 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -1030,6 +1030,8 @@ "@kbn/reporting-common/*": ["packages/kbn-reporting/common/*"], "@kbn/reporting-example-plugin": ["x-pack/examples/reporting_example"], "@kbn/reporting-example-plugin/*": ["x-pack/examples/reporting_example/*"], + "@kbn/reporting-export-types": ["x-pack/plugins/reporting_export_types"], + "@kbn/reporting-export-types/*": ["x-pack/plugins/reporting_export_types/*"], "@kbn/reporting-plugin": ["x-pack/plugins/reporting"], "@kbn/reporting-plugin/*": ["x-pack/plugins/reporting/*"], "@kbn/resolver-test-plugin": ["x-pack/test/plugin_functional/plugins/resolver_test"], diff --git a/x-pack/.i18nrc.json b/x-pack/.i18nrc.json index 59dea3cb2c9a3..13640e54f641b 100644 --- a/x-pack/.i18nrc.json +++ b/x-pack/.i18nrc.json @@ -61,6 +61,7 @@ "xpack.profiling": ["plugins/profiling"], "xpack.remoteClusters": "plugins/remote_clusters", "xpack.reporting": ["plugins/reporting"], + "xpack.reportingExportTypes": ["plugins/reporting_export_types"], "xpack.rollupJobs": ["plugins/rollup"], "xpack.runtimeFields": "plugins/runtime_fields", "xpack.screenshotting": "plugins/screenshotting", diff --git a/x-pack/examples/reporting_example/public/containers/main.tsx b/x-pack/examples/reporting_example/public/containers/main.tsx index 251626cadd05f..c850667413c9f 100644 --- a/x-pack/examples/reporting_example/public/containers/main.tsx +++ b/x-pack/examples/reporting_example/public/containers/main.tsx @@ -34,12 +34,12 @@ import { BrowserRouter as Router, useHistory } from 'react-router-dom'; import * as Rx from 'rxjs'; import { takeWhile } from 'rxjs/operators'; import type { ScreenshotModePluginSetup } from '@kbn/screenshot-mode-plugin/public'; +import type { ReportingStart } from '@kbn/reporting-plugin/public'; import type { JobAppParamsPDF, JobParamsPDFV2, JobParamsPNGV2, } from '@kbn/reporting-plugin/common/types'; -import type { ReportingStart } from '@kbn/reporting-plugin/public'; import { REPORTING_EXAMPLE_LOCATOR_ID } from '../../common'; import { useApplicationContext } from '../application_context'; import { ROUTES } from '../constants'; diff --git a/x-pack/plugins/canvas/kibana.jsonc b/x-pack/plugins/canvas/kibana.jsonc index c52f6628b4fad..7d4b4c9dbafe4 100644 --- a/x-pack/plugins/canvas/kibana.jsonc +++ b/x-pack/plugins/canvas/kibana.jsonc @@ -31,11 +31,11 @@ "uiActions", "share", "savedObjectsManagement", - "savedObjectsFinder" + "savedObjectsFinder", + "reporting" ], "optionalPlugins": [ "home", - "reporting", "spaces", "usageCollection", "savedObjects", @@ -47,7 +47,7 @@ "lens", "maps", "visualizations", - "fieldFormats" + "fieldFormats", ], } } diff --git a/x-pack/plugins/canvas/server/feature.test.ts b/x-pack/plugins/canvas/server/feature.test.ts index d6ec20258f5cf..f7af5e22db799 100644 --- a/x-pack/plugins/canvas/server/feature.test.ts +++ b/x-pack/plugins/canvas/server/feature.test.ts @@ -12,6 +12,7 @@ let mockReportingPlugin: ReportingStart; beforeEach(() => { mockReportingPlugin = { usesUiCapabilities: () => false, + registerExportType: () => {}, }; }); @@ -87,6 +88,7 @@ it('Provides a feature declaration ', () => { it(`Calls on Reporting whether to include Generate PDF as a sub-feature`, () => { mockReportingPlugin = { usesUiCapabilities: () => true, + registerExportType: () => {}, }; expect(getCanvasFeature({ reporting: mockReportingPlugin })).toMatchInlineSnapshot(` Object { diff --git a/x-pack/plugins/reporting/server/export_types/common/get_absolute_url.test.ts b/x-pack/plugins/reporting/common/get_absolute_url.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/get_absolute_url.test.ts rename to x-pack/plugins/reporting/common/get_absolute_url.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/common/get_absolute_url.ts b/x-pack/plugins/reporting/common/get_absolute_url.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/get_absolute_url.ts rename to x-pack/plugins/reporting/common/get_absolute_url.ts diff --git a/x-pack/plugins/reporting/common/test/fixtures.ts b/x-pack/plugins/reporting/common/test/fixtures.ts index 1a78e52199534..16f748c0a15f7 100644 --- a/x-pack/plugins/reporting/common/test/fixtures.ts +++ b/x-pack/plugins/reporting/common/test/fixtures.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { ReportApiJSON } from '../types'; +import { ReportApiJSON } from '../types'; import type { ReportMock } from './types'; const buildMockReport = (baseObj: ReportMock): ReportApiJSON => ({ diff --git a/x-pack/plugins/reporting/common/types/export_types/printable_pdf.ts b/x-pack/plugins/reporting/common/types/export_types/printable_pdf.ts deleted file mode 100644 index 240cc778b269d..0000000000000 --- a/x-pack/plugins/reporting/common/types/export_types/printable_pdf.ts +++ /dev/null @@ -1,36 +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 type { LayoutParams } from '@kbn/screenshotting-plugin/common'; -import type { BaseParams, BasePayload } from '../base'; - -interface BaseParamsPDF { - layout: LayoutParams; - relativeUrls: string[]; - isDeprecated?: boolean; -} - -// Job params: structure of incoming user request data, after being parsed from RISON - -/** - * @deprecated - */ -export type JobParamsPDFDeprecated = BaseParamsPDF & BaseParams; - -/** - * @deprecated - */ -export type JobAppParamsPDF = Omit; - -/** - * Structure of stored job data provided by create_job - */ -export interface TaskPayloadPDF extends BasePayload { - layout: LayoutParams; - forceNow?: string; - objects: Array<{ relativeUrl: string }>; -} diff --git a/x-pack/plugins/reporting/common/types/export_types/printable_pdf_v2.ts b/x-pack/plugins/reporting/common/types/export_types/printable_pdf_v2.ts deleted file mode 100644 index 58462b84c5eec..0000000000000 --- a/x-pack/plugins/reporting/common/types/export_types/printable_pdf_v2.ts +++ /dev/null @@ -1,33 +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 type { LayoutParams } from '@kbn/screenshotting-plugin/common'; -import type { LocatorParams } from '../url'; -import type { BaseParams, BasePayload } from '../base'; - -interface BaseParamsPDFV2 { - layout: LayoutParams; - - /** - * This value is used to re-create the same visual state as when the report was requested as well as navigate to the correct page. - */ - locatorParams: LocatorParams[]; -} - -// Job params: structure of incoming user request data, after being parsed from RISON -export type JobParamsPDFV2 = BaseParamsPDFV2 & BaseParams; - -export type JobAppParamsPDFV2 = Omit; - -// Job payload: structure of stored job data provided by create_job -export interface TaskPayloadPDFV2 extends BasePayload, BaseParamsPDFV2 { - layout: LayoutParams; - /** - * The value of forceNow is injected server-side every time a given report is generated. - */ - forceNow: string; -} diff --git a/x-pack/plugins/reporting/common/types/index.ts b/x-pack/plugins/reporting/common/types/index.ts index 48968e17a1cb9..a63a53eddc192 100644 --- a/x-pack/plugins/reporting/common/types/index.ts +++ b/x-pack/plugins/reporting/common/types/index.ts @@ -4,19 +4,13 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ - import { TaskRunMetrics, TaskRunResult } from '@kbn/reporting-common'; +import { LayoutParams } from '@kbn/screenshotting-plugin/common'; import type { PdfScreenshotResult, PngScreenshotResult } from '@kbn/screenshotting-plugin/server'; +import type { JobParamsPDFDeprecated } from '../../server/routes/lib'; import type { BaseParams, BaseParamsV2, BasePayload, BasePayloadV2, JobId } from './base'; +import { LocatorParams } from './url'; -export type { - JobParamsCsvFromSavedObject, - TaskPayloadCsvFromSavedObject, -} from './export_types/csv_v2'; -export type { JobParamsPNGDeprecated } from './export_types/png'; -export type { JobParamsPNGV2 } from './export_types/png_v2'; -export type { JobAppParamsPDF, JobParamsPDFDeprecated } from './export_types/printable_pdf'; -export type { JobAppParamsPDFV2, JobParamsPDFV2 } from './export_types/printable_pdf_v2'; export type { DownloadReportFn, IlmPolicyMigrationStatus, @@ -25,6 +19,7 @@ export type { ManagementLinkFn, UrlOrUrlLocatorTuple, } from './url'; + export type { JobId, BaseParams, BaseParamsV2, BasePayload, BasePayloadV2 }; export interface ReportDocumentHead { @@ -148,3 +143,38 @@ export interface JobSummarySet { completed: JobSummary[]; failed: JobSummary[]; } + +interface BaseParamsPDFV2 { + layout: LayoutParams; + + /** + * This value is used to re-create the same visual state as when the report was requested as well as navigate to the correct page. + */ + locatorParams: LocatorParams[]; +} +export type JobParamsPDFV2 = BaseParamsPDFV2 & BaseParams; + +export type JobAppParamsPDFV2 = Omit; + +// Job payload: structure of stored job data provided by create_job +export interface TaskPayloadPDFV2 extends BasePayload, BaseParamsPDFV2 { + layout: LayoutParams; + /** + * The value of forceNow is injected server-side every time a given report is generated. + */ + forceNow: string; +} + +// Job params: structure of incoming user request data +export interface JobParamsPNGV2 extends BaseParams { + layout: LayoutParams; + /** + * This value is used to re-create the same visual state as when the report was requested as well as navigate to the correct page. + */ + locatorParams: LocatorParams; +} + +/** + * @deprecated + */ +export type JobAppParamsPDF = Omit; diff --git a/x-pack/plugins/reporting/kibana.jsonc b/x-pack/plugins/reporting/kibana.jsonc index a02db938c9ec3..d51b829d719c0 100644 --- a/x-pack/plugins/reporting/kibana.jsonc +++ b/x-pack/plugins/reporting/kibana.jsonc @@ -25,16 +25,16 @@ "screenshotting", "screenshotMode", "share", - "features" + "features", ], "optionalPlugins": [ "security", "spaces", - "usageCollection" + "usageCollection", ], "requiredBundles": [ "kibanaReact", - "discover" + "discover", ] } } diff --git a/x-pack/plugins/reporting/public/lib/reporting_api_client/hooks.ts b/x-pack/plugins/reporting/public/lib/reporting_api_client/hooks.ts index 0b697b333dddd..2981b083d5cd4 100644 --- a/x-pack/plugins/reporting/public/lib/reporting_api_client/hooks.ts +++ b/x-pack/plugins/reporting/public/lib/reporting_api_client/hooks.ts @@ -5,8 +5,8 @@ * 2.0. */ -import { useRequest, UseRequestResponse } from '../../shared_imports'; import { IlmPolicyStatusResponse } from '../../../common/types'; +import { useRequest, UseRequestResponse } from '../../shared_imports'; import { API_GET_ILM_POLICY_STATUS } from '../../../common/constants'; diff --git a/x-pack/plugins/reporting/public/lib/reporting_api_client/reporting_api_client.ts b/x-pack/plugins/reporting/public/lib/reporting_api_client/reporting_api_client.ts index 91abac38f4d66..91ba128d53b68 100644 --- a/x-pack/plugins/reporting/public/lib/reporting_api_client/reporting_api_client.ts +++ b/x-pack/plugins/reporting/public/lib/reporting_api_client/reporting_api_client.ts @@ -10,6 +10,13 @@ import { stringify } from 'query-string'; import rison from '@kbn/rison'; import type { HttpFetchQuery } from '@kbn/core/public'; import { HttpSetup, IUiSettingsClient } from '@kbn/core/public'; +import { + BaseParams, + ManagementLinkFn, + DownloadReportFn, + ReportApiJSON, + JobId, +} from '../../../common/types'; import { buildKibanaPath } from '../../../common/build_kibana_path'; import { API_BASE_GENERATE, @@ -20,13 +27,6 @@ import { getRedirectAppPath, REPORTING_MANAGEMENT_HOME, } from '../../../common/constants'; -import { - BaseParams, - DownloadReportFn, - JobId, - ManagementLinkFn, - ReportApiJSON, -} from '../../../common/types'; import { add } from '../../notifier/job_completion_notifications'; import { Job } from '../job'; diff --git a/x-pack/plugins/reporting/public/plugin.ts b/x-pack/plugins/reporting/public/plugin.ts index d8f4132a59541..9a74f6cf9aab6 100644 --- a/x-pack/plugins/reporting/public/plugin.ts +++ b/x-pack/plugins/reporting/public/plugin.ts @@ -25,7 +25,6 @@ import type { HomePublicPluginSetup, HomePublicPluginStart } from '@kbn/home-plu import { ManagementSetup, ManagementStart } from '@kbn/management-plugin/public'; import { LicensingPluginStart } from '@kbn/licensing-plugin/public'; import { durationToNumber } from '../common/schema_utils'; -import { JobId, JobSummarySet } from '../common/types'; import { ReportingSetup, ReportingStart } from '.'; import { ReportingAPIClient } from './lib/reporting_api_client'; import { ReportingNotifierStreamHandler as StreamHandler } from './lib/stream_handler'; @@ -42,6 +41,7 @@ import { AppNavLinkStatus } from './shared_imports'; import { reportingCsvShareProvider } from './share_context_menu/register_csv_reporting'; import { reportingScreenshotShareProvider } from './share_context_menu/register_pdf_png_reporting'; import { JOB_COMPLETION_NOTIFICATIONS_SESSION_KEY } from '../common/constants'; +import { JobId, JobSummarySet } from '../common/types'; export interface ClientConfigType { poll: { jobsRefresh: { interval: number; intervalErrorMultiplier: number } }; diff --git a/x-pack/plugins/reporting/public/redirect/redirect_app.tsx b/x-pack/plugins/reporting/public/redirect/redirect_app.tsx index c7ce0b8d5b24f..4238578b0b4e0 100644 --- a/x-pack/plugins/reporting/public/redirect/redirect_app.tsx +++ b/x-pack/plugins/reporting/public/redirect/redirect_app.tsx @@ -14,8 +14,8 @@ import { EuiCallOut, EuiCodeBlock } from '@elastic/eui'; import type { ScopedHistory } from '@kbn/core/public'; import type { ScreenshotModePluginSetup } from '@kbn/screenshot-mode-plugin/public'; -import { REPORTING_REDIRECT_LOCATOR_STORE_KEY } from '../../common/constants'; import { LocatorParams } from '../../common/types'; +import { REPORTING_REDIRECT_LOCATOR_STORE_KEY } from '../../common/constants'; import { ReportingAPIClient } from '../lib/reporting_api_client'; import type { SharePluginSetup } from '../shared_imports'; diff --git a/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx b/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx index 1116652ab05f9..2e3e52fc7b1b8 100644 --- a/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx +++ b/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx @@ -53,7 +53,6 @@ export const reportingCsvShareProvider = ({ const licenseHasCsvReporting = licenseCheck.showLinks; const licenseDisabled = !licenseCheck.enableLinks; - // TODO: add abstractions in ExportTypeRegistry to use here? let capabilityHasCsvReporting = false; if (usesUiCapabilities) { capabilityHasCsvReporting = application.capabilities.discover?.generateCsv === true; diff --git a/x-pack/plugins/reporting/public/share_context_menu/reporting_panel_content/reporting_panel_content.tsx b/x-pack/plugins/reporting/public/share_context_menu/reporting_panel_content/reporting_panel_content.tsx index 6ac0e374b3919..1d67c384604c3 100644 --- a/x-pack/plugins/reporting/public/share_context_menu/reporting_panel_content/reporting_panel_content.tsx +++ b/x-pack/plugins/reporting/public/share_context_menu/reporting_panel_content/reporting_panel_content.tsx @@ -21,6 +21,7 @@ import React, { Component, ReactElement } from 'react'; import { IUiSettingsClient, ThemeServiceSetup, ToastsSetup } from '@kbn/core/public'; import url from 'url'; import { toMountPoint } from '@kbn/kibana-react-plugin/public'; +import { BaseParams } from '../../../common/types'; import { CSV_REPORT_TYPE, PDF_REPORT_TYPE, @@ -28,7 +29,6 @@ import { PNG_REPORT_TYPE, PNG_REPORT_TYPE_V2, } from '../../../common/constants'; -import { BaseParams } from '../../../common/types'; import { ReportingAPIClient } from '../../lib/reporting_api_client'; import { ErrorUnsavedWorkPanel, ErrorUrlTooLongPanel } from './components'; import { getMaxUrlLength } from './constants'; diff --git a/x-pack/plugins/reporting/server/core.ts b/x-pack/plugins/reporting/server/core.ts index 397c2c391d50b..4e9b0b41ea042 100644 --- a/x-pack/plugins/reporting/server/core.ts +++ b/x-pack/plugins/reporting/server/core.ts @@ -24,7 +24,7 @@ import { CoreKibanaRequest, ServiceStatusLevels } from '@kbn/core/server'; import type { PluginStart as DataPluginStart } from '@kbn/data-plugin/server'; import type { DiscoverServerPluginStart } from '@kbn/discover-plugin/server'; import type { PluginSetupContract as FeaturesPluginSetup } from '@kbn/features-plugin/server'; -import type { FieldFormatsStart } from '@kbn/field-formats-plugin/server'; +import { FieldFormatsStart } from '@kbn/field-formats-plugin/server'; import type { LicensingPluginStart } from '@kbn/licensing-plugin/server'; import { PdfScreenshotResult, @@ -71,12 +71,12 @@ export interface ReportingInternalStart { esClient: IClusterClient; data: DataPluginStart; discover: DiscoverServerPluginStart; - fieldFormats: FieldFormatsStart; licensing: LicensingPluginStart; logger: Logger; screenshotting: ScreenshottingStart; security?: SecurityPluginStart; taskManager: TaskManagerStartContract; + fieldFormats: FieldFormatsStart; } /** @@ -108,6 +108,7 @@ export class ReportingCore { this.getContract = () => ({ usesUiCapabilities: () => syncConfig.roles.enabled === false, + registerExportType: (id) => this.exportTypesRegistry.register(id), }); this.executing = new Set(); @@ -283,6 +284,9 @@ export class ReportingCore { return (await this.getPluginStartDeps()).store; } + /** + * License registry + */ public async getLicenseInfo() { const { license$ } = (await this.getPluginStartDeps()).licensing; const registry = this.getExportTypesRegistry(); diff --git a/x-pack/plugins/reporting/server/export_types/png/types.ts b/x-pack/plugins/reporting/server/export_types/png/types.ts deleted file mode 100644 index 3940f24b762a8..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/png/types.ts +++ /dev/null @@ -1,11 +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. - */ - -export type { - JobParamsPNGDeprecated, - TaskPayloadPNG, -} from '../../../common/types/export_types/png'; diff --git a/x-pack/plugins/reporting/server/export_types/png_v2/types.ts b/x-pack/plugins/reporting/server/export_types/png_v2/types.ts deleted file mode 100644 index ae5c80e32894a..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/png_v2/types.ts +++ /dev/null @@ -1,8 +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. - */ - -export type { JobParamsPNGV2, TaskPayloadPNGV2 } from '../../../common/types/export_types/png_v2'; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/types.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf/types.ts deleted file mode 100644 index ebf258f73a41f..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/types.ts +++ /dev/null @@ -1,11 +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. - */ - -export type { - JobParamsPDFDeprecated, - TaskPayloadPDF, -} from '../../../common/types/export_types/printable_pdf'; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/types.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/types.ts deleted file mode 100644 index b150d53984706..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/types.ts +++ /dev/null @@ -1,11 +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. - */ - -export type { - JobParamsPDFV2, - TaskPayloadPDFV2, -} from '../../../common/types/export_types/printable_pdf_v2'; diff --git a/x-pack/plugins/reporting/server/index.ts b/x-pack/plugins/reporting/server/index.ts index 8c715ee9df271..82e7f8c79cd91 100644 --- a/x-pack/plugins/reporting/server/index.ts +++ b/x-pack/plugins/reporting/server/index.ts @@ -22,5 +22,6 @@ export const plugin = (initContext: PluginInitializerContext { if (typeof encryptionKey !== 'string') { throw new Error('Encryption Key required.'); } return nodeCrypto({ encryptionKey }); -} +}; diff --git a/x-pack/plugins/reporting/server/lib/deprecations/check_ilm_migration_status.ts b/x-pack/plugins/reporting/server/lib/deprecations/check_ilm_migration_status.ts index 9f3872dfa6918..e516568412f1a 100644 --- a/x-pack/plugins/reporting/server/lib/deprecations/check_ilm_migration_status.ts +++ b/x-pack/plugins/reporting/server/lib/deprecations/check_ilm_migration_status.ts @@ -5,8 +5,8 @@ * 2.0. */ -import { ILM_POLICY_NAME } from '../../../common/constants'; import { IlmPolicyMigrationStatus } from '../../../common/types'; +import { ILM_POLICY_NAME } from '../../../common/constants'; import { IlmPolicyManager } from '../store/ilm_policy_manager'; import type { DeprecationsDependencies } from './types'; diff --git a/x-pack/plugins/reporting/server/lib/export_types_registry.ts b/x-pack/plugins/reporting/server/lib/export_types_registry.ts index 96456ea93926c..1dbfca79b5a8b 100644 --- a/x-pack/plugins/reporting/server/lib/export_types_registry.ts +++ b/x-pack/plugins/reporting/server/lib/export_types_registry.ts @@ -6,15 +6,8 @@ */ import { isString } from 'lodash'; -import { getExportType as getTypeCsvFromSavedObject } from '../export_types/csv_v2'; -import { getExportType as getTypeCsvFromSavedObjectImmediate } from '../export_types/csv_searchsource_immediate'; -import { getExportType as getTypeCsv } from '../export_types/csv_searchsource'; -import { getExportType as getTypePng } from '../export_types/png'; -import { getExportType as getTypePngV2 } from '../export_types/png_v2'; -import { getExportType as getTypePrintablePdf } from '../export_types/printable_pdf'; -import { getExportType as getTypePrintablePdfV2 } from '../export_types/printable_pdf_v2'; -import { CreateJobFn, ExportTypeDefinition } from '../types'; +import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../types'; type GetCallbackFn = (item: ExportTypeDefinition) => boolean; @@ -23,7 +16,7 @@ export class ExportTypesRegistry { constructor() {} - register(item: ExportTypeDefinition): void { + register(item: ExportTypeDefinition, RunTaskFn>): void { if (!isString(item.id)) { throw new Error(`'item' must have a String 'id' property `); } @@ -59,9 +52,10 @@ export class ExportTypesRegistry { } const foundResult: ExportTypeDefinition = value; - if (result) { - throw new Error('Found multiple items matching predicate.'); - } + // PDF works if this is commented out + // if (result) { + // throw new Error('Found multiple items matching predicate.'); + // } result = foundResult; } @@ -77,26 +71,11 @@ export class ExportTypesRegistry { // TODO: Define a 2nd ExportTypeRegistry instance for "immediate execute" report job types only. // It should not require a `CreateJobFn` for its ExportTypeDefinitions, which only makes sense for async. // Once that is done, the `any` types below can be removed. - /* * @return ExportTypeRegistry: the ExportTypeRegistry instance that should be * used to register async export type definitions */ export function getExportTypesRegistry(): ExportTypesRegistry { const registry = new ExportTypesRegistry(); - type CreateFnType = CreateJobFn; // can not specify params types because different type of params are not assignable to each other - type RunFnType = any; // can not specify because ImmediateExecuteFn is not assignable to RunTaskFn - const getTypeFns: Array<() => ExportTypeDefinition> = [ - getTypeCsv, - getTypeCsvFromSavedObject, - getTypeCsvFromSavedObjectImmediate, - getTypePng, - getTypePngV2, - getTypePrintablePdf, - getTypePrintablePdfV2, - ]; - getTypeFns.forEach((getType) => { - registry.register(getType()); - }); return registry; } diff --git a/x-pack/plugins/reporting/server/lib/index.ts b/x-pack/plugins/reporting/server/lib/index.ts index 36d310fcd131b..98b788e4c4502 100644 --- a/x-pack/plugins/reporting/server/lib/index.ts +++ b/x-pack/plugins/reporting/server/lib/index.ts @@ -8,9 +8,9 @@ export { checkLicense } from './check_license'; export { checkParamsVersion } from './check_params_version'; export { ContentStream, getContentStream } from './content_stream'; -export { cryptoFactory } from './crypto'; export { ExportTypesRegistry, getExportTypesRegistry } from './export_types_registry'; export { PassThroughStream } from './passthrough_stream'; export { statuses } from './statuses'; export { ReportingStore, IlmPolicyManager } from './store'; export { startTrace } from './trace'; +export { cryptoFactory } from './crypto'; diff --git a/x-pack/plugins/reporting/server/lib/store/index.ts b/x-pack/plugins/reporting/server/lib/store/index.ts index 125c592c8626b..330e3d03e293d 100644 --- a/x-pack/plugins/reporting/server/lib/store/index.ts +++ b/x-pack/plugins/reporting/server/lib/store/index.ts @@ -4,8 +4,6 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ - -export type { ReportDocument } from '../../../common/types'; export { Report } from './report'; export { SavedReport } from './saved_report'; export { ReportingStore } from './store'; diff --git a/x-pack/plugins/reporting/server/lib/store/report.ts b/x-pack/plugins/reporting/server/lib/store/report.ts index 6f23c23e9066a..5e76136317e46 100644 --- a/x-pack/plugins/reporting/server/lib/store/report.ts +++ b/x-pack/plugins/reporting/server/lib/store/report.ts @@ -8,14 +8,14 @@ import { omit } from 'lodash'; import moment from 'moment'; import Puid from 'puid'; -import { JOB_STATUSES } from '../../../common/constants'; import { - ReportApiJSON, ReportDocument, + ReportApiJSON, + ReportSource, ReportDocumentHead, ReportFields, - ReportSource, } from '../../../common/types'; +import { JOB_STATUSES } from '../../../common/constants'; import type { ReportTaskParams } from '../tasks'; export type { ReportDocument }; diff --git a/x-pack/plugins/reporting/server/lib/store/saved_report.ts b/x-pack/plugins/reporting/server/lib/store/saved_report.ts index c4d46c167a312..957b375a0fa07 100644 --- a/x-pack/plugins/reporting/server/lib/store/saved_report.ts +++ b/x-pack/plugins/reporting/server/lib/store/saved_report.ts @@ -5,8 +5,9 @@ * 2.0. */ -import { ReportDocumentHead, ReportSource } from '../../../common/types'; +import { ReportDocumentHead } from '../../../common/types'; import { Report } from '.'; +import { ReportSource } from './report'; /* * Class for a report document that is saved in Elasticsearch diff --git a/x-pack/plugins/reporting/server/lib/store/store.test.ts b/x-pack/plugins/reporting/server/lib/store/store.test.ts index f1400ab357ee9..3b1baed8c1a0f 100644 --- a/x-pack/plugins/reporting/server/lib/store/store.test.ts +++ b/x-pack/plugins/reporting/server/lib/store/store.test.ts @@ -8,7 +8,8 @@ import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { elasticsearchServiceMock, loggingSystemMock } from '@kbn/core/server/mocks'; import { ReportingCore } from '../..'; import { createMockConfigSchema, createMockReportingCore } from '../../test_helpers'; -import { Report, ReportDocument, ReportingStore, SavedReport } from '.'; +import { Report, ReportingStore, SavedReport } from '.'; +import { ReportDocument } from './report'; describe('ReportingStore', () => { const mockLogger = loggingSystemMock.createLogger(); diff --git a/x-pack/plugins/reporting/server/lib/store/store.ts b/x-pack/plugins/reporting/server/lib/store/store.ts index 883cd3d404590..0b1ab4d7570c0 100644 --- a/x-pack/plugins/reporting/server/lib/store/store.ts +++ b/x-pack/plugins/reporting/server/lib/store/store.ts @@ -8,17 +8,16 @@ import moment from 'moment'; import { IndexResponse, UpdateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { ElasticsearchClient, Logger } from '@kbn/core/server'; +import { ReportOutput, JobStatus } from '../../../common/types'; import { statuses } from '..'; import type { ReportingCore } from '../..'; import { ILM_POLICY_NAME, REPORTING_SYSTEM_INDEX } from '../../../common/constants'; -import type { JobStatus, ReportOutput, ReportSource } from '../../../common/types'; import type { ReportTaskParams } from '../tasks'; -import type { IReport, Report, ReportDocument } from '.'; -import { SavedReport } from '.'; +import { Report, ReportDocument, MIGRATION_VERSION, ReportSource } from './report'; +import { IReport, SavedReport } from '.'; import { IlmPolicyManager } from './ilm_policy_manager'; import { indexTimestamp } from './index_timestamp'; import { mapping } from './mapping'; -import { MIGRATION_VERSION } from './report'; /* * When an instance of Kibana claims a report job, this information tells us about that instance diff --git a/x-pack/plugins/reporting/server/lib/tasks/execute_report.ts b/x-pack/plugins/reporting/server/lib/tasks/execute_report.ts index bdff3fc6441d0..1542523c88617 100644 --- a/x-pack/plugins/reporting/server/lib/tasks/execute_report.ts +++ b/x-pack/plugins/reporting/server/lib/tasks/execute_report.ts @@ -25,14 +25,14 @@ import { KibanaShuttingDownError, TaskRunResult, } from '@kbn/reporting-common'; +import { ReportDocument, ReportOutput } from '../../../common/types'; import { mapToReportingError } from '../../../common/errors/map_to_reporting_error'; import { getContentStream } from '..'; import type { ReportingCore } from '../..'; import { durationToNumber, numberToDuration } from '../../../common/schema_utils'; -import type { ReportOutput } from '../../../common/types'; import type { ReportingConfigType } from '../../config'; import type { BasePayload, ExportTypeDefinition, RunTaskFn } from '../../types'; -import type { ReportDocument, ReportingStore } from '../store'; +import type { ReportingStore } from '../store'; import { Report, SavedReport } from '../store'; import type { ReportFailedFields, ReportProcessingFields } from '../store/store'; import { ReportingTask, ReportingTaskStatus, REPORTING_EXECUTE_TYPE, ReportTaskParams } from '.'; diff --git a/x-pack/plugins/reporting/server/lib/tasks/index.ts b/x-pack/plugins/reporting/server/lib/tasks/index.ts index f60bcefd73853..d33360053b69d 100644 --- a/x-pack/plugins/reporting/server/lib/tasks/index.ts +++ b/x-pack/plugins/reporting/server/lib/tasks/index.ts @@ -6,8 +6,8 @@ */ import { TaskRunCreatorFunction } from '@kbn/task-manager-plugin/server'; -import { ReportSource } from '../../../common/types'; import { BasePayload } from '../../types'; +import { ReportSource } from '../store/report'; export const REPORTING_EXECUTE_TYPE = 'report:execute'; export const REPORTING_MONITOR_TYPE = 'reports:monitor'; diff --git a/x-pack/plugins/reporting/server/plugin.ts b/x-pack/plugins/reporting/server/plugin.ts index ac340e5928ffe..04c50bb21f2d1 100644 --- a/x-pack/plugins/reporting/server/plugin.ts +++ b/x-pack/plugins/reporting/server/plugin.ts @@ -18,7 +18,6 @@ import { buildConfig, registerUiSettings, ReportingConfigType } from './config'; import { registerDeprecations } from './deprecations'; import { ReportingStore } from './lib'; import { registerRoutes } from './routes'; -import { setFieldFormats } from './services'; import type { ReportingRequestHandlerContext, ReportingSetup, @@ -96,7 +95,6 @@ export class ReportingPlugin const { elasticsearch, savedObjects, uiSettings } = core; // use fieldFormats plugin for csv formats - setFieldFormats(plugins.fieldFormats); const reportingCore = this.reportingCore!; // async background start diff --git a/x-pack/plugins/reporting/server/routes/deprecations/deprecations.ts b/x-pack/plugins/reporting/server/routes/deprecations/deprecations.ts index ac9cf8be2074b..176cc7a0eaaf3 100644 --- a/x-pack/plugins/reporting/server/routes/deprecations/deprecations.ts +++ b/x-pack/plugins/reporting/server/routes/deprecations/deprecations.ts @@ -6,13 +6,13 @@ */ import { errors } from '@elastic/elasticsearch'; import type { Logger, RequestHandler } from '@kbn/core/server'; +import { IlmPolicyStatusResponse } from '../../../common/types'; import { API_GET_ILM_POLICY_STATUS, API_MIGRATE_ILM_POLICY_URL, ILM_POLICY_NAME, } from '../../../common/constants'; -import type { IlmPolicyStatusResponse } from '../../../common/types'; -import type { ReportingCore } from '../../core'; +import { ReportingCore } from '../..'; import { IlmPolicyManager } from '../../lib'; import { deprecations } from '../../lib/deprecations'; import { getCounters } from '../lib'; diff --git a/x-pack/plugins/reporting/server/routes/generate/generate_from_jobparams.ts b/x-pack/plugins/reporting/server/routes/generate/generate_from_jobparams.ts index 373e72efb8bd0..5bab247a37a28 100644 --- a/x-pack/plugins/reporting/server/routes/generate/generate_from_jobparams.ts +++ b/x-pack/plugins/reporting/server/routes/generate/generate_from_jobparams.ts @@ -9,8 +9,8 @@ import { schema } from '@kbn/config-schema'; import type { Logger } from '@kbn/core/server'; import rison from '@kbn/rison'; import type { ReportingCore } from '../..'; -import { API_BASE_URL } from '../../../common/constants'; import type { BaseParams } from '../../types'; +import { API_BASE_URL } from '../../../common/constants'; import { authorizedUserPreRouting, getCounters, RequestHandler } from '../lib'; const BASE_GENERATE = `${API_BASE_URL}/generate`; diff --git a/x-pack/plugins/reporting/server/routes/generate/index.ts b/x-pack/plugins/reporting/server/routes/generate/index.ts index 210abee3e6606..2ab9f15173696 100644 --- a/x-pack/plugins/reporting/server/routes/generate/index.ts +++ b/x-pack/plugins/reporting/server/routes/generate/index.ts @@ -5,5 +5,4 @@ * 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'; diff --git a/x-pack/plugins/reporting/server/routes/index.ts b/x-pack/plugins/reporting/server/routes/index.ts index 570d74f3e02ab..20b028b2c4d35 100644 --- a/x-pack/plugins/reporting/server/routes/index.ts +++ b/x-pack/plugins/reporting/server/routes/index.ts @@ -6,19 +6,15 @@ */ import type { Logger } from '@kbn/core/server'; -import { ReportingCore } from '..'; +import { ReportingCore } from '../core'; import { registerDeprecationsRoutes } from './deprecations/deprecations'; -import { registerDiagnosticRoutes } from './diagnostic'; -import { - registerGenerateCsvFromSavedObjectImmediate, - registerJobGenerationRoutes, -} from './generate'; +import { registerJobGenerationRoutes } from './generate'; import { registerJobInfoRoutes } from './management'; export function registerRoutes(reporting: ReportingCore, logger: Logger) { registerDeprecationsRoutes(reporting, logger); - registerDiagnosticRoutes(reporting, logger); - registerGenerateCsvFromSavedObjectImmediate(reporting, logger); registerJobGenerationRoutes(reporting, logger); registerJobInfoRoutes(reporting); } + +export type { JobAppParamsPDF } from './lib'; diff --git a/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts b/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts index d4f6e4bf49ab0..263e76c6a16b7 100644 --- a/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts +++ b/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts @@ -9,8 +9,8 @@ import { RequestHandler, RouteMethod } from '@kbn/core/server'; import { AuthenticatedUser } from '@kbn/security-plugin/server'; import { i18n } from '@kbn/i18n'; import { ReportingCore } from '../../core'; -import { getUser } from './get_user'; import type { ReportingRequestHandlerContext } from '../../types'; +import { getUser } from './get_user'; const superuserRole = 'superuser'; diff --git a/x-pack/plugins/reporting/server/routes/lib/get_document_payload.test.ts b/x-pack/plugins/reporting/server/routes/lib/get_document_payload.test.ts index efe22f0111c63..519a1fe03e578 100644 --- a/x-pack/plugins/reporting/server/routes/lib/get_document_payload.test.ts +++ b/x-pack/plugins/reporting/server/routes/lib/get_document_payload.test.ts @@ -7,11 +7,11 @@ import { Readable } from 'stream'; import { CSV_JOB_TYPE, PDF_JOB_TYPE } from '../../../common/constants'; -import { ReportApiJSON } from '../../../common/types'; import { ContentStream, getContentStream, statuses } from '../../lib'; import { createMockConfigSchema, createMockReportingCore } from '../../test_helpers'; import { jobsQueryFactory } from './jobs_query'; import { getDocumentPayloadFactory } from './get_document_payload'; +import { ReportApiJSON } from '../../../common/types'; jest.mock('../../lib/content_stream'); jest.mock('./jobs_query'); 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 58f878e7a29d7..9f1a1225714c2 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 @@ -7,9 +7,9 @@ import { ResponseHeaders } from '@kbn/core-http-server'; import { Stream } from 'stream'; -import { ReportingCore } from '../..'; -import { CSV_JOB_TYPE, CSV_JOB_TYPE_DEPRECATED } from '../../../common/constants'; import { ReportApiJSON } from '../../../common/types'; +import { CSV_JOB_TYPE, CSV_JOB_TYPE_DEPRECATED } from '../../../common/constants'; +import { ReportingCore } from '../..'; import { getContentStream, statuses } from '../../lib'; import { ExportTypeDefinition } from '../../types'; import { jobsQueryFactory } from './jobs_query'; diff --git a/x-pack/plugins/reporting/server/routes/lib/index.ts b/x-pack/plugins/reporting/server/routes/lib/index.ts index 50f5653f894ff..21627fa745230 100644 --- a/x-pack/plugins/reporting/server/routes/lib/index.ts +++ b/x-pack/plugins/reporting/server/routes/lib/index.ts @@ -12,4 +12,5 @@ export { getCounters } from './get_counter'; export type { Counters } from './get_counter'; export { handleUnavailable, RequestHandler } from './request_handler'; +export type { JobParamsPDFDeprecated, JobAppParamsPDF } from './request_handler'; export { jobsQueryFactory } from './jobs_query'; diff --git a/x-pack/plugins/reporting/server/routes/lib/job_management_pre_routing.ts b/x-pack/plugins/reporting/server/routes/lib/job_management_pre_routing.ts index a443b6fc05bb3..cf5f978180c0a 100644 --- a/x-pack/plugins/reporting/server/routes/lib/job_management_pre_routing.ts +++ b/x-pack/plugins/reporting/server/routes/lib/job_management_pre_routing.ts @@ -8,10 +8,10 @@ import Boom from '@hapi/boom'; import { IKibanaResponse, kibanaResponseFactory } from '@kbn/core/server'; import { i18n } from '@kbn/i18n'; -import { jobsQueryFactory } from '.'; import { ReportingCore } from '../..'; import { ReportApiJSON } from '../../lib/store/report'; import { ReportingUser } from '../../types'; +import { jobsQueryFactory } from '.'; import type { Counters } from './get_counter'; /** 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 dee61b41de7be..a06afe60b3d10 100644 --- a/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts +++ b/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts @@ -10,9 +10,9 @@ import { errors } from '@elastic/elasticsearch'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { ElasticsearchClient } from '@kbn/core/server'; import { i18n } from '@kbn/i18n'; -import type { ReportingCore } from '../..'; +import { ReportSource, ReportApiJSON } from '../../../common/types'; import { REPORTING_SYSTEM_INDEX } from '../../../common/constants'; -import type { ReportApiJSON, ReportSource } from '../../../common/types'; +import type { ReportingCore } from '../..'; import { statuses } from '../../lib/statuses'; import { Report } from '../../lib/store'; import { runtimeFieldKeys, runtimeFields } from '../../lib/store/runtime_fields'; diff --git a/x-pack/plugins/reporting/server/routes/lib/request_handler.test.ts b/x-pack/plugins/reporting/server/routes/lib/request_handler.test.ts index 69fb16831d557..f09e5a75bae75 100644 --- a/x-pack/plugins/reporting/server/routes/lib/request_handler.test.ts +++ b/x-pack/plugins/reporting/server/routes/lib/request_handler.test.ts @@ -8,12 +8,11 @@ import { KibanaRequest, KibanaResponseFactory } from '@kbn/core/server'; import { coreMock, httpServerMock, loggingSystemMock } from '@kbn/core/server/mocks'; import { ReportingCore } from '../..'; -import { JobParamsPDFDeprecated, TaskPayloadPDF } from '../../export_types/printable_pdf/types'; import { Report, ReportingStore } from '../../lib/store'; import { ReportApiJSON } from '../../lib/store/report'; import { createMockConfigSchema, createMockReportingCore } from '../../test_helpers'; import { ReportingRequestHandlerContext, ReportingSetup } from '../../types'; -import { RequestHandler } from './request_handler'; +import { JobParamsPDFDeprecated, RequestHandler, TaskPayloadPDF } from './request_handler'; jest.mock('../../lib/crypto', () => ({ cryptoFactory: () => ({ @@ -125,7 +124,7 @@ describe('Handle request to generate', () => { "timeout": undefined, } `); - const { forceNow, ...snapPayload } = payload as TaskPayloadPDF; + const { forceNow, ...snapPayload } = payload as unknown as TaskPayloadPDF; expect(snapPayload).toMatchInlineSnapshot(` Object { "browserTimezone": "UTC", diff --git a/x-pack/plugins/reporting/server/routes/lib/request_handler.ts b/x-pack/plugins/reporting/server/routes/lib/request_handler.ts index 0e0eba2a26ab8..5aa570896add5 100644 --- a/x-pack/plugins/reporting/server/routes/lib/request_handler.ts +++ b/x-pack/plugins/reporting/server/routes/lib/request_handler.ts @@ -9,11 +9,17 @@ import moment from 'moment'; import Boom from '@hapi/boom'; import { i18n } from '@kbn/i18n'; import type { KibanaRequest, KibanaResponseFactory, Logger } from '@kbn/core/server'; +import { LayoutParams } from '@kbn/screenshotting-plugin/common'; import type { ReportingCore } from '../..'; import { API_BASE_URL } from '../../../common/constants'; import { checkParamsVersion, cryptoFactory } from '../../lib'; import { Report } from '../../lib/store'; -import type { BaseParams, ReportingRequestHandlerContext, ReportingUser } from '../../types'; +import type { + BaseParams, + BasePayload, + ReportingRequestHandlerContext, + ReportingUser, +} from '../../types'; import { Counters } from './get_counter'; export const handleUnavailable = (res: KibanaResponseFactory) => { @@ -183,3 +189,30 @@ export class RequestHandler { }); } } + +interface BaseParamsPDF { + layout: LayoutParams; + relativeUrls: string[]; + isDeprecated?: boolean; +} + +// Job params: structure of incoming user request data, after being parsed from RISON + +/** + * @deprecated + */ +export type JobAppParamsPDF = Omit; + +/** + * Structure of stored job data provided by create_job + */ +export interface TaskPayloadPDF extends BasePayload { + layout: LayoutParams; + forceNow?: string; + objects: Array<{ relativeUrl: string }>; +} + +/** + * @deprecated + */ +export type JobParamsPDFDeprecated = BaseParamsPDF & BaseParams; diff --git a/x-pack/plugins/reporting/server/routes/management/integration_tests/jobs.test.ts b/x-pack/plugins/reporting/server/routes/management/integration_tests/jobs.test.ts index e5b326df56f56..19591bd43ab74 100644 --- a/x-pack/plugins/reporting/server/routes/management/integration_tests/jobs.test.ts +++ b/x-pack/plugins/reporting/server/routes/management/integration_tests/jobs.test.ts @@ -15,7 +15,7 @@ import { licensingMock } from '@kbn/licensing-plugin/server/mocks'; import { BehaviorSubject } from 'rxjs'; import { Readable } from 'stream'; import supertest from 'supertest'; -import { ReportingCore } from '../../..'; +import type { ReportingCore } from '../../..'; import { ReportingInternalSetup, ReportingInternalStart } from '../../../core'; import { ContentStream, ExportTypesRegistry, getContentStream } from '../../../lib'; import { @@ -24,7 +24,7 @@ import { createMockPluginStart, createMockReportingCore, } from '../../../test_helpers'; -import { ExportTypeDefinition, ReportingRequestHandlerContext } from '../../../types'; +import { CreateJobFn, ExportTypeDefinition, ReportingRequestHandlerContext } from '../../../types'; import { registerJobInfoRoutes } from '../jobs'; type SetupServerReturn = Awaited>; @@ -55,7 +55,7 @@ describe('GET /api/reporting/jobs/download', () => { httpSetup.registerRouteHandlerContext( reportingSymbol, 'reporting', - () => ({ usesUiCapabilities: jest.fn() }) + () => ({ usesUiCapabilities: jest.fn(), registerExportType: jest.fn() }) ); mockSetupDeps = createMockPluginSetup({ @@ -88,14 +88,14 @@ describe('GET /api/reporting/jobs/download', () => { jobType: 'unencodedJobType', jobContentExtension: 'csv', validLicenses: ['basic', 'gold'], - } as ExportTypeDefinition); + } as ExportTypeDefinition); exportTypesRegistry.register({ id: 'base64Encoded', jobType: 'base64EncodedJobType', jobContentEncoding: 'base64', jobContentExtension: 'pdf', validLicenses: ['basic', 'gold'], - } as ExportTypeDefinition); + } as ExportTypeDefinition); core.getExportTypesRegistry = () => exportTypesRegistry; mockEsClient = (await core.getEsClient()).asInternalUser as typeof mockEsClient; diff --git a/x-pack/plugins/reporting/server/test_helpers/create_mock_reportingplugin.ts b/x-pack/plugins/reporting/server/test_helpers/create_mock_reportingplugin.ts index 4c1d28e75ba15..c158c63d1c753 100644 --- a/x-pack/plugins/reporting/server/test_helpers/create_mock_reportingplugin.ts +++ b/x-pack/plugins/reporting/server/test_helpers/create_mock_reportingplugin.ts @@ -19,8 +19,6 @@ import { } from '@kbn/core/server/mocks'; import { dataPluginMock } from '@kbn/data-plugin/server/mocks'; import { discoverPluginMock } from '@kbn/discover-plugin/server/mocks'; -import { FieldFormatsRegistry } from '@kbn/field-formats-plugin/common'; -import { fieldFormatsMock } from '@kbn/field-formats-plugin/common/mocks'; import { DeepPartial } from 'utility-types'; import { featuresPluginMock } from '@kbn/features-plugin/server/mocks'; import { licensingMock } from '@kbn/licensing-plugin/server/mocks'; @@ -31,7 +29,6 @@ import { ReportingConfig, ReportingCore } from '..'; import { buildConfig, ReportingConfigType } from '../config'; import { ReportingInternalSetup, ReportingInternalStart } from '../core'; import { ReportingStore } from '../lib'; -import { setFieldFormats } from '../services'; export const createMockPluginSetup = ( setupMock: Partial> @@ -69,7 +66,7 @@ export const createMockPluginStart = async ( uiSettings: { asScopedToClient: () => ({ get: jest.fn() }) }, discover: discoverPluginMock.createStartContract(), data: dataPluginMock.createStartContract(), - fieldFormats: () => Promise.resolve(fieldFormatsMock), + // fieldFormats: () => Promise.resolve(fieldFormatsMock), store: await createMockReportingStore(config), taskManager: { schedule: jest.fn().mockImplementation(() => ({ id: 'taskId' })), @@ -162,12 +159,12 @@ export const createMockReportingCore = async ( await core.pluginStart(startDepsMock); await core.pluginStartsUp(); - setFieldFormats({ - fieldFormatServiceFactory() { - const fieldFormatsRegistry = new FieldFormatsRegistry(); - return Promise.resolve(fieldFormatsRegistry); - }, - }); + // setFieldFormats({ + // fieldFormatServiceFactory() { + // const fieldFormatsRegistry = new FieldFormatsRegistry(); + // return Promise.resolve(fieldFormatsRegistry); + // }, + // }); return core; }; diff --git a/x-pack/plugins/reporting/server/types.ts b/x-pack/plugins/reporting/server/types.ts index e0d60931b30bf..7c531721915ed 100644 --- a/x-pack/plugins/reporting/server/types.ts +++ b/x-pack/plugins/reporting/server/types.ts @@ -9,7 +9,6 @@ import type { CustomRequestHandlerContext, IRouter, KibanaRequest, Logger } from import type { DataPluginStart } from '@kbn/data-plugin/server/plugin'; import { DiscoverServerPluginStart } from '@kbn/discover-plugin/server'; import type { PluginSetupContract as FeaturesPluginSetup } from '@kbn/features-plugin/server'; -import { FieldFormatsStart } from '@kbn/field-formats-plugin/server'; import type { LicensingPluginStart } from '@kbn/licensing-plugin/server'; import type { ScreenshotModePluginSetup } from '@kbn/screenshot-mode-plugin/server'; import type { @@ -30,10 +29,12 @@ import type { import type { UsageCollectionSetup } from '@kbn/usage-collection-plugin/server'; import type { Writable } from 'stream'; import type { CancellationToken, TaskRunResult } from '@kbn/reporting-common'; -import type { BaseParams, BasePayload, UrlOrUrlLocatorTuple } from '../common/types'; +import { FieldFormatsStart } from '@kbn/field-formats-plugin/server'; import type { ReportingConfigType } from './config'; import type { ReportingCore } from './core'; import type { ReportTaskParams } from './lib/tasks'; +import { ExportTypesRegistry } from './lib'; +import { BaseParams, BasePayload, UrlOrUrlLocatorTuple } from '../common/types'; /** * Plugin Setup Contract @@ -43,6 +44,7 @@ export interface ReportingSetup { * Used to inform plugins if Reporting config is compatible with UI Capabilities / Application Sub-Feature Controls */ usesUiCapabilities: () => boolean; + registerExportType: ExportTypesRegistry['register']; } /** @@ -82,20 +84,6 @@ export type RunTaskFnFactory = ( logger: Logger ) => RunTaskFnType; -export interface ExportTypeDefinition< - CreateJobFnType = CreateJobFn | null, - RunTaskFnType = RunTaskFn -> { - id: string; - name: string; - jobType: string; - jobContentEncoding?: string; - jobContentExtension: string; - createJobFnFactory: CreateJobFnFactory | null; // immediate job does not have a "create" phase - runTaskFnFactory: RunTaskFnFactory; - validLicenses: string[]; -} - export interface ReportingSetupDeps { features: FeaturesPluginSetup; screenshotMode: ScreenshotModePluginSetup; @@ -130,3 +118,14 @@ export interface PngScreenshotOptions extends Omit { + id: string; + name: string; + jobType: string; + jobContentEncoding?: string; + jobContentExtension: string; + createJobFnFactory: CreateJobFnFactory | null; // csv immediate job does not have a "create" phase + runTaskFnFactory: RunTaskFnFactory; + validLicenses: string[]; +} diff --git a/x-pack/plugins/reporting/server/usage/reporting_usage_collector.ts b/x-pack/plugins/reporting/server/usage/reporting_usage_collector.ts index c299f9d13b9a0..ca3e970aa975f 100644 --- a/x-pack/plugins/reporting/server/usage/reporting_usage_collector.ts +++ b/x-pack/plugins/reporting/server/usage/reporting_usage_collector.ts @@ -57,7 +57,6 @@ export function registerReportingUsageCollector( ); }; const collectionIsReady = reporting.pluginStartsUp.bind(reporting); - const collector = getReportingUsageCollector( usageCollection, getLicense, diff --git a/x-pack/plugins/reporting/tsconfig.json b/x-pack/plugins/reporting/tsconfig.json index a3725f831c1a1..08d85ab4d9c63 100644 --- a/x-pack/plugins/reporting/tsconfig.json +++ b/x-pack/plugins/reporting/tsconfig.json @@ -3,14 +3,13 @@ "compilerOptions": { "outDir": "target/types", }, - "include": ["common/**/*", "public/**/*", "server/**/*", "../../../typings/**/*"], + "include": ["common/**/*", "public/**/*", "server/**/*", "../../../typings/**/*", "../reporting_export_types/server/routes/generate/integration_tests", ], "kbn_references": [ "@kbn/core", "@kbn/data-plugin", "@kbn/discover-plugin", "@kbn/embeddable-plugin", "@kbn/kibana-react-plugin", - "@kbn/kibana-utils-plugin", "@kbn/management-plugin", "@kbn/screenshot-mode-plugin", "@kbn/share-plugin", @@ -33,11 +32,11 @@ "@kbn/task-manager-plugin", "@kbn/config", "@kbn/logging-mocks", - "@kbn/core-http-server", - "@kbn/core-test-helpers-test-utils", "@kbn/safer-lodash-set", "@kbn/generate-csv", "@kbn/reporting-common", + "@kbn/core-test-helpers-test-utils", + "@kbn/core-http-server", ], "exclude": [ "target/**/*", diff --git a/x-pack/plugins/reporting_export_types/.eslintrc.js b/x-pack/plugins/reporting_export_types/.eslintrc.js new file mode 100644 index 0000000000000..dcd9ea0d061e9 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/.eslintrc.js @@ -0,0 +1,9 @@ +require('@kbn/babel-register').install(); + +module.exports = { + root: true, + extends: ['@kbn/eslint-config', 'plugin:@elastic/eui/recommended'], + rules: { + '@kbn/eslint/require-license-header': 'off', + }, +}; diff --git a/x-pack/plugins/reporting_export_types/.gitignore b/x-pack/plugins/reporting_export_types/.gitignore new file mode 100644 index 0000000000000..d2e696e8096a8 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/.gitignore @@ -0,0 +1,3 @@ +/build +/target +config/kibana.yml \ No newline at end of file diff --git a/x-pack/plugins/reporting_export_types/README.md b/x-pack/plugins/reporting_export_types/README.md new file mode 100755 index 0000000000000..888245a5fd560 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/README.md @@ -0,0 +1,14 @@ +## Summary + +There are three constructs that interact: the `ReportingPlugin`, the `ExportTypesPlugin` and the `ExportTypesRegistry`. + +`ReportingExportTypesPlugin` on setup() creates the `export_type_definitions`. The export type definitions can be one of the following: +- CSVExportTypeDefinition +- PNGExportTypeDefinition +- PDFExportTypeDefinition + +The `ReportingPlugin` creates an instance of the `ExportTypeRegistry` and exposes its `registerExportType()` to other plugins, which `ReportingExportTypesPlugin` uses to register all of the export types. The `ReportingPlugin` uses the getExportType() method to use the registered export types for exporting. + +### Problems this solves + +The `ExportTypesPlugin` allows reporting to create its `ExportTypeRegistry`. This registry can be referenced in UI facing points of reporting can be enabled or disabled. \ No newline at end of file diff --git a/x-pack/plugins/reporting/common/types/export_types/csv_searchsource.ts b/x-pack/plugins/reporting_export_types/common/csv_searchsource.ts similarity index 87% rename from x-pack/plugins/reporting/common/types/export_types/csv_searchsource.ts rename to x-pack/plugins/reporting_export_types/common/csv_searchsource.ts index 9943deb642e88..d551783d54f43 100644 --- a/x-pack/plugins/reporting/common/types/export_types/csv_searchsource.ts +++ b/x-pack/plugins/reporting_export_types/common/csv_searchsource.ts @@ -6,7 +6,7 @@ */ import type { SerializedSearchSourceFields } from '@kbn/data-plugin/common'; -import type { BaseParams, BasePayload } from '../base'; +import { BaseParams, BasePayload } from '@kbn/reporting-plugin/common/types'; interface BaseParamsCSV { searchSource: SerializedSearchSourceFields; diff --git a/x-pack/plugins/reporting/common/types/export_types/csv_searchsource_immediate.ts b/x-pack/plugins/reporting_export_types/common/csv_searchsource_immediate.ts similarity index 100% rename from x-pack/plugins/reporting/common/types/export_types/csv_searchsource_immediate.ts rename to x-pack/plugins/reporting_export_types/common/csv_searchsource_immediate.ts diff --git a/x-pack/plugins/reporting/common/types/export_types/csv_v2.ts b/x-pack/plugins/reporting_export_types/common/csv_v2.ts similarity index 88% rename from x-pack/plugins/reporting/common/types/export_types/csv_v2.ts rename to x-pack/plugins/reporting_export_types/common/csv_v2.ts index f56295ca651d5..3ba1032a0ec61 100644 --- a/x-pack/plugins/reporting/common/types/export_types/csv_v2.ts +++ b/x-pack/plugins/reporting_export_types/common/csv_v2.ts @@ -5,7 +5,8 @@ * 2.0. */ -import type { BaseParamsV2, BasePayloadV2 } from '..'; +import { BaseParamsV2, BasePayloadV2 } from '@kbn/reporting-plugin/common/types'; + interface CsvFromSavedObjectBase { objectType: 'search'; } diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/types.ts b/x-pack/plugins/reporting_export_types/common/index.ts similarity index 59% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/types.ts rename to x-pack/plugins/reporting_export_types/common/index.ts index f5c25207c78fa..0ce21b5e07a5d 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/types.ts +++ b/x-pack/plugins/reporting_export_types/common/index.ts @@ -5,8 +5,6 @@ * 2.0. */ -export type { - FakeRequest, - JobParamsDownloadCSV, - SavedObjectServiceError, -} from '../../../common/types/export_types/csv_searchsource_immediate'; +export type { JobParamsPNGDeprecated } from './png'; +export type { JobParamsCSV } from './csv_searchsource'; +export type { JobParamsCsvFromSavedObject } from './csv_v2'; diff --git a/x-pack/plugins/reporting/common/types/export_types/png.ts b/x-pack/plugins/reporting_export_types/common/png.ts similarity index 89% rename from x-pack/plugins/reporting/common/types/export_types/png.ts rename to x-pack/plugins/reporting_export_types/common/png.ts index 4a5367c754f4c..63132ac3f57bc 100644 --- a/x-pack/plugins/reporting/common/types/export_types/png.ts +++ b/x-pack/plugins/reporting_export_types/common/png.ts @@ -5,8 +5,8 @@ * 2.0. */ +import { BaseParams, BasePayload } from '@kbn/reporting-plugin/common/types/base'; import type { LayoutParams } from '@kbn/screenshotting-plugin/common'; -import type { BaseParams, BasePayload } from '../base'; interface BaseParamsPNG { layout: LayoutParams; diff --git a/x-pack/plugins/reporting/common/types/export_types/png_v2.ts b/x-pack/plugins/reporting_export_types/common/png_v2.ts similarity index 61% rename from x-pack/plugins/reporting/common/types/export_types/png_v2.ts rename to x-pack/plugins/reporting_export_types/common/png_v2.ts index ff3ff5a692edb..bd2c56e3351e1 100644 --- a/x-pack/plugins/reporting/common/types/export_types/png_v2.ts +++ b/x-pack/plugins/reporting_export_types/common/png_v2.ts @@ -5,18 +5,8 @@ * 2.0. */ +import { LocatorParams, BasePayload } from '@kbn/reporting-plugin/common/types'; import type { LayoutParams } from '@kbn/screenshotting-plugin/common'; -import type { LocatorParams } from '../url'; -import type { BaseParams, BasePayload } from '../base'; - -// Job params: structure of incoming user request data -export interface JobParamsPNGV2 extends BaseParams { - layout: LayoutParams; - /** - * This value is used to re-create the same visual state as when the report was requested as well as navigate to the correct page. - */ - locatorParams: LocatorParams; -} // Job payload: structure of stored job data provided by create_job export interface TaskPayloadPNGV2 extends BasePayload { diff --git a/x-pack/plugins/reporting_export_types/jest.config.js b/x-pack/plugins/reporting_export_types/jest.config.js new file mode 100644 index 0000000000000..313d22e12e612 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/jest.config.js @@ -0,0 +1,18 @@ +/* + * 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. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../..', + roots: ['/x-pack/plugins/reporting_export_types'], + coverageDirectory: '/target/kibana-coverage/jest/x-pack/plugins/reporting_export_types', + coverageReporters: ['text', 'html'], + collectCoverageFrom: [ + '/x-pack/plugins/reporting_export_types/{common,server}/**/**/**/*.{js,ts,tsx}', + '/x-pack/plugins/reporting_export_types/server/routes/diagnostic/integration_tests/*.{js,ts,tsx}', + ], +}; diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/types.ts b/x-pack/plugins/reporting_export_types/jest.integration.config.js similarity index 63% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource/types.ts rename to x-pack/plugins/reporting_export_types/jest.integration.config.js index 1fef8eb47a8c9..d4ba31f45a2ec 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/types.ts +++ b/x-pack/plugins/reporting_export_types/jest.integration.config.js @@ -5,7 +5,8 @@ * 2.0. */ -export type { - JobParamsCSV, - TaskPayloadCSV, -} from '../../../common/types/export_types/csv_searchsource'; +module.exports = { + preset: '@kbn/test/jest_integration', + rootDir: '../../..', + roots: ['/x-pack/plugins/reporting_export_types'], +}; diff --git a/x-pack/plugins/reporting_export_types/kibana.jsonc b/x-pack/plugins/reporting_export_types/kibana.jsonc new file mode 100644 index 0000000000000..44e4fb9b8078e --- /dev/null +++ b/x-pack/plugins/reporting_export_types/kibana.jsonc @@ -0,0 +1,17 @@ +{ + "type": "plugin", + "id": "@kbn/reporting-export-types", + "owner": "@elastic/appex-sharedux", + "plugin": { + "id": "reportingExportTypes", + "server": true, + "browser": false, + "configPath": [ + "xpack", + "reporting" + ], + "requiredPlugins": ["reporting"], + "optionalPlugins": [], + "requiredBundles": [], + }, +} diff --git a/x-pack/plugins/reporting_export_types/package.json b/x-pack/plugins/reporting_export_types/package.json new file mode 100644 index 0000000000000..59a9a1617b5b9 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/package.json @@ -0,0 +1,12 @@ +{ + "name": "@kbn/reporting-export-types", + "version": "1.0.0", + "license": "Elastic License 2.0", + "private": true, + "scripts": { + "build": "yarn plugin-helpers build", + "dev": "yarn plugin-helpers dev", + "plugin-helpers": "node ../../scripts/plugin_helpers", + "kbn": "node ../../scripts/kbn" + } +} diff --git a/x-pack/plugins/reporting_export_types/server/core.ts b/x-pack/plugins/reporting_export_types/server/core.ts new file mode 100644 index 0000000000000..d4360d6a6a3c2 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/core.ts @@ -0,0 +1,232 @@ +/* + * 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 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { + DocLinksServiceSetup, + IClusterClient, + IRouter, + KibanaRequest, + Logger, + PluginInitializerContext, + SavedObjectsClientContract, + UiSettingsServiceStart, +} from '@kbn/core/server'; +import { DataPluginStart } from '@kbn/data-plugin/server/plugin'; +import { DiscoverServerPluginStart } from '@kbn/discover-plugin/server'; +import { LicensingPluginStart } from '@kbn/licensing-plugin/server'; +import { REPORTING_REDIRECT_LOCATOR_STORE_KEY } from '@kbn/reporting-plugin/common/constants'; +import { ReportingConfig } from '@kbn/reporting-plugin/server'; +import { ReportingConfigType } from '@kbn/reporting-plugin/server/config/schema'; +import { checkLicense, ExportTypesRegistry } from '@kbn/reporting-plugin/server/lib'; +import { reportingEventLoggerFactory } from '@kbn/reporting-plugin/server/lib/event_logger/logger'; +import { IReport, ReportingStore } from '@kbn/reporting-plugin/server/lib/store'; +import { ReportTaskParams } from '@kbn/reporting-plugin/server/lib/tasks'; +import { + PdfScreenshotOptions, + PdfScreenshotResult, + PngScreenshotOptions, + PngScreenshotResult, + ScreenshotOptions, + ScreenshottingStart, +} from '@kbn/screenshotting-plugin/server'; +import { SecurityPluginSetup, SecurityPluginStart } from '@kbn/security-plugin/server'; +import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common'; +import { SpacesPluginSetup } from '@kbn/spaces-plugin/server'; +import { UsageCounter } from '@kbn/usage-collection-plugin/server'; +import * as Rx from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import { ExecuteReportTask } from './routes/lib/execute_report'; + +export interface ReportingExportTypesSetupDeps { + spaces?: SpacesPluginSetup; + docLinks: DocLinksServiceSetup; + router: IRouter; + security?: SecurityPluginSetup; + usageCounter?: UsageCounter; + logger: Logger; + exportTypesRegistry: ExportTypesRegistry; +} + +export interface ReportingExportTypesStartDeps { + licensing: LicensingPluginStart; + store: ReportingStore; + esClient: IClusterClient; + data: DataPluginStart; + logger: Logger; + security?: SecurityPluginStart; + uiSettings: UiSettingsServiceStart; + screenshotting: ScreenshottingStart; + discover: DiscoverServerPluginStart; +} + +export class ReportingExportTypesCore { + private pluginSetupDeps?: ReportingExportTypesSetupDeps; + private pluginStartDeps?: ReportingExportTypesStartDeps; + private readonly pluginSetup$ = new Rx.ReplaySubject(); // observe async background setupDeps and config each are done + private readonly pluginStart$ = new Rx.ReplaySubject(); // observe async background startDeps + private deprecatedAllowedRoles: false | string[] = false; // DEPRECATED. If `false`, the deprecated features have been disableed + private executeTask: ExecuteReportTask; + private executing: Set; + private kibanaShuttingDown$ = new Rx.ReplaySubject(1); + private config?: ReportingConfigType; + + constructor(private logger: Logger, context: PluginInitializerContext) { + // this.packageInfo = context.env.packageInfo; + const syncConfig = context.config.get(); + this.executeTask = new ExecuteReportTask(this, syncConfig, this.logger); + + this.executing = new Set(); + } + + /* + * Gives synchronous access to the setupDeps + */ + public getPluginSetupDeps() { + if (!this.pluginSetupDeps) { + throw new Error(`"pluginSetupDeps" dependencies haven't initialized yet`); + } + return this.pluginSetupDeps; + } + + /* + * Gives async access to the startDeps + */ + public async getPluginStartDeps() { + if (this.pluginStartDeps) { + return this.pluginStartDeps; + } + + return await Rx.firstValueFrom(this.pluginStart$); + } + /* + * If deprecated feature has not been disabled, + * this returns an array of allowed role names + * that have access to Reporting. + */ + public getDeprecatedAllowedRoles(): string[] | false { + return this.deprecatedAllowedRoles; + } + + /* + * + * Track usage of code paths for telemetry + */ + public getUsageCounter(): UsageCounter | undefined { + return this.pluginSetupDeps?.usageCounter; + } + + public getEventLogger(report: IReport, task?: { id: string }) { + const ReportingEventLogger = reportingEventLoggerFactory(this.logger); + return new ReportingEventLogger(report, task); + } + + public getConfig(): ReportingConfig { + if (!this.config) { + throw new Error('Config is not yet initialized'); + } + return this.config as unknown as ReportingConfig; + } + + public async getDataService() { + const startDeps = await this.getPluginStartDeps(); + return startDeps.data; + } + + public async getUiSettingsServiceFactory(savedObjectsClient: SavedObjectsClientContract) { + const { uiSettings: uiSettingsService } = await this.getPluginStartDeps(); + const scopedUiSettingsService = uiSettingsService.asScopedToClient(savedObjectsClient); + return scopedUiSettingsService; + } + + public async getEsClient() { + const startDeps = await this.getPluginStartDeps(); + return startDeps.esClient; + } + + public async getStore() { + return (await this.getPluginStartDeps()).store; + } + + public getSpaceId(request: KibanaRequest, logger = this.logger): string | undefined { + const spacesService = this.getPluginSetupDeps().spaces?.spacesService; + if (spacesService) { + const spaceId = spacesService?.getSpaceId(request); + + if (spaceId !== DEFAULT_SPACE_ID) { + logger.info(`Request uses Space ID: ${spaceId}`); + return spaceId; + } else { + logger.debug(`Request uses default Space`); + } + } + } + + public async scheduleTask(report: ReportTaskParams) { + return await this.executeTask.scheduleTask(report); + } + + public getExportTypesRegistry() { + return this.getPluginSetupDeps().exportTypesRegistry; + } + + public countConcurrentReports(): number { + return this.executing.size; + } + + public trackReport(reportId: string) { + this.executing.add(reportId); + } + + public untrackReport(reportId: string) { + this.executing.delete(reportId); + } + + public getKibanaShutdown$(): Rx.Observable { + return this.kibanaShuttingDown$.pipe(take(1)); + } + + /* + * Allows config to be set in the background + */ + public setConfig(config: ReportingConfig) { + // @ts-ignore + this.config = config; + this.pluginSetup$.next(true); + } + + /** + * License registry + */ + public async getLicenseInfo() { + const { license$ } = (await this.getPluginStartDeps()).licensing; + const registry = this.getExportTypesRegistry(); + + return await Rx.firstValueFrom( + license$.pipe(map((license: any) => checkLicense(registry, license))) + ); + } + + public getScreenshots(options: PdfScreenshotOptions): Rx.Observable; + public getScreenshots(options: PngScreenshotOptions): Rx.Observable; + public getScreenshots( + options: PngScreenshotOptions | PdfScreenshotOptions + ): Rx.Observable { + return Rx.defer(() => this.getPluginStartDeps()).pipe( + Rx.switchMap(({ screenshotting }) => { + return screenshotting.getScreenshots({ + ...options, + urls: options.urls!.map((url) => + typeof url === 'string' + ? url + : [url[0], { [REPORTING_REDIRECT_LOCATOR_STORE_KEY]: url[1] }] + ), + } as ScreenshotOptions); + }) + ); + } +} diff --git a/x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/decrypt_job_headers.test.ts similarity index 95% rename from x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/decrypt_job_headers.test.ts index a65be580adca3..d95aea8bb2f77 100644 --- a/x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/decrypt_job_headers.test.ts @@ -6,7 +6,7 @@ */ import { loggingSystemMock } from '@kbn/core/server/mocks'; -import { cryptoFactory } from '../../lib'; +import { cryptoFactory } from '@kbn/reporting-plugin/server/lib'; import { decryptJobHeaders } from '.'; const logger = loggingSystemMock.createLogger(); diff --git a/x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/decrypt_job_headers.ts similarity index 63% rename from x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/decrypt_job_headers.ts index 13b8b4804e6fb..6720441626f47 100644 --- a/x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/decrypt_job_headers.ts @@ -7,7 +7,7 @@ import { i18n } from '@kbn/i18n'; import type { Logger } from '@kbn/core/server'; -import { cryptoFactory } from '../../lib'; +import { cryptoFactory } from '@kbn/reporting-plugin/server/lib'; export const decryptJobHeaders = async ( encryptionKey: string | undefined, @@ -17,7 +17,7 @@ export const decryptJobHeaders = async ( try { if (typeof headers !== 'string') { throw new Error( - i18n.translate('xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage', { + i18n.translate('xpack.reportingExportTypes.missingJobHeadersErrorMessage', { defaultMessage: 'Job headers are missing', }) ); @@ -29,14 +29,11 @@ export const decryptJobHeaders = async ( logger.error(err); throw new Error( - i18n.translate( - 'xpack.reporting.exportTypes.common.failedToDecryptReportJobDataErrorMessage', - { - defaultMessage: - 'Failed to decrypt report job data. Please ensure that {encryptionKey} is set and re-generate this report. {err}', - values: { encryptionKey: 'xpack.reporting.encryptionKey', err: err.toString() }, - } - ) + i18n.translate('xpack.reportingExportTypes.failedToDecryptReportJobDataErrorMessage', { + defaultMessage: + 'Failed to decrypt report job data. Please ensure that {encryptionKey} is set and re-generate this report. {err}', + values: { encryptionKey: 'xpack.reportingExportTypes.encryptionKey', err: err.toString() }, + }) ); } }; diff --git a/x-pack/plugins/reporting/server/export_types/common/generate_png.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/generate_png.ts similarity index 86% rename from x-pack/plugins/reporting/server/export_types/common/generate_png.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/generate_png.ts index 328591a3056c3..b0c4fa64692e0 100644 --- a/x-pack/plugins/reporting/server/export_types/common/generate_png.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/generate_png.ts @@ -9,10 +9,10 @@ import apm from 'elastic-apm-node'; import type { Logger } from '@kbn/core/server'; import * as Rx from 'rxjs'; import { finalize, map, tap } from 'rxjs/operators'; -import type { ReportingCore } from '../..'; -import { REPORTING_TRANSACTION_TYPE } from '../../../common/constants'; -import type { PngMetrics } from '../../../common/types'; -import type { PngScreenshotOptions } from '../../types'; +import { REPORTING_TRANSACTION_TYPE } from '@kbn/reporting-plugin/common/constants'; +import type { PngScreenshotOptions } from '@kbn/reporting-plugin/server/types'; +import { PngMetrics } from '@kbn/reporting-common/metrics'; +import { ReportingExportTypesCore } from '../../core'; interface PngResult { buffer: Buffer; @@ -21,7 +21,7 @@ interface PngResult { } export function generatePngObservable( - reporting: ReportingCore, + reporting: ReportingExportTypesCore, logger: Logger, options: Omit ): Rx.Observable { diff --git a/x-pack/plugins/reporting/server/export_types/common/get_custom_logo.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/get_custom_logo.test.ts similarity index 87% rename from x-pack/plugins/reporting/server/export_types/common/get_custom_logo.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/get_custom_logo.test.ts index 99fa554b4f400..e711a097169b9 100644 --- a/x-pack/plugins/reporting/server/export_types/common/get_custom_logo.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/get_custom_logo.test.ts @@ -6,8 +6,11 @@ */ import { loggingSystemMock } from '@kbn/core/server/mocks'; -import { ReportingCore } from '../..'; -import { createMockConfigSchema, createMockReportingCore } from '../../test_helpers'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; +import { + createMockConfigSchema, + createMockReportingCore, +} from '@kbn/reporting-plugin/server/test_helpers'; import { getCustomLogo } from './get_custom_logo'; let mockReportingPlugin: ReportingCore; diff --git a/x-pack/plugins/reporting/server/export_types/common/get_custom_logo.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/get_custom_logo.ts similarity index 92% rename from x-pack/plugins/reporting/server/export_types/common/get_custom_logo.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/get_custom_logo.ts index c13bea2e95c2d..f7d831be3c8a8 100644 --- a/x-pack/plugins/reporting/server/export_types/common/get_custom_logo.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/get_custom_logo.ts @@ -7,7 +7,7 @@ import type { Headers, Logger } from '@kbn/core/server'; import { UI_SETTINGS_CUSTOM_PDF_LOGO } from '@kbn/reporting-common'; -import { ReportingCore } from '../..'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; export const getCustomLogo = async ( reporting: ReportingCore, diff --git a/x-pack/plugins/reporting/server/export_types/common/get_full_urls.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/get_full_urls.test.ts similarity index 95% rename from x-pack/plugins/reporting/server/export_types/common/get_full_urls.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/get_full_urls.test.ts index aae2a06a130eb..d8696178c3d28 100644 --- a/x-pack/plugins/reporting/server/export_types/common/get_full_urls.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/get_full_urls.test.ts @@ -5,10 +5,10 @@ * 2.0. */ -import { ReportingConfig } from '../..'; -import { createMockConfig } from '../../test_helpers'; -import { TaskPayloadPNG } from '../png/types'; -import { TaskPayloadPDF } from '../printable_pdf/types'; +import type { ReportingConfig } from '@kbn/reporting-plugin/server'; +import { createMockConfig } from '@kbn/reporting-plugin/server/test_helpers'; +import { TaskPayloadPDF } from '@kbn/reporting-plugin/server/routes/lib/request_handler'; +import { TaskPayloadPNG } from '../../../common/png'; import { getFullUrls } from './get_full_urls'; let mockConfig: ReportingConfig; diff --git a/x-pack/plugins/reporting/server/export_types/common/get_full_urls.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/get_full_urls.ts similarity index 92% rename from x-pack/plugins/reporting/server/export_types/common/get_full_urls.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/get_full_urls.ts index 069c882794ebd..1bdffe7b7b93b 100644 --- a/x-pack/plugins/reporting/server/export_types/common/get_full_urls.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/get_full_urls.ts @@ -11,10 +11,9 @@ import { UrlWithParsedQuery, UrlWithStringQuery, } from 'url'; -import { ReportingConfig } from '../..'; -import { TaskPayloadPNG } from '../png/types'; -import { TaskPayloadPDF } from '../printable_pdf/types'; -import { getAbsoluteUrlFactory } from './get_absolute_url'; +import { ReportingConfig, TaskPayloadPDF } from '@kbn/reporting-plugin/server'; +import { getAbsoluteUrlFactory } from '@kbn/reporting-plugin/common/get_absolute_url'; +import { TaskPayloadPNG } from '../../../common/png'; import { validateUrls } from './validate_urls'; function isPngJob(job: TaskPayloadPNG | TaskPayloadPDF): job is TaskPayloadPNG { diff --git a/x-pack/plugins/reporting/server/export_types/common/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/index.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/index.ts diff --git a/x-pack/plugins/reporting/server/export_types/common/pdf_tracker.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/pdf_tracker.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/pdf_tracker.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/pdf_tracker.ts diff --git a/x-pack/plugins/reporting_export_types/server/export_types/common/types.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/types.ts new file mode 100644 index 0000000000000..bb4fcebc4abf8 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/types.ts @@ -0,0 +1,54 @@ +/* + * 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 } from '@kbn/core-http-server'; +import { CancellationToken, TaskRunResult } from '@kbn/reporting-common'; +import { ReportingCore } from '@kbn/reporting-plugin/server'; +import { ReportTaskParams } from '@kbn/reporting-plugin/server/lib/tasks'; +import { BaseParams, BasePayload } from '@kbn/reporting-plugin/server/types'; +import type { Writable } from 'stream'; +import { Logger } from '@kbn/core/server'; +import { ReportingExportTypesCore } from '../../core'; +import { ReportingRequestHandlerContext } from '../../routes'; + +/** + * Internal Types + */ + +// default fn type for CreateJobFnFactory +export type CreateJobFn = ( + jobParams: JobParamsType, + context: ReportingRequestHandlerContext, + req: KibanaRequest +) => Promise>; + +// default fn type for RunTaskFnFactory +export type RunTaskFn = ( + jobId: string, + payload: ReportTaskParams['payload'], + cancellationToken: CancellationToken, + stream: Writable +) => Promise; +export type CreateJobFnFactory = ( + reporting: ReportingExportTypesCore | ReportingCore, + logger: Logger +) => CreateJobFnType; + +export type RunTaskFnFactory = ( + reporting: ReportingExportTypesCore | ReportingCore, + logger: Logger +) => RunTaskFnType; + +export interface ExportTypeDefinition { + id: string; + name: string; + jobType: string; + jobContentEncoding?: string; + jobContentExtension: string; + createJobFnFactory: CreateJobFnFactory | null; // csv immediate job does not have a "create" phase + runTaskFnFactory: RunTaskFnFactory; + validLicenses: string[]; +} diff --git a/x-pack/plugins/reporting/server/export_types/common/v2/get_full_redirect_app_url.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/v2/get_full_redirect_app_url.test.ts similarity index 93% rename from x-pack/plugins/reporting/server/export_types/common/v2/get_full_redirect_app_url.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/v2/get_full_redirect_app_url.test.ts index 69baf143156fd..b07bf8e90398f 100644 --- a/x-pack/plugins/reporting/server/export_types/common/v2/get_full_redirect_app_url.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/v2/get_full_redirect_app_url.test.ts @@ -6,7 +6,7 @@ */ import { get } from 'lodash'; -import { ReportingConfig } from '../../../config/config'; +import { ReportingConfig } from '@kbn/reporting-plugin/server/config/config'; import { getFullRedirectAppUrl } from './get_full_redirect_app_url'; describe('getFullRedirectAppUrl', () => { diff --git a/x-pack/plugins/reporting/server/export_types/common/v2/get_full_redirect_app_url.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/v2/get_full_redirect_app_url.ts similarity index 79% rename from x-pack/plugins/reporting/server/export_types/common/v2/get_full_redirect_app_url.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/v2/get_full_redirect_app_url.ts index 9c329db64fa1a..ec9e965446c5b 100644 --- a/x-pack/plugins/reporting/server/export_types/common/v2/get_full_redirect_app_url.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/common/v2/get_full_redirect_app_url.ts @@ -6,9 +6,9 @@ */ import { format } from 'url'; -import { ReportingConfig } from '../../..'; -import { getRedirectAppPath } from '../../../../common/constants'; -import { buildKibanaPath } from '../../../../common/build_kibana_path'; +import type { ReportingConfig } from '@kbn/reporting-plugin/server'; +import { getRedirectAppPath } from '@kbn/reporting-plugin/common/constants'; +import { buildKibanaPath } from '@kbn/reporting-plugin/common/build_kibana_path'; export function getFullRedirectAppUrl( config: ReportingConfig, diff --git a/x-pack/plugins/reporting/server/export_types/common/validate_urls.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/validate_urls.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/validate_urls.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/validate_urls.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/common/validate_urls.ts b/x-pack/plugins/reporting_export_types/server/export_types/common/validate_urls.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/validate_urls.ts rename to x-pack/plugins/reporting_export_types/server/export_types/common/validate_urls.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/create_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/create_job.ts similarity index 72% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource/create_job.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/create_job.ts index a2d89be1e0008..fd910b1fd3fa6 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/create_job.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/create_job.ts @@ -5,8 +5,9 @@ * 2.0. */ -import { CreateJobFn, CreateJobFnFactory } from '../../types'; -import { JobParamsCSV, TaskPayloadCSV } from './types'; +import { JobParamsCSV } from '../../../common'; +import { TaskPayloadCSV } from '../../../common/csv_searchsource'; +import { CreateJobFn, CreateJobFnFactory } from '../common/types'; export const createJobFnFactory: CreateJobFnFactory> = function createJobFactoryFn() { diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/execute_job.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/execute_job.test.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource/execute_job.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/execute_job.test.ts index dd59c07dc72c4..3beb072776849 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/execute_job.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/execute_job.test.ts @@ -19,10 +19,13 @@ jest.mock('@kbn/generate-csv', () => ({ import nodeCrypto from '@elastic/node-crypto'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { Writable } from 'stream'; -import { ReportingCore } from '../..'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; import { CancellationToken } from '@kbn/reporting-common'; -import { createMockConfigSchema, createMockReportingCore } from '../../test_helpers'; import { runTaskFnFactory } from './execute_job'; +import { + createMockConfigSchema, + createMockReportingCore, +} from '@kbn/reporting-plugin/server/test_helpers'; const logger = loggingSystemMock.createLogger(); const encryptionKey = 'tetkey'; diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/execute_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/execute_job.ts similarity index 89% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource/execute_job.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/execute_job.ts index 3c6b3c7e316e8..d96164ffb5d3a 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/execute_job.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/execute_job.ts @@ -6,10 +6,10 @@ */ import { CsvGenerator } from '@kbn/generate-csv'; -import { TaskPayloadCSV } from './types'; -import { getFieldFormats } from '../../services'; -import { RunTaskFn, RunTaskFnFactory } from '../../types'; +import type { RunTaskFn, RunTaskFnFactory } from '@kbn/reporting-plugin/server/types'; +import { TaskPayloadCSV } from '../../../common/csv_searchsource'; import { decryptJobHeaders } from '../common'; +import { getFieldFormats } from '../../services/services'; export const runTaskFnFactory: RunTaskFnFactory> = ( reporting, diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/index.ts similarity index 76% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/index.ts index 64c440b5a9ca2..9b70bca155cb7 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/index.ts @@ -4,21 +4,22 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ - +import type { CreateJobFn, RunTaskFn } from '@kbn/reporting-plugin/server/types'; import { - CSV_JOB_TYPE as jobType, - LICENSE_TYPE_BASIC, + LICENSE_TYPE_CLOUD_STANDARD, LICENSE_TYPE_ENTERPRISE, LICENSE_TYPE_GOLD, LICENSE_TYPE_PLATINUM, - LICENSE_TYPE_CLOUD_STANDARD, LICENSE_TYPE_TRIAL, -} from '../../../common/constants'; -import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../../types'; -import { createJobFnFactory } from './create_job'; + LICENSE_TYPE_BASIC, + CSV_JOB_TYPE as jobType, +} from '@kbn/reporting-plugin/common/constants'; +import { JobParamsCSV } from '../../../common'; +import { TaskPayloadCSV } from '../../../common/csv_searchsource'; import { runTaskFnFactory } from './execute_job'; import { metadata } from './metadata'; -import { JobParamsCSV, TaskPayloadCSV } from './types'; +import { createJobFnFactory } from './create_job'; +import { ExportTypeDefinition } from '../common/types'; export const getExportType = (): ExportTypeDefinition< CreateJobFn, diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/metadata.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/metadata.ts similarity index 82% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource/metadata.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/metadata.ts index 187d64d872a9d..e85234f970d21 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/metadata.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource/metadata.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { CSV_JOB_TYPE } from '../../../common/constants'; +import { CSV_JOB_TYPE } from '@kbn/reporting-plugin/common/constants'; export const metadata = { id: 'csv_searchsource', diff --git a/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/execute_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/execute_job.ts new file mode 100644 index 0000000000000..d7c76f0a5a4ab --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/execute_job.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { KibanaRequest } from '@kbn/core/server'; +import { Writable } from 'stream'; +import { CancellationToken, TaskRunResult } from '@kbn/reporting-common'; +import { CsvGenerator } from '@kbn/generate-csv'; +import type { + ReportingRequestHandlerContext, + RunTaskFnFactory, +} from '@kbn/reporting-plugin/server/types'; +import { JobParamsDownloadCSV } from '../../../common/csv_searchsource_immediate'; +import { getFieldFormats } from '../../services/services'; + +/* + * ImmediateExecuteFn receives the job doc payload because the payload was + * generated in the ScheduleFn + */ +export type ImmediateExecuteFn = ( + jobId: null, + job: JobParamsDownloadCSV, + context: ReportingRequestHandlerContext, + stream: Writable, + req: KibanaRequest +) => Promise; + +export const runTaskFnFactory: RunTaskFnFactory = function executeJobFactoryFn( + reporting, + parentLogger +) { + const config = reporting.getConfig().get('csv'); + const logger = parentLogger.get('execute-job'); + + return async function runTask(_jobId, immediateJobParams, context, stream, req) { + const job = { + objectType: 'immediate-search', + ...immediateJobParams, + }; + + const dataPluginStart = await reporting.getDataService(); + const savedObjectsClient = (await context.core).savedObjects.client; + const uiSettings = await reporting.getUiSettingsServiceFactory(savedObjectsClient); + const fieldFormatsRegistry = await getFieldFormats().fieldFormatServiceFactory(uiSettings); + + const [es, searchSourceStart] = await Promise.all([ + (await reporting.getEsClient()).asScoped(req), + await dataPluginStart.search.searchSource.asScoped(req), + ]); + const clients = { + uiSettings, + data: dataPluginStart.search.asScoped(req), + es, + }; + const dependencies = { + fieldFormatsRegistry, + searchSourceStart, + }; + const cancellationToken = new CancellationToken(); + + const csv = new CsvGenerator( + job, + config, + clients, + dependencies, + cancellationToken, + logger, + stream + ); + const result = await csv.generateData(); + + if (result.csv_contains_formulas) { + logger.warn(`CSV may contain formulas whose values have been escaped`); + } + + if (result.max_size_reached) { + logger.warn(`Max size reached: CSV output truncated`); + } + + const { warnings } = result; + if (warnings) { + warnings.forEach((warning) => { + logger.warn(warning); + }); + } + + return result; + }; +}; diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/index.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/index.ts index 116b69225a243..c91341c9a01c7 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/index.ts @@ -6,15 +6,15 @@ */ import { - CSV_SEARCHSOURCE_IMMEDIATE_TYPE, + LICENSE_TYPE_TRIAL, LICENSE_TYPE_BASIC, - LICENSE_TYPE_ENTERPRISE, + LICENSE_TYPE_CLOUD_STANDARD, LICENSE_TYPE_GOLD, LICENSE_TYPE_PLATINUM, - LICENSE_TYPE_CLOUD_STANDARD, - LICENSE_TYPE_TRIAL, -} from '../../../common/constants'; -import { ExportTypeDefinition } from '../../types'; + LICENSE_TYPE_ENTERPRISE, + CSV_SEARCHSOURCE_IMMEDIATE_TYPE, +} from '@kbn/reporting-plugin/common/constants'; +import { ExportTypeDefinition } from '@kbn/reporting-plugin/server/types'; import { ImmediateExecuteFn, runTaskFnFactory } from './execute_job'; import { metadata } from './metadata'; diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/metadata.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/metadata.ts similarity index 82% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/metadata.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/metadata.ts index c27b8484697dd..39e7a942fdff8 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/metadata.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_searchsource_immediate/metadata.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { CSV_SEARCHSOURCE_IMMEDIATE_TYPE } from '../../../common/constants'; +import { CSV_SEARCHSOURCE_IMMEDIATE_TYPE } from '@kbn/reporting-common'; export const metadata = { id: CSV_SEARCHSOURCE_IMMEDIATE_TYPE, diff --git a/x-pack/plugins/reporting/server/export_types/csv_v2/create_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_v2/create_job.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/csv_v2/create_job.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_v2/create_job.ts index b0c886137eddc..fda1b705c03ed 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_v2/create_job.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_v2/create_job.ts @@ -6,8 +6,9 @@ */ import Boom from '@hapi/boom'; -import { JobParamsCsvFromSavedObject, TaskPayloadCsvFromSavedObject } from '../../../common/types'; -import { CreateJobFn, CreateJobFnFactory } from '../../types'; +import type { CreateJobFn } from '@kbn/reporting-plugin/server/types'; +import { JobParamsCsvFromSavedObject, TaskPayloadCsvFromSavedObject } from '../../../common/csv_v2'; +import { CreateJobFnFactory } from '../common/types'; type CreateJobFnType = CreateJobFn; diff --git a/x-pack/plugins/reporting/server/export_types/csv_v2/execute_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_v2/execute_job.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/csv_v2/execute_job.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_v2/execute_job.ts index b9181ed3e213f..6e167aa052752 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_v2/execute_job.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_v2/execute_job.ts @@ -6,9 +6,9 @@ */ import { CsvGenerator } from '@kbn/generate-csv'; -import type { TaskPayloadCsvFromSavedObject } from '../../../common/types'; -import { getFieldFormats } from '../../services'; -import type { RunTaskFn, RunTaskFnFactory } from '../../types'; +import type { RunTaskFn, RunTaskFnFactory } from '@kbn/reporting-plugin/server/types'; +import { TaskPayloadCsvFromSavedObject } from '../../../common/csv_v2'; +import { getFieldFormats } from '../../services/services'; import { decryptJobHeaders } from '../common'; type RunTaskFnType = RunTaskFn; diff --git a/x-pack/plugins/reporting/server/export_types/csv_v2/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/csv_v2/index.ts similarity index 84% rename from x-pack/plugins/reporting/server/export_types/csv_v2/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/csv_v2/index.ts index 0e914affbf149..66c713ccdf72a 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_v2/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/csv_v2/index.ts @@ -13,9 +13,11 @@ import { LICENSE_TYPE_GOLD, LICENSE_TYPE_PLATINUM, LICENSE_TYPE_TRIAL, -} from '../../../common/constants'; -import { JobParamsCsvFromSavedObject, TaskPayloadCsvFromSavedObject } from '../../../common/types'; -import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../../types'; +} from '@kbn/reporting-plugin/common/constants'; +import { JobParamsCsvFromSavedObject } from '../../../common'; +import { TaskPayloadCsvFromSavedObject } from '../../../common/csv_v2'; +import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../common/types'; + import { createJobFnFactory } from './create_job'; import { runTaskFnFactory } from './execute_job'; diff --git a/x-pack/plugins/reporting/server/export_types/png/create_job/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/png/create_job/index.ts similarity index 72% rename from x-pack/plugins/reporting/server/export_types/png/create_job/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png/create_job/index.ts index 70822c29119d5..555055364e215 100644 --- a/x-pack/plugins/reporting/server/export_types/png/create_job/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png/create_job/index.ts @@ -5,9 +5,11 @@ * 2.0. */ -import { CreateJobFn, CreateJobFnFactory } from '../../../types'; +import type { CreateJobFn } from '@kbn/reporting-plugin/server/types'; +import { JobParamsPNGDeprecated } from '../../../../common'; +import { TaskPayloadPNG } from '../../../../common/png'; import { validateUrls } from '../../common'; -import { JobParamsPNGDeprecated, TaskPayloadPNG } from '../types'; +import { CreateJobFnFactory } from '../../common/types'; export const createJobFnFactory: CreateJobFnFactory< CreateJobFn diff --git a/x-pack/plugins/reporting/server/export_types/png/execute_job/index.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/png/execute_job/index.test.ts similarity index 93% rename from x-pack/plugins/reporting/server/export_types/png/execute_job/index.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png/execute_job/index.test.ts index 29128f7254227..eb1702ab96365 100644 --- a/x-pack/plugins/reporting/server/export_types/png/execute_job/index.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png/execute_job/index.test.ts @@ -8,17 +8,17 @@ import * as Rx from 'rxjs'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { Writable } from 'stream'; -import { ReportingCore } from '../../..'; +import { ReportingCore } from '@kbn/reporting-plugin/server'; import { CancellationToken } from '@kbn/reporting-common'; -import { cryptoFactory } from '../../../lib'; +import { cryptoFactory } from '@kbn/reporting-plugin/server/lib'; import { createMockConfig, createMockConfigSchema, createMockReportingCore, -} from '../../../test_helpers'; +} from '@kbn/reporting-plugin/server/test_helpers'; import { generatePngObservable } from '../../common'; -import { TaskPayloadPNG } from '../types'; import { runTaskFnFactory } from '.'; +import { TaskPayloadPNG } from '../../../../common/png'; jest.mock('../../common/generate_png'); diff --git a/x-pack/plugins/reporting/server/export_types/png/execute_job/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/png/execute_job/index.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/png/execute_job/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png/execute_job/index.ts index 586ca209f5895..0cb7c37cc57f0 100644 --- a/x-pack/plugins/reporting/server/export_types/png/execute_job/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png/execute_job/index.ts @@ -9,10 +9,10 @@ import { TaskRunResult } from '@kbn/reporting-common'; import apm from 'elastic-apm-node'; import * as Rx from 'rxjs'; import { finalize, map, mergeMap, takeUntil, tap } from 'rxjs/operators'; -import { REPORTING_TRANSACTION_TYPE } from '../../../../common/constants'; -import { RunTaskFn, RunTaskFnFactory } from '../../../types'; +import { REPORTING_TRANSACTION_TYPE } from '@kbn/reporting-plugin/common/constants'; +import { RunTaskFn, RunTaskFnFactory } from '@kbn/reporting-plugin/server/types'; +import { TaskPayloadPNG } from '../../../../common/png'; import { decryptJobHeaders, generatePngObservable, getFullUrls } from '../../common'; -import { TaskPayloadPNG } from '../types'; export const runTaskFnFactory: RunTaskFnFactory> = function executeJobFactoryFn(reporting, parentLogger) { diff --git a/x-pack/plugins/reporting/server/export_types/png/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/png/index.ts similarity index 78% rename from x-pack/plugins/reporting/server/export_types/png/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png/index.ts index e547cb31c7498..c7e40b1af384a 100644 --- a/x-pack/plugins/reporting/server/export_types/png/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png/index.ts @@ -12,12 +12,17 @@ import { LICENSE_TYPE_CLOUD_STANDARD, LICENSE_TYPE_TRIAL, PNG_JOB_TYPE as jobType, -} from '../../../common/constants'; -import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../../types'; +} from '@kbn/reporting-plugin/common/constants'; +import type { + CreateJobFn, + ExportTypeDefinition, + RunTaskFn, +} from '@kbn/reporting-plugin/server/types'; +import { JobParamsPNGDeprecated } from '../../../common'; +import { TaskPayloadPNG } from '../../../common/png'; import { createJobFnFactory } from './create_job'; import { runTaskFnFactory } from './execute_job'; import { metadata } from './metadata'; -import { JobParamsPNGDeprecated, TaskPayloadPNG } from './types'; export const getExportType = (): ExportTypeDefinition< CreateJobFn, diff --git a/x-pack/plugins/reporting/server/export_types/png/metadata.ts b/x-pack/plugins/reporting_export_types/server/export_types/png/metadata.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/png/metadata.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png/metadata.ts diff --git a/x-pack/plugins/reporting/server/export_types/png_v2/create_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/create_job.ts similarity index 70% rename from x-pack/plugins/reporting/server/export_types/png_v2/create_job.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png_v2/create_job.ts index ea2c4ed5910c9..5676f98705e2c 100644 --- a/x-pack/plugins/reporting/server/export_types/png_v2/create_job.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/create_job.ts @@ -5,8 +5,10 @@ * 2.0. */ -import { CreateJobFn, CreateJobFnFactory } from '../../types'; -import { JobParamsPNGV2, TaskPayloadPNGV2 } from './types'; +import { JobParamsPNGV2 } from '@kbn/reporting-plugin/common/types'; +import type { CreateJobFn } from '@kbn/reporting-plugin/server/types'; +import { TaskPayloadPNGV2 } from '../../../common/png_v2'; +import { CreateJobFnFactory } from '../common/types'; export const createJobFnFactory: CreateJobFnFactory> = function createJobFactoryFn() { diff --git a/x-pack/plugins/reporting/server/export_types/png_v2/execute_job.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/execute_job.test.ts similarity index 92% rename from x-pack/plugins/reporting/server/export_types/png_v2/execute_job.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png_v2/execute_job.test.ts index 73c6e71337d79..188ca8398122c 100644 --- a/x-pack/plugins/reporting/server/export_types/png_v2/execute_job.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/execute_job.test.ts @@ -8,18 +8,18 @@ import * as Rx from 'rxjs'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { Writable } from 'stream'; -import { ReportingCore } from '../..'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; import { CancellationToken } from '@kbn/reporting-common'; -import { LocatorParams } from '../../../common/types'; -import { cryptoFactory } from '../../lib'; +import { generatePngObservable } from '../common'; +import { runTaskFnFactory } from './execute_job'; +import { cryptoFactory } from '@kbn/reporting-plugin/server/lib'; +import { LocatorParams } from '@kbn/reporting-plugin/common/types'; import { - createMockConfig, createMockConfigSchema, createMockReportingCore, -} from '../../test_helpers'; -import { generatePngObservable } from '../common'; -import { runTaskFnFactory } from './execute_job'; -import { TaskPayloadPNGV2 } from './types'; + createMockConfig, +} from '@kbn/reporting-plugin/server/test_helpers'; +import { TaskPayloadPNGV2 } from '../../../common/png_v2'; jest.mock('../common/generate_png'); diff --git a/x-pack/plugins/reporting/server/export_types/png_v2/execute_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/execute_job.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/png_v2/execute_job.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png_v2/execute_job.ts index 0d464eb6cadc9..80ee04ed6f560 100644 --- a/x-pack/plugins/reporting/server/export_types/png_v2/execute_job.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/execute_job.ts @@ -5,15 +5,14 @@ * 2.0. */ -import { TaskRunResult } from '@kbn/reporting-common'; +import { REPORTING_TRANSACTION_TYPE, TaskRunResult } from '@kbn/reporting-common'; import apm from 'elastic-apm-node'; import * as Rx from 'rxjs'; import { finalize, map, mergeMap, takeUntil, tap } from 'rxjs/operators'; -import { REPORTING_TRANSACTION_TYPE } from '../../../common/constants'; -import { RunTaskFn, RunTaskFnFactory } from '../../types'; +import type { RunTaskFn, RunTaskFnFactory } from '@kbn/reporting-plugin/server/types'; +import { TaskPayloadPNGV2 } from '../../../common/png_v2'; import { decryptJobHeaders, generatePngObservable } from '../common'; import { getFullRedirectAppUrl } from '../common/v2/get_full_redirect_app_url'; -import { TaskPayloadPNGV2 } from './types'; export const runTaskFnFactory: RunTaskFnFactory> = function executeJobFactoryFn(reporting, parentLogger) { diff --git a/x-pack/plugins/reporting/server/export_types/png_v2/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/index.ts similarity index 77% rename from x-pack/plugins/reporting/server/export_types/png_v2/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png_v2/index.ts index 64cbf9d8d96f4..f14fadb8cc589 100644 --- a/x-pack/plugins/reporting/server/export_types/png_v2/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/index.ts @@ -12,12 +12,17 @@ import { LICENSE_TYPE_CLOUD_STANDARD, LICENSE_TYPE_TRIAL, PNG_JOB_TYPE_V2 as jobType, -} from '../../../common/constants'; -import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../../types'; +} from '@kbn/reporting-plugin/common/constants'; +import { JobParamsPNGV2 } from '@kbn/reporting-plugin/common/types'; +import type { + CreateJobFn, + ExportTypeDefinition, + RunTaskFn, +} from '@kbn/reporting-plugin/server/types'; +import { TaskPayloadPNGV2 } from '../../../common/png_v2'; import { createJobFnFactory } from './create_job'; import { runTaskFnFactory } from './execute_job'; import { metadata } from './metadata'; -import { JobParamsPNGV2, TaskPayloadPNGV2 } from './types'; export const getExportType = (): ExportTypeDefinition< CreateJobFn, diff --git a/x-pack/plugins/reporting/server/export_types/png_v2/metadata.ts b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/metadata.ts similarity index 80% rename from x-pack/plugins/reporting/server/export_types/png_v2/metadata.ts rename to x-pack/plugins/reporting_export_types/server/export_types/png_v2/metadata.ts index 56e18b96f663a..47e978c0e0acc 100644 --- a/x-pack/plugins/reporting/server/export_types/png_v2/metadata.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/png_v2/metadata.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { PNG_REPORT_TYPE_V2 } from '../../../common/constants'; +import { PNG_REPORT_TYPE_V2 } from '@kbn/reporting-plugin/common/constants'; export const metadata = { id: PNG_REPORT_TYPE_V2, diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/create_job/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/create_job/index.ts similarity index 67% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/create_job/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/create_job/index.ts index eeaf0f82f1698..78f7707761d51 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/create_job/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/create_job/index.ts @@ -5,9 +5,11 @@ * 2.0. */ -import { CreateJobFn, CreateJobFnFactory } from '../../../types'; +import { JobParamsPDFDeprecated } from '@kbn/reporting-plugin/server/routes/lib'; +import { TaskPayloadPDF } from '@kbn/reporting-plugin/server/routes/lib/request_handler'; +import type { CreateJobFn } from '@kbn/reporting-plugin/server/types'; import { validateUrls } from '../../common'; -import { JobParamsPDFDeprecated, TaskPayloadPDF } from '../types'; +import { CreateJobFnFactory } from '../../common/types'; export const createJobFnFactory: CreateJobFnFactory< CreateJobFn @@ -22,7 +24,7 @@ export const createJobFnFactory: CreateJobFnFactory< ...jobParams, isDeprecated: true, forceNow: new Date().toISOString(), - objects: relativeUrls.map((u) => ({ relativeUrl: u })), + objects: relativeUrls.map((u: any) => ({ relativeUrl: u })), }; }; }; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/execute_job/index.test.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/execute_job/index.test.ts index cf10b29c328aa..9a25839378120 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/execute_job/index.test.ts @@ -8,13 +8,16 @@ import * as Rx from 'rxjs'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { Writable } from 'stream'; -import { ReportingCore } from '../../..'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; import { CancellationToken } from '@kbn/reporting-common'; -import { cryptoFactory } from '../../../lib'; -import { createMockConfigSchema, createMockReportingCore } from '../../../test_helpers'; import { generatePdfObservable } from '../lib/generate_pdf'; -import { TaskPayloadPDF } from '../types'; import { runTaskFnFactory } from '.'; +import { cryptoFactory } from '@kbn/reporting-plugin/server/lib'; +import { TaskPayloadPDF } from '@kbn/reporting-plugin/server/routes/lib/request_handler'; +import { + createMockConfigSchema, + createMockReportingCore, +} from '@kbn/reporting-plugin/server/test_helpers'; jest.mock('../lib/generate_pdf'); diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/execute_job/index.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/execute_job/index.ts index e3619b3bea77b..f9ebeb0f46fbc 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/execute_job/index.ts @@ -5,15 +5,14 @@ * 2.0. */ -import { TaskRunResult } from '@kbn/reporting-common'; +import { REPORTING_TRANSACTION_TYPE, TaskRunResult } from '@kbn/reporting-common'; import apm from 'elastic-apm-node'; import * as Rx from 'rxjs'; import { catchError, map, mergeMap, takeUntil, tap } from 'rxjs/operators'; -import { REPORTING_TRANSACTION_TYPE } from '../../../../common/constants'; -import { RunTaskFn, RunTaskFnFactory } from '../../../types'; +import type { RunTaskFn, RunTaskFnFactory } from '@kbn/reporting-plugin/server/types'; +import { TaskPayloadPDF } from '@kbn/reporting-plugin/server/routes/lib/request_handler'; import { decryptJobHeaders, getCustomLogo, getFullUrls } from '../../common'; import { generatePdfObservable } from '../lib/generate_pdf'; -import { TaskPayloadPDF } from '../types'; export const runTaskFnFactory: RunTaskFnFactory> = function executeJobFactoryFn(reporting, parentLogger) { diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/index.ts similarity index 75% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/index.ts index 8b94981bc46ae..0efdae214202d 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/index.ts @@ -12,12 +12,13 @@ import { LICENSE_TYPE_CLOUD_STANDARD, LICENSE_TYPE_TRIAL, PDF_JOB_TYPE as jobType, -} from '../../../common/constants'; -import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../../types'; +} from '@kbn/reporting-plugin/common/constants'; +import { JobParamsPDFDeprecated } from '@kbn/reporting-plugin/server/routes/lib'; +import { TaskPayloadPDF } from '@kbn/reporting-plugin/server/routes/lib/request_handler'; +import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '@kbn/reporting-plugin/server/types'; import { createJobFnFactory } from './create_job'; import { runTaskFnFactory } from './execute_job'; import { metadata } from './metadata'; -import { JobParamsPDFDeprecated, TaskPayloadPDF } from './types'; export const getExportType = (): ExportTypeDefinition< CreateJobFn, diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/generate_pdf.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/lib/generate_pdf.ts similarity index 86% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/lib/generate_pdf.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/lib/generate_pdf.ts index 0a77762011d4b..a9b8821ad4be1 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/generate_pdf.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/lib/generate_pdf.ts @@ -7,9 +7,9 @@ import * as Rx from 'rxjs'; import { mergeMap, tap } from 'rxjs/operators'; -import { ReportingCore } from '../../..'; -import { PdfScreenshotOptions } from '../../../types'; -import type { PdfMetrics } from '../../../../common/types'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; +import { PdfScreenshotOptions } from '@kbn/reporting-plugin/server/types'; +import { PdfMetrics } from '@kbn/reporting-common/metrics'; import { getTracker } from '../../common/pdf_tracker'; interface PdfResult { diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/metadata.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/metadata.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/metadata.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf/metadata.ts diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/create_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/create_job.ts similarity index 71% rename from x-pack/plugins/reporting/server/export_types/printable_pdf_v2/create_job.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/create_job.ts index 427b29765080e..f75dffda8698c 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/create_job.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/create_job.ts @@ -5,8 +5,9 @@ * 2.0. */ -import { CreateJobFn, CreateJobFnFactory } from '../../types'; -import { JobParamsPDFV2, TaskPayloadPDFV2 } from './types'; +import { JobParamsPDFV2, TaskPayloadPDFV2 } from '@kbn/reporting-plugin/common/types'; +import type { CreateJobFn } from '@kbn/reporting-plugin/server/types'; +import { CreateJobFnFactory } from '../common/types'; export const createJobFnFactory: CreateJobFnFactory> = function createJobFactoryFn() { diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/execute_job.test.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/execute_job.test.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/printable_pdf_v2/execute_job.test.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/execute_job.test.ts index 03740aa471483..cbb544715f803 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/execute_job.test.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/execute_job.test.ts @@ -10,14 +10,16 @@ jest.mock('./lib/generate_pdf'); import * as Rx from 'rxjs'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { Writable } from 'stream'; -import { ReportingCore } from '../..'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; import { CancellationToken } from '@kbn/reporting-common'; -import { LocatorParams } from '../../../common/types'; -import { cryptoFactory } from '../../lib'; -import { createMockConfigSchema, createMockReportingCore } from '../../test_helpers'; import { runTaskFnFactory } from './execute_job'; import { generatePdfObservable } from './lib/generate_pdf'; -import { TaskPayloadPDFV2 } from './types'; +import { LocatorParams, TaskPayloadPDFV2 } from '@kbn/reporting-plugin/common/types'; +import { cryptoFactory } from '@kbn/reporting-plugin/server/lib'; +import { + createMockConfigSchema, + createMockReportingCore, +} from '@kbn/reporting-plugin/server/test_helpers'; let content: string; let mockReporting: ReportingCore; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/execute_job.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/execute_job.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/printable_pdf_v2/execute_job.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/execute_job.ts index 77e14c9f9a073..d1fa1e861892a 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/execute_job.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/execute_job.ts @@ -8,12 +8,11 @@ import apm from 'elastic-apm-node'; import * as Rx from 'rxjs'; import { catchError, map, mergeMap, takeUntil, tap } from 'rxjs/operators'; -import { TaskRunResult } from '@kbn/reporting-common'; -import { REPORTING_TRANSACTION_TYPE } from '../../../common/constants'; -import { RunTaskFn, RunTaskFnFactory } from '../../types'; +import { REPORTING_TRANSACTION_TYPE, TaskRunResult } from '@kbn/reporting-common'; +import type { RunTaskFn, RunTaskFnFactory } from '@kbn/reporting-plugin/server/types'; +import { TaskPayloadPDFV2 } from '@kbn/reporting-plugin/common/types'; import { decryptJobHeaders, getCustomLogo } from '../common'; import { generatePdfObservable } from './lib/generate_pdf'; -import { TaskPayloadPDFV2 } from './types'; export const runTaskFnFactory: RunTaskFnFactory> = function executeJobFactoryFn(reporting, parentLogger) { diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/index.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/index.ts similarity index 79% rename from x-pack/plugins/reporting/server/export_types/printable_pdf_v2/index.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/index.ts index e97c3aa98c137..29dff5f936630 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/index.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/index.ts @@ -12,12 +12,16 @@ import { LICENSE_TYPE_CLOUD_STANDARD, LICENSE_TYPE_TRIAL, PDF_JOB_TYPE_V2 as jobType, -} from '../../../common/constants'; -import { CreateJobFn, ExportTypeDefinition, RunTaskFn } from '../../types'; +} from '@kbn/reporting-plugin/common/constants'; +import { JobParamsPDFV2, TaskPayloadPDFV2 } from '@kbn/reporting-plugin/common/types'; +import type { + CreateJobFn, + ExportTypeDefinition, + RunTaskFn, +} from '@kbn/reporting-plugin/server/types'; import { createJobFnFactory } from './create_job'; import { runTaskFnFactory } from './execute_job'; import { metadata } from './metadata'; -import { JobParamsPDFV2, TaskPayloadPDFV2 } from './types'; export const getExportType = (): ExportTypeDefinition< CreateJobFn, diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/lib/generate_pdf.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/lib/generate_pdf.ts similarity index 84% rename from x-pack/plugins/reporting/server/export_types/printable_pdf_v2/lib/generate_pdf.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/lib/generate_pdf.ts index b29b3f90861e6..6bf656e14321d 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/lib/generate_pdf.ts +++ b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/lib/generate_pdf.ts @@ -7,12 +7,16 @@ import * as Rx from 'rxjs'; import { mergeMap, tap } from 'rxjs/operators'; -import type { ReportingCore } from '../../..'; -import type { LocatorParams, PdfMetrics, UrlOrUrlLocatorTuple } from '../../../../common/types'; -import type { PdfScreenshotOptions } from '../../../types'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; +import { PdfMetrics } from '@kbn/reporting-common/metrics'; +import { PdfScreenshotOptions } from '@kbn/screenshotting-plugin/server'; +import { + LocatorParams, + TaskPayloadPDFV2, + UrlOrUrlLocatorTuple, +} from '@kbn/reporting-plugin/common/types'; import { getFullRedirectAppUrl } from '../../common/v2/get_full_redirect_app_url'; import { getTracker } from '../../common/pdf_tracker'; -import type { TaskPayloadPDFV2 } from '../types'; interface PdfResult { buffer: Uint8Array | null; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/metadata.ts b/x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/metadata.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf_v2/metadata.ts rename to x-pack/plugins/reporting_export_types/server/export_types/printable_pdf_v2/metadata.ts diff --git a/x-pack/plugins/reporting_export_types/server/index.ts b/x-pack/plugins/reporting_export_types/server/index.ts new file mode 100644 index 0000000000000..603b941e2e97e --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/index.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import { PluginInitializerContext } from '@kbn/core-plugins-server'; +import { ExportTypesPlugin } from './plugin'; +export { getExportType as getTypeCsvFromSavedObject } from './export_types/csv_v2'; +export { getExportType as getTypeCsvFromSavedObjectImmediate } from './export_types/csv_searchsource_immediate'; +export { getExportType as getTypeCsv } from './export_types/csv_searchsource'; +export { getExportType as getTypePng } from './export_types/png'; +export { getExportType as getTypePngV2 } from './export_types/png_v2'; +export { getExportType as getTypePrintablePdf } from './export_types/printable_pdf'; +export { getExportType as getTypePrintablePdfV2 } from './export_types/printable_pdf_v2'; + +export * from './export_types/common'; +export type { ExportTypesPluginSetupDependencies } from './plugin'; + +export const plugin = (initCtx: PluginInitializerContext) => new ExportTypesPlugin(initCtx); diff --git a/x-pack/plugins/reporting_export_types/server/plugin.ts b/x-pack/plugins/reporting_export_types/server/plugin.ts new file mode 100644 index 0000000000000..c46db2f38aba5 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/plugin.ts @@ -0,0 +1,68 @@ +/* + * 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 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { Plugin, PluginInitializerContext, Logger, CoreSetup, CoreStart } from '@kbn/core/server'; +import { FieldFormatsSetup, FieldFormatsStart } from '@kbn/field-formats-plugin/server'; +import type { ReportingSetup } from '@kbn/reporting-plugin/server/types'; +import { ScreenshottingStart } from '@kbn/screenshotting-plugin/server'; +import { + getTypeCsv, + getTypeCsvFromSavedObject, + getTypeCsvFromSavedObjectImmediate, + getTypePng, + getTypePngV2, + getTypePrintablePdf, + getTypePrintablePdfV2, +} from '.'; +import { ReportingExportTypesCore } from './core'; +import { setFieldFormats } from './services/services'; +// import { setFieldFormats } from './services/services'; + +export interface ExportTypesPluginSetupDependencies { + reporting: ReportingSetup; + fieldFormats: FieldFormatsSetup; +} + +export interface ExportTypesPluginStartDependencies { + screenshotting: ScreenshottingStart; + fieldFormats: FieldFormatsStart; +} + +/** This plugin creates the export types in export type definitions to be registered in the Reporting Export Type Registry */ +export class ExportTypesPlugin implements Plugin { + private logger: Logger; + + constructor(private initContext: PluginInitializerContext) { + this.logger = initContext.logger.get(); + } + + public setup(core: CoreSetup, { reporting, fieldFormats }: ExportTypesPluginSetupDependencies) { + const reportingExportTypesCore = new ReportingExportTypesCore(this.logger, this.initContext); + + /** + * Export types to the central reporting plugin + */ + reporting.registerExportType(getTypeCsv()); + reporting.registerExportType(getTypeCsvFromSavedObject()); + // @ts-ignore + reporting.registerExportType(getTypeCsvFromSavedObjectImmediate()); + reporting.registerExportType(getTypePng()); + reporting.registerExportType(getTypePngV2()); + reporting.registerExportType(getTypePrintablePdf()); + reporting.registerExportType(getTypePrintablePdfV2()); + + /** + * Export Types Plugin Routes + */ + // registerRoutes(reportingExportTypesCore, this.logger); + } + + public start(_core: CoreStart, plugins: ExportTypesPluginStartDependencies) { + setFieldFormats(plugins.fieldFormats); + } +} diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/browser.ts b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/browser.ts similarity index 76% rename from x-pack/plugins/reporting/server/routes/diagnostic/browser.ts rename to x-pack/plugins/reporting_export_types/server/routes/diagnostic/browser.ts index 93a5ab72aff28..7f5519616112b 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/browser.ts +++ b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/browser.ts @@ -8,14 +8,15 @@ import type { DocLinksServiceSetup, Logger } from '@kbn/core/server'; import { i18n } from '@kbn/i18n'; import { lastValueFrom } from 'rxjs'; -import type { DiagnosticResponse } from '.'; -import type { ReportingCore } from '../..'; -import { API_DIAGNOSE_URL } from '../../../common/constants'; -import { authorizedUserPreRouting, getCounters } from '../lib'; +import { API_DIAGNOSE_URL } from '@kbn/reporting-plugin/common/constants'; +import { getCounters } from '@kbn/reporting-plugin/server/routes/lib'; +import { DiagnosticResponse } from '.'; +import { ReportingExportTypesCore } from '../../core'; +import { authorizedUserPreRouting } from '../lib/authorized_user_pre_routing'; const logsToHelpMapFactory = (docLinks: DocLinksServiceSetup) => ({ 'error while loading shared libraries': i18n.translate( - 'xpack.reporting.diagnostic.browserMissingDependency', + 'xpack.reportingExportTypes.diagnostic.browserMissingDependency', { defaultMessage: `The browser couldn't start properly due to missing system dependencies. Please see {url}`, values: { url: docLinks.links.reporting.browserSystemDependencies }, @@ -23,14 +24,14 @@ const logsToHelpMapFactory = (docLinks: DocLinksServiceSetup) => ({ ), 'Could not find the default font': i18n.translate( - 'xpack.reporting.diagnostic.browserMissingFonts', + 'xpack.reportingExportTypes.diagnostic.browserMissingFonts', { defaultMessage: `The browser couldn't locate a default font. Please see {url} to fix this issue.`, values: { url: docLinks.links.reporting.browserSystemDependencies }, } ), - 'No usable sandbox': i18n.translate('xpack.reporting.diagnostic.noUsableSandbox', { + 'No usable sandbox': i18n.translate('xpack.reportingExportTypes.diagnostic.noUsableSandbox', { defaultMessage: `Unable to use Chromium sandbox. This can be disabled at your own risk with 'xpack.screenshotting.browser.chromium.disableSandbox'. Please see {url}`, values: { url: docLinks.links.reporting.browserSandboxDependencies }, }), @@ -38,15 +39,18 @@ const logsToHelpMapFactory = (docLinks: DocLinksServiceSetup) => ({ const path = `${API_DIAGNOSE_URL}/browser`; -export const registerDiagnoseBrowser = (reporting: ReportingCore, logger: Logger) => { - const { router } = reporting.getPluginSetupDeps(); +export const registerDiagnoseBrowser = async ( + reporting: ReportingExportTypesCore, + logger: Logger +) => { + const { router } = await reporting.getPluginSetupDeps(); router.post( { path: `${path}`, validate: {} }, authorizedUserPreRouting(reporting, async (_user, _context, req, res) => { const counters = getCounters(req.route.method, path, reporting.getUsageCounter()); - const { docLinks } = reporting.getPluginSetupDeps(); + const { docLinks } = await reporting.getPluginSetupDeps(); const logsToHelpMap = logsToHelpMapFactory(docLinks); try { diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/index.ts b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/index.ts similarity index 79% rename from x-pack/plugins/reporting/server/routes/diagnostic/index.ts rename to x-pack/plugins/reporting_export_types/server/routes/diagnostic/index.ts index 952163a260806..5ff64a8081546 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/index.ts +++ b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/index.ts @@ -6,11 +6,11 @@ */ import type { Logger } from '@kbn/core/server'; -import type { ReportingCore } from '../../core'; +import { ReportingExportTypesCore } from '../../core'; import { registerDiagnoseBrowser } from './browser'; import { registerDiagnoseScreenshot } from './screenshot'; -export const registerDiagnosticRoutes = (reporting: ReportingCore, logger: Logger) => { +export const registerDiagnosticRoutes = (reporting: ReportingExportTypesCore, logger: Logger) => { registerDiagnoseBrowser(reporting, logger); registerDiagnoseScreenshot(reporting, logger); }; diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/integration_tests/browser.test.ts b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/integration_tests/browser.test.ts similarity index 93% rename from x-pack/plugins/reporting/server/routes/diagnostic/integration_tests/browser.test.ts rename to x-pack/plugins/reporting_export_types/server/routes/diagnostic/integration_tests/browser.test.ts index bb835fb8a039c..9a9c390430030 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/integration_tests/browser.test.ts +++ b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/integration_tests/browser.test.ts @@ -9,14 +9,14 @@ import * as Rx from 'rxjs'; import { docLinksServiceMock, loggingSystemMock } from '@kbn/core/server/mocks'; import { setupServer } from '@kbn/core-test-helpers-test-utils'; import supertest from 'supertest'; -import { ReportingCore } from '../../..'; +import type { ReportingCore } from '@kbn/reporting-plugin/server'; import type { ScreenshottingStart } from '@kbn/screenshotting-plugin/server'; import { createMockConfigSchema, createMockPluginSetup, createMockReportingCore, -} from '../../../test_helpers'; -import type { ReportingRequestHandlerContext } from '../../../types'; +} from '@kbn/reporting-plugin/server/test_helpers'; +import type { ReportingRequestHandlerContext } from '@kbn/reporting-plugin/server/types'; import { registerDiagnoseBrowser } from '../browser'; type SetupServerReturn = Awaited>; @@ -44,7 +44,7 @@ describe('POST /diagnose/browser', () => { httpSetup.registerRouteHandlerContext( reportingSymbol, 'reporting', - () => ({ usesUiCapabilities: () => false }) + () => ({ usesUiCapabilities: () => false, registerExportType: jest.fn }) ); const docLinksSetupMock = docLinksServiceMock.createSetupContract(); diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/integration_tests/screenshot.test.ts b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/screenshot.test.ts similarity index 88% rename from x-pack/plugins/reporting/server/routes/diagnostic/integration_tests/screenshot.test.ts rename to x-pack/plugins/reporting_export_types/server/routes/diagnostic/screenshot.test.ts index e53efe67ebf44..de112f46da1db 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/integration_tests/screenshot.test.ts +++ b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/screenshot.test.ts @@ -8,18 +8,18 @@ import { loggingSystemMock } from '@kbn/core/server/mocks'; import { setupServer } from '@kbn/core-test-helpers-test-utils'; import supertest from 'supertest'; -import { ReportingCore } from '../../..'; -import { generatePngObservable } from '../../../export_types/common'; +import { ReportingCore } from '@kbn/reporting-plugin/server'; import { createMockConfigSchema, createMockPluginSetup, createMockReportingCore, -} from '../../../test_helpers'; -import type { ReportingRequestHandlerContext } from '../../../types'; -import { registerDiagnoseScreenshot } from '../screenshot'; +} from '@kbn/reporting-plugin/server/test_helpers'; +import type { ReportingRequestHandlerContext } from '@kbn/reporting-plugin/server/types'; +import { registerDiagnoseScreenshot } from './screenshot'; import { defer } from 'rxjs'; +import { generatePngObservable } from '../..'; -jest.mock('../../../export_types/common/generate_png'); +jest.mock('../../export_types/common/generate_png'); type SetupServerReturn = Awaited>; @@ -45,7 +45,7 @@ describe('POST /diagnose/screenshot', () => { httpSetup.registerRouteHandlerContext( reportingSymbol, 'reporting', - () => ({ usesUiCapabilities: () => false }) + () => ({ usesUiCapabilities: () => false, registerExportType: jest.fn() }) ); core = await createMockReportingCore( diff --git a/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.ts b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/screenshot.ts similarity index 81% rename from x-pack/plugins/reporting/server/routes/diagnostic/screenshot.ts rename to x-pack/plugins/reporting_export_types/server/routes/diagnostic/screenshot.ts index cedcf65297f75..e349b60913a2e 100644 --- a/x-pack/plugins/reporting/server/routes/diagnostic/screenshot.ts +++ b/x-pack/plugins/reporting_export_types/server/routes/diagnostic/screenshot.ts @@ -8,18 +8,18 @@ import type { Logger } from '@kbn/core/server'; import { APP_WRAPPER_CLASS } from '@kbn/core/server'; import { i18n } from '@kbn/i18n'; +import { API_DIAGNOSE_URL } from '@kbn/reporting-plugin/common/constants'; import { lastValueFrom } from 'rxjs'; -import type { ReportingCore } from '../..'; -import { API_DIAGNOSE_URL } from '../../../common/constants'; -import { generatePngObservable } from '../../export_types/common'; -import { getAbsoluteUrlFactory } from '../../export_types/common/get_absolute_url'; -import { authorizedUserPreRouting, getCounters } from '../lib'; +import { getAbsoluteUrlFactory } from '@kbn/reporting-plugin/common/get_absolute_url'; +import { getCounters } from '@kbn/reporting-plugin/server/routes/lib'; +import { generatePngObservable } from '../..'; +import { ReportingExportTypesCore } from '../../core'; +import { authorizedUserPreRouting } from '../lib/authorized_user_pre_routing'; const path = `${API_DIAGNOSE_URL}/screenshot`; -export const registerDiagnoseScreenshot = (reporting: ReportingCore, logger: Logger) => { - const setupDeps = reporting.getPluginSetupDeps(); - const { router } = setupDeps; +export const registerDiagnoseScreenshot = (reporting: ReportingExportTypesCore, logger: Logger) => { + const { router } = reporting.getPluginSetupDeps(); router.post( { path, validate: {} }, @@ -88,7 +88,7 @@ export const registerDiagnoseScreenshot = (reporting: ReportingCore, logger: Log body: { success: false, help: [ - i18n.translate('xpack.reporting.diagnostic.screenshotFailureMessage', { + i18n.translate('xpack.reportingExportTypes.diagnostic.screenshotFailureMessage', { defaultMessage: `We couldn't screenshot your Kibana install.`, }), ], diff --git a/x-pack/plugins/reporting/server/routes/generate/csv_searchsource_immediate.ts b/x-pack/plugins/reporting_export_types/server/routes/generate/csv_searchsource_immediate.ts similarity index 85% rename from x-pack/plugins/reporting/server/routes/generate/csv_searchsource_immediate.ts rename to x-pack/plugins/reporting_export_types/server/routes/generate/csv_searchsource_immediate.ts index 7c4886be207b3..d1b5d2f19ff9b 100644 --- a/x-pack/plugins/reporting/server/routes/generate/csv_searchsource_immediate.ts +++ b/x-pack/plugins/reporting_export_types/server/routes/generate/csv_searchsource_immediate.ts @@ -8,13 +8,21 @@ import Boom from '@hapi/boom'; import { schema } from '@kbn/config-schema'; import type { KibanaRequest, Logger } from '@kbn/core/server'; +import { SerializedSearchSourceFields } from '@kbn/data-plugin/common'; import moment from 'moment'; -import type { ReportingCore } from '../..'; -import { CSV_SEARCHSOURCE_IMMEDIATE_TYPE } from '../../../common/constants'; -import { runTaskFnFactory } from '../../export_types/csv_searchsource_immediate/execute_job'; -import type { JobParamsDownloadCSV } from '../../export_types/csv_searchsource_immediate/types'; -import { PassThroughStream } from '../../lib'; -import { authorizedUserPreRouting, getCounters } from '../lib'; +import { CSV_SEARCHSOURCE_IMMEDIATE_TYPE } from '@kbn/reporting-plugin/common/constants'; +import { PassThroughStream } from '@kbn/reporting-plugin/server/lib'; +import { getCounters } from '@kbn/reporting-plugin/server/routes/lib'; +import { ReportingExportTypesCore } from '../../core'; +import { runTaskFnFactory } from './execute_job'; +import { authorizedUserPreRouting } from '../lib/authorized_user_pre_routing'; + +export interface JobParamsDownloadCSV { + browserTimezone: string; + title: string; + searchSource: SerializedSearchSourceFields; + columns?: string[]; +} const API_BASE_URL_V1 = '/api/reporting/v1'; const API_BASE_GENERATE_V1 = `${API_BASE_URL_V1}/generate`; @@ -33,11 +41,10 @@ const path = `${API_BASE_GENERATE_V1}/immediate/csv_searchsource`; * - local (transient) changes the user made to the saved object */ export function registerGenerateCsvFromSavedObjectImmediate( - reporting: ReportingCore, + reporting: ReportingExportTypesCore, parentLogger: Logger ) { - const setupDeps = reporting.getPluginSetupDeps(); - const { router } = setupDeps; + const { router } = reporting.getPluginSetupDeps(); // TODO: find a way to abstract this using ExportTypeRegistry: it needs a new // public method to return this array diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/execute_job.ts b/x-pack/plugins/reporting_export_types/server/routes/generate/execute_job.ts similarity index 92% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/execute_job.ts rename to x-pack/plugins/reporting_export_types/server/routes/generate/execute_job.ts index 26fc4b7a3ed8f..b90cbb81cdbf4 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/execute_job.ts +++ b/x-pack/plugins/reporting_export_types/server/routes/generate/execute_job.ts @@ -9,9 +9,10 @@ import { KibanaRequest } from '@kbn/core/server'; import { Writable } from 'stream'; import { CancellationToken, TaskRunResult } from '@kbn/reporting-common'; import { CsvGenerator } from '@kbn/generate-csv'; -import { getFieldFormats } from '../../services'; -import { ReportingRequestHandlerContext, RunTaskFnFactory } from '../../types'; -import { JobParamsDownloadCSV } from './types'; +import { JobParamsDownloadCSV } from './csv_searchsource_immediate'; +import { ReportingRequestHandlerContext } from '..'; +import { RunTaskFnFactory } from '../../types'; +import { getFieldFormats } from './services'; /* * ImmediateExecuteFn receives the job doc payload because the payload was diff --git a/x-pack/plugins/reporting_export_types/server/routes/generate/generate_from_jobparams.ts b/x-pack/plugins/reporting_export_types/server/routes/generate/generate_from_jobparams.ts new file mode 100644 index 0000000000000..c9803742da629 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/routes/generate/generate_from_jobparams.ts @@ -0,0 +1,113 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { Logger } from '@kbn/core/server'; +import rison from '@kbn/rison'; +import { API_BASE_URL } from '@kbn/reporting-plugin/common/constants'; +import type { BaseParams } from '@kbn/reporting-plugin/server/types'; +import { getCounters } from '@kbn/reporting-plugin/server/routes/lib'; +import { ReportingExportTypesCore } from '../../core'; +import { authorizedUserPreRouting } from '../lib/authorized_user_pre_routing'; +import { RequestHandler } from '../lib/request_handler'; + +const BASE_GENERATE = `${API_BASE_URL}/generate`; + +export function registerJobGenerationRoutes(reporting: ReportingExportTypesCore, logger: Logger) { + const setupDeps = reporting.getPluginSetupDeps(); + const { router } = setupDeps; + + // TODO: find a way to abstract this using ExportTypeRegistry: it needs a new + // public method to return this array + // const registry = reporting.getExportTypesRegistry(); + // const kibanaAccessControlTags = registry.getAllAccessControlTags(); + const useKibanaAccessControl = reporting.getDeprecatedAllowedRoles() === false; // true if Reporting's deprecated access control feature is disabled + const kibanaAccessControlTags = useKibanaAccessControl ? ['access:generateReport'] : []; + + const registerPostGenerationEndpoint = () => { + const path = `${BASE_GENERATE}/{exportType}`; + router.post( + { + path, + validate: { + params: schema.object({ exportType: schema.string({ minLength: 2 }) }), + body: schema.nullable(schema.object({ jobParams: schema.maybe(schema.string()) })), + query: schema.nullable(schema.object({ jobParams: schema.string({ defaultValue: '' }) })), + }, + options: { tags: kibanaAccessControlTags }, + }, + authorizedUserPreRouting(reporting, async (user, context, req, res) => { + const counters = getCounters( + req.route.method, + path.replace(/{exportType}/, req.params.exportType), + reporting.getUsageCounter() + ); + + let jobParamsRison: null | string = null; + + if (req.body) { + const { jobParams: jobParamsPayload } = req.body; + jobParamsRison = jobParamsPayload ? jobParamsPayload : null; + } else if (req.query?.jobParams) { + const { jobParams: queryJobParams } = req.query; + if (queryJobParams) { + jobParamsRison = queryJobParams; + } else { + jobParamsRison = null; + } + } + + if (!jobParamsRison) { + return res.customError({ + statusCode: 400, + body: 'A jobParams RISON string is required in the querystring or POST body', + }); + } + + let jobParams; + + try { + jobParams = rison.decode(jobParamsRison) as BaseParams | null; + if (!jobParams) { + return res.customError({ + statusCode: 400, + body: 'Missing jobParams!', + }); + } + } catch (err) { + return res.customError({ + statusCode: 400, + body: `invalid rison: ${jobParamsRison}`, + }); + } + + const requestHandler = new RequestHandler(reporting, user, context, req, res, logger); + return await requestHandler.handleGenerateRequest( + req.params.exportType, + jobParams, + counters + ); + }) + ); + }; + + const registerGetGenerationEndpoint = () => { + // Get route to generation endpoint: show error about GET method to user + router.get( + { + path: `${BASE_GENERATE}/{p*}`, + validate: false, + }, + (_context, _req, res) => { + return res.customError({ statusCode: 405, body: 'GET is not allowed' }); + } + ); + }; + + registerPostGenerationEndpoint(); + registerGetGenerationEndpoint(); +} diff --git a/x-pack/plugins/reporting_export_types/server/routes/generate/index.ts b/x-pack/plugins/reporting_export_types/server/routes/generate/index.ts new file mode 100644 index 0000000000000..10ab3e8b3d2e5 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/routes/generate/index.ts @@ -0,0 +1,11 @@ +/* + * 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 { registerJobGenerationRoutes } from './generate_from_jobparams'; +export type { JobParamsDownloadCSV } from './csv_searchsource_immediate'; + +export { registerGenerateCsvFromSavedObjectImmediate } from './csv_searchsource_immediate'; diff --git a/x-pack/plugins/reporting/server/routes/generate/integration_tests/generation_from_jobparams.test.ts b/x-pack/plugins/reporting_export_types/server/routes/generate/integration_tests/generation_from_jobparams.test.ts similarity index 91% rename from x-pack/plugins/reporting/server/routes/generate/integration_tests/generation_from_jobparams.test.ts rename to x-pack/plugins/reporting_export_types/server/routes/generate/integration_tests/generation_from_jobparams.test.ts index 985ed9d1de7c7..5ae3504204699 100644 --- a/x-pack/plugins/reporting/server/routes/generate/integration_tests/generation_from_jobparams.test.ts +++ b/x-pack/plugins/reporting_export_types/server/routes/generate/integration_tests/generation_from_jobparams.test.ts @@ -10,19 +10,19 @@ import { BehaviorSubject } from 'rxjs'; import { loggingSystemMock } from '@kbn/core/server/mocks'; import { setupServer } from '@kbn/core-test-helpers-test-utils'; import supertest from 'supertest'; -import { ReportingCore } from '../../..'; import { licensingMock } from '@kbn/licensing-plugin/server/mocks'; -import { ReportingStore } from '../../../lib'; -import { ExportTypesRegistry } from '../../../lib/export_types_registry'; -import { Report } from '../../../lib/store'; +import { ReportingStore } from '@kbn/reporting-plugin/server/lib'; +import { ExportTypesRegistry } from '@kbn/reporting-plugin/server/lib/export_types_registry'; +import { Report } from '@kbn/reporting-plugin/server/lib/store'; import { createMockConfigSchema, createMockPluginSetup, createMockPluginStart, createMockReportingCore, -} from '../../../test_helpers'; -import type { ReportingRequestHandlerContext } from '../../../types'; -import { registerJobGenerationRoutes } from '../generate_from_jobparams'; +} from '@kbn/reporting-plugin/server/test_helpers'; +import { registerJobGenerationRoutes } from '@kbn/reporting-plugin/server/routes/generate/generate_from_jobparams'; +import { ReportingRequestHandlerContext } from '@kbn/reporting-plugin/server/types'; +import { ReportingCore } from '@kbn/reporting-plugin/server'; type SetupServerReturn = Awaited>; @@ -45,7 +45,7 @@ describe('POST /api/reporting/generate', () => { httpSetup.registerRouteHandlerContext( reportingSymbol, 'reporting', - () => ({ usesUiCapabilities: jest.fn() }) + () => ({ usesUiCapabilities: jest.fn(), registerExportType: jest.fn() }) ); const mockSetupDeps = createMockPluginSetup({ diff --git a/x-pack/plugins/reporting/server/services.ts b/x-pack/plugins/reporting_export_types/server/routes/generate/services.ts similarity index 100% rename from x-pack/plugins/reporting/server/services.ts rename to x-pack/plugins/reporting_export_types/server/routes/generate/services.ts diff --git a/x-pack/plugins/reporting_export_types/server/routes/index.ts b/x-pack/plugins/reporting_export_types/server/routes/index.ts new file mode 100644 index 0000000000000..a7d70853abc38 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/routes/index.ts @@ -0,0 +1,25 @@ +/* + * 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 { CustomRequestHandlerContext, IRouter, Logger } from '@kbn/core/server'; +import { ReportingStart } from '@kbn/reporting-plugin/server'; +import { ReportingExportTypesCore } from '../core'; +import { registerDiagnosticRoutes } from './diagnostic'; +import { registerGenerateCsvFromSavedObjectImmediate } from './generate'; +export { registerDiagnosticRoutes } from './diagnostic'; +export type { DiagnosticResponse } from './diagnostic'; + +export function registerRoutes(reporting: ReportingExportTypesCore, logger: Logger) { + registerDiagnosticRoutes(reporting, logger); + registerGenerateCsvFromSavedObjectImmediate(reporting, logger); +} + +export type ReportingRequestHandlerContext = CustomRequestHandlerContext<{ + reporting: ReportingStart | null; +}>; + +export type ReportingExportTypesPluginRouter = IRouter; +export type { JobParamsDownloadCSV } from './generate/csv_searchsource_immediate'; diff --git a/x-pack/plugins/reporting_export_types/server/routes/lib/authorized_user_pre_routing.ts b/x-pack/plugins/reporting_export_types/server/routes/lib/authorized_user_pre_routing.ts new file mode 100644 index 0000000000000..02e188e9484ae --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/routes/lib/authorized_user_pre_routing.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { RequestHandler, RouteMethod } from '@kbn/core/server'; +import { AuthenticatedUser } from '@kbn/security-plugin/server'; +import { i18n } from '@kbn/i18n'; +import type { ReportingRequestHandlerContext } from '@kbn/reporting-plugin/server/types'; +import { getUser } from '@kbn/reporting-plugin/server/routes/lib/get_user'; +import { ReportingExportTypesCore } from '../../core'; + +const superuserRole = 'superuser'; + +type ReportingRequestUser = AuthenticatedUser | false; + +export type RequestHandlerUser = RequestHandler< + P, + Q, + B, + ReportingRequestHandlerContext +> extends (...a: infer U) => infer R + ? (user: ReportingRequestUser, ...a: U) => R + : never; + +export const authorizedUserPreRouting = ( + reporting: ReportingExportTypesCore, + handler: RequestHandlerUser +): RequestHandler => { + const { logger, security, docLinks } = reporting.getPluginSetupDeps(); + + return async (context, req, res) => { + const { security: securityStart } = await reporting.getPluginStartDeps(); + try { + let user: ReportingRequestUser = false; + if (security && security.license.isEnabled()) { + // find the authenticated user, or null if security is not enabled + user = getUser(req, securityStart); + if (!user) { + // security is enabled but the user is null + return res.unauthorized({ body: `Sorry, you aren't authenticated` }); + } + } + + const deprecatedAllowedRoles = reporting.getDeprecatedAllowedRoles(); + if (user && deprecatedAllowedRoles !== false) { + // check allowance with the configured set of roleas + "superuser" + const allowedRoles = deprecatedAllowedRoles || []; + const authorizedRoles = [superuserRole, ...allowedRoles]; + + if (!user.roles.find((role) => authorizedRoles.includes(role))) { + const body = i18n.translate('xpack.reportingExportTypes.userAccessError.message', { + defaultMessage: `Ask your administrator for access to reporting features. {grantUserAccessDocs}.`, + values: { + grantUserAccessDocs: + `` + + i18n.translate('xpack.reportingExportTypes.userAccessError.learnMoreLink', { + defaultMessage: 'Learn more', + }) + + '', + }, + }); + // user's roles do not allow + return res.forbidden({ body }); + } + } + + return handler(user, context, req, res); + } catch (err) { + logger.error(err); + return res.custom({ statusCode: 500 }); + } + }; +}; diff --git a/x-pack/plugins/reporting_export_types/server/routes/lib/content_stream.ts b/x-pack/plugins/reporting_export_types/server/routes/lib/content_stream.ts new file mode 100644 index 0000000000000..8df037f2d907f --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/routes/lib/content_stream.ts @@ -0,0 +1,40 @@ +/* + * 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 { ContentStream } from '@kbn/reporting-plugin/server/lib'; +import { ReportingExportTypesCore } from '../../core'; + +type ContentStreamEncoding = 'base64' | 'raw'; + +interface ContentStreamDocument { + id: string; + index: string; + if_primary_term?: number; + if_seq_no?: number; +} +interface ContentStreamParameters { + /** + * Content encoding. By default, it is Base64. + */ + encoding?: ContentStreamEncoding; +} + +export async function getContentStream( + reporting: ReportingExportTypesCore, + document: ContentStreamDocument, + parameters?: ContentStreamParameters +) { + const { asInternalUser: client } = await reporting.getEsClient(); + const { logger } = reporting.getPluginSetupDeps(); + + return new ContentStream( + client, + logger.get('content_stream').get(document.id), + document, + parameters + ); +} diff --git a/x-pack/plugins/reporting_export_types/server/routes/lib/execute_report.ts b/x-pack/plugins/reporting_export_types/server/routes/lib/execute_report.ts new file mode 100644 index 0000000000000..e3f8d31470b4c --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/routes/lib/execute_report.ts @@ -0,0 +1,534 @@ +/* + * 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 { UpdateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { Logger } from '@kbn/core/server'; +import moment from 'moment'; +import * as Rx from 'rxjs'; +import { timeout } from 'rxjs/operators'; +import { Writable } from 'stream'; +import { finished } from 'stream/promises'; +import { setTimeout } from 'timers/promises'; +import type { + RunContext, + TaskManagerStartContract, + TaskRunCreatorFunction, +} from '@kbn/task-manager-plugin/server'; +import { + CancellationToken, + ReportingError, + QueueTimeoutError, + KibanaShuttingDownError, + TaskRunResult, + durationToNumber, + numberToDuration, +} from '@kbn/reporting-common'; +import { mapToReportingError } from '@kbn/reporting-plugin/common/errors/map_to_reporting_error'; +import { ReportOutput, ReportDocument } from '@kbn/reporting-plugin/common/types'; +import { ReportingConfigType } from '@kbn/reporting-plugin/server/config'; +import { ReportingStore } from '@kbn/reporting-plugin/server/lib'; +import { Report, SavedReport } from '@kbn/reporting-plugin/server/lib/store'; +import { + ReportProcessingFields, + ReportFailedFields, +} from '@kbn/reporting-plugin/server/lib/store/store'; +import { + ReportTaskParams, + ReportingTask, + REPORTING_EXECUTE_TYPE, + ReportingTaskStatus, +} from '@kbn/reporting-plugin/server/lib/tasks'; +import { errorLogger } from '@kbn/reporting-plugin/server/lib/tasks/error_logger'; +import { ExportTypeDefinition, RunTaskFn, BasePayload } from '@kbn/reporting-plugin/server/types'; +import { ReportingExportTypesCore } from '../../core'; +import { getContentStream } from './content_stream'; + +type CompletedReportOutput = Omit; + +interface ReportingExecuteTaskInstance { + state: object; + taskType: string; + params: ReportTaskParams; + runAt?: Date; +} + +interface TaskExecutor extends Pick { + jobExecutor: RunTaskFn; +} + +function isOutput(output: CompletedReportOutput | Error): output is CompletedReportOutput { + return (output as CompletedReportOutput).size != null; +} + +function reportFromTask(task: ReportTaskParams) { + return new Report({ ...task, _id: task.id, _index: task.index }); +} + +async function finishedWithNoPendingCallbacks(stream: Writable) { + await finished(stream, { readable: false }); + + // Race condition workaround: + // `finished(...)` will resolve while there's still pending callbacks in the writable part of the `stream`. + // This introduces a race condition where the code continues before the writable part has completely finished. + // The `pendingCallbacks` function is a hack to ensure that all pending callbacks have been called before continuing. + // For more information, see: https://github.com/nodejs/node/issues/46170 + await (async function pendingCallbacks(delay = 1) { + if ((stream as any)._writableState.pendingcb > 0) { + await setTimeout(delay); + await pendingCallbacks(delay < 32 ? delay * 2 : delay); + } + })(); +} + +export class ExecuteReportTask implements ReportingTask { + public TYPE = REPORTING_EXECUTE_TYPE; + + private logger: Logger; + private taskManagerStart?: TaskManagerStartContract; + private taskExecutors?: Map; + private kibanaId?: string; + private kibanaName?: string; + private store?: ReportingStore; + + constructor( + private reporting: ReportingExportTypesCore, + private config: ReportingConfigType, + logger: Logger + ) { + this.logger = logger.get('runTask'); + } + + /* + * To be called from plugin start + */ + public async init(taskManager: TaskManagerStartContract) { + this.taskManagerStart = taskManager; + + const { reporting } = this; + + const exportTypesRegistry = reporting.getExportTypesRegistry(); + const executors = new Map(); + for (const exportType of exportTypesRegistry.getAll()) { + const exportTypeLogger = this.logger.get(exportType.jobType); + const jobExecutor = exportType.runTaskFnFactory(reporting, exportTypeLogger); + // The task will run the function with the job type as a param. + // This allows us to retrieve the specific export type runFn when called to run an export + executors.set(exportType.jobType, { + jobExecutor, + jobContentEncoding: exportType.jobContentEncoding, + }); + } + + this.taskExecutors = executors; + + const config = reporting.getConfig(); + this.kibanaId = config.kbnConfig.get('server', 'uuid'); + this.kibanaName = config.kbnConfig.get('server', 'name'); + } + + /* + * Async get the ReportingStore: it is only available after PluginStart + */ + private async getStore(): Promise { + if (this.store) { + return this.store; + } + const { store } = await this.reporting.getPluginStartDeps(); + this.store = store; + return store; + } + + private getTaskManagerStart() { + if (!this.taskManagerStart) { + throw new Error('Reporting task runner has not been initialized!'); + } + return this.taskManagerStart; + } + + private getJobContentEncoding(jobType: string) { + return this.taskExecutors?.get(jobType)?.jobContentEncoding; + } + + public async _claimJob(task: ReportTaskParams): Promise { + if (this.kibanaId == null) { + throw new Error(`Kibana instance ID is undefined!`); + } + if (this.kibanaName == null) { + throw new Error(`Kibana instance name is undefined!`); + } + + const store = await this.getStore(); + const report = await store.findReportFromTask(task); // receives seq_no and primary_term + + // Check if this is a completed job. This may happen if the `reports:monitor` + // task detected it to be a zombie job and rescheduled it, but it + // eventually completed on its own. + if (report.status === 'completed') { + throw new Error(`Can not claim the report job: it is already completed!`); + } + + const m = moment(); + + // check if job has exceeded the configured maxAttempts + const maxAttempts = this.config.capture.maxAttempts; + if (report.attempts >= maxAttempts) { + const err = new QueueTimeoutError( + `Max attempts reached (${maxAttempts}). Queue timeout reached.` + ); + await this._failJob(report, err); + throw err; + } + + const queueTimeout = durationToNumber(this.config.queue.timeout); + const startTime = m.toISOString(); + const expirationTime = m.add(queueTimeout).toISOString(); + + const doc: ReportProcessingFields = { + kibana_id: this.kibanaId, + kibana_name: this.kibanaName, + attempts: report.attempts + 1, + max_attempts: maxAttempts, + started_at: startTime, + timeout: queueTimeout, + process_expiration: expirationTime, + }; + + const claimedReport = new SavedReport({ + ...report, + ...doc, + }); + + this.logger.info( + `Claiming ${claimedReport.jobtype} ${report._id} ` + + `[_index: ${report._index}] ` + + `[_seq_no: ${report._seq_no}] ` + + `[_primary_term: ${report._primary_term}] ` + + `[attempts: ${report.attempts}] ` + + `[process_expiration: ${expirationTime}]` + ); + + const resp = await store.setReportClaimed(claimedReport, doc); + claimedReport._seq_no = resp._seq_no; + claimedReport._primary_term = resp._primary_term; + return claimedReport; + } + + private async _failJob( + report: SavedReport, + error?: ReportingError + ): Promise> { + const message = `Failing ${report.jobtype} job ${report._id}`; + + // log the error + let docOutput; + if (error) { + errorLogger(this.logger, message, error); + docOutput = this._formatOutput(error); + } else { + errorLogger(this.logger, message); + } + + // update the report in the store + const store = await this.getStore(); + const completedTime = moment().toISOString(); + const doc: ReportFailedFields = { + completed_at: completedTime, + output: docOutput ?? null, + }; + + return await store.setReportFailed(report, doc); + } + + private _formatOutput(output: CompletedReportOutput | ReportingError): ReportOutput { + const docOutput = {} as ReportOutput; + const unknownMime = null; + + if (isOutput(output)) { + docOutput.content_type = output.content_type || unknownMime; + docOutput.max_size_reached = output.max_size_reached; + docOutput.csv_contains_formulas = output.csv_contains_formulas; + docOutput.size = output.size; + docOutput.warnings = + output.warnings && output.warnings.length > 0 ? output.warnings : undefined; + docOutput.error_code = output.error_code; + } else { + const defaultOutput = null; + docOutput.content = output.humanFriendlyMessage?.() || output.toString() || defaultOutput; + docOutput.content_type = unknownMime; + docOutput.warnings = [output.toString()]; + docOutput.error_code = output.code; + } + + return docOutput; + } + + public async _performJob( + task: ReportTaskParams, + cancellationToken: CancellationToken, + stream: Writable + ): Promise { + if (!this.taskExecutors) { + throw new Error(`Task run function factories have not been called yet!`); + } + + // get the run_task function + const runner = this.taskExecutors.get(task.jobtype); + if (!runner) { + throw new Error(`No defined task runner function for ${task.jobtype}!`); + } + + // run the report + // if workerFn doesn't finish before timeout, call the cancellationToken and throw an error + const queueTimeout = durationToNumber(this.config.queue.timeout); + return Rx.lastValueFrom( + Rx.from(runner.jobExecutor(task.id, task.payload, cancellationToken, stream)).pipe( + timeout(queueTimeout) + ) // throw an error if a value is not emitted before timeout + ); + } + + public async _completeJob( + report: SavedReport, + output: CompletedReportOutput + ): Promise { + let docId = `/${report._index}/_doc/${report._id}`; + + this.logger.debug(`Saving ${report.jobtype} to ${docId}.`); + + const completedTime = moment().toISOString(); + const docOutput = this._formatOutput(output); + const store = await this.getStore(); + const doc = { + completed_at: completedTime, + metrics: output.metrics, + output: docOutput, + }; + docId = `/${report._index}/_doc/${report._id}`; + + const resp = await store.setReportCompleted(report, doc); + this.logger.info(`Saved ${report.jobtype} job ${docId}`); + report._seq_no = resp._seq_no; + report._primary_term = resp._primary_term; + return report; + } + + // Generic is used to let TS infer the return type at call site. + private async throwIfKibanaShutsDown(): Promise { + await this.reporting.getKibanaShutdown$().toPromise(); + throw new KibanaShuttingDownError(); + } + + /* + * Provides a TaskRunner for Task Manager + */ + private getTaskRunner(): TaskRunCreatorFunction { + // Keep a separate local stack for each task run + return (context: RunContext) => { + let jobId: string; + const cancellationToken = new CancellationToken(); + + return { + /* + * Runs a reporting job + * Claim job: Finds the report in ReportingStore, updates it to "processing" + * Perform job: Gets the export type's runner, runs it with the job params + * Complete job: Updates the report in ReportStore with the output from the runner + * If any error happens, additional retry attempts may be picked up by a separate instance + */ + run: async () => { + let report: SavedReport | undefined; + + // find the job in the store and set status to processing + const task = context.taskInstance.params as ReportTaskParams; + jobId = task?.id; + + try { + if (!jobId) { + throw new Error('Invalid report data provided in scheduled task!'); + } + this.reporting.trackReport(jobId); + + // Update job status to claimed + report = await this._claimJob(task); + } catch (failedToClaim) { + // error claiming report - log the error + // could be version conflict, or no longer connected to ES + errorLogger(this.logger, `Error in claiming ${jobId}`, failedToClaim); + } + + if (!report) { + this.reporting.untrackReport(jobId); + errorLogger(this.logger, `Job ${jobId} could not be claimed. Exiting...`); + return; + } + + const { jobtype: jobType, attempts } = report; + const maxAttempts = this.config.capture.maxAttempts; + + this.logger.debug( + `Starting ${jobType} report ${jobId}: attempt ${attempts} of ${maxAttempts}.` + ); + this.logger.debug(`Reports running: ${this.reporting.countConcurrentReports()}.`); + + const eventLog = this.reporting.getEventLogger( + new Report({ ...task, _id: task.id, _index: task.index }) + ); + + try { + const jobContentEncoding = this.getJobContentEncoding(jobType); + const stream = await getContentStream( + this.reporting, + { + id: report._id, + index: report._index, + if_primary_term: report._primary_term, + if_seq_no: report._seq_no, + }, + { + encoding: jobContentEncoding === 'base64' ? 'base64' : 'raw', + } + ); + + eventLog.logExecutionStart(); + + const output = await Promise.race([ + this._performJob(task, cancellationToken, stream), + this.throwIfKibanaShutsDown(), + ]); + + stream.end(); + + await finishedWithNoPendingCallbacks(stream); + + report._seq_no = stream.getSeqNo()!; + report._primary_term = stream.getPrimaryTerm()!; + + eventLog.logExecutionComplete({ + ...(output.metrics ?? {}), + byteSize: stream.bytesWritten, + }); + + if (output) { + this.logger.debug(`Job output size: ${stream.bytesWritten} bytes.`); + report = await this._completeJob(report, { + ...output, + size: stream.bytesWritten, + }); + } + // untrack the report for concurrency awareness + this.logger.debug(`Stopping ${jobId}.`); + } catch (failedToExecuteErr) { + eventLog.logError(failedToExecuteErr); + + cancellationToken.cancel(); + + if (attempts < maxAttempts) { + // attempts remain, reschedule + try { + if (report == null) { + throw new Error(`Report ${jobId} is null!`); + } + // reschedule to retry + const remainingAttempts = maxAttempts - report.attempts; + errorLogger( + this.logger, + `Scheduling retry for job ${jobId}. Retries remaining: ${remainingAttempts}.`, + failedToExecuteErr + ); + + await this.rescheduleTask(reportFromTask(task).toReportTaskJSON(), this.logger); + } catch (rescheduleErr) { + // can not be rescheduled - log the error + errorLogger( + this.logger, + `Could not reschedule the errored job ${jobId}!`, + rescheduleErr + ); + } + } else { + // 0 attempts remain - fail the job + try { + if (report == null) { + throw new Error(`Report ${jobId} is null!`); + } + const error = mapToReportingError(failedToExecuteErr); + error.details = + error.details || + `Max attempts (${attempts}) reached for job ${jobId}. Failed with: ${failedToExecuteErr.message}`; + const resp = await this._failJob(report, error); + report._seq_no = resp._seq_no; + report._primary_term = resp._primary_term; + } catch (failedToFailError) { + errorLogger(this.logger, `Could not fail ${jobId}!`, failedToFailError); + } + } + } finally { + this.reporting.untrackReport(jobId); + this.logger.debug(`Reports running: ${this.reporting.countConcurrentReports()}.`); + } + }, + + /* + * Called by Task Manager to stop the report execution process in case + * of timeout or server shutdown + */ + cancel: async () => { + if (jobId) { + this.logger.warn(`Cancelling job ${jobId}...`); + } + cancellationToken.cancel(); + }, + }; + }; + } + + public getTaskDefinition() { + // round up from ms to the nearest second + const queueTimeout = Math.ceil(numberToDuration(this.config.queue.timeout).asSeconds()) + 's'; + const maxConcurrency = this.config.queue.pollEnabled ? 1 : 0; + + return { + type: REPORTING_EXECUTE_TYPE, + title: 'Reporting: execute job', + createTaskRunner: this.getTaskRunner(), + maxAttempts: 1, // NOTE: not using Task Manager retries + timeout: queueTimeout, + maxConcurrency, + }; + } + + public async scheduleTask(params: ReportTaskParams) { + const taskInstance: ReportingExecuteTaskInstance = { + taskType: REPORTING_EXECUTE_TYPE, + state: {}, + params, + }; + + return await this.getTaskManagerStart().schedule(taskInstance); + } + + private async rescheduleTask(task: ReportTaskParams, logger: Logger) { + logger.info(`Rescheduling task:${task.id} to retry after error.`); + + const oldTaskInstance: ReportingExecuteTaskInstance = { + taskType: REPORTING_EXECUTE_TYPE, + state: {}, + params: task, + }; + const newTask = await this.getTaskManagerStart().schedule(oldTaskInstance); + logger.debug(`Rescheduled task:${task.id}. New task: task:${newTask.id}`); + return newTask; + } + + public getStatus() { + if (this.taskManagerStart) { + return ReportingTaskStatus.INITIALIZED; + } + + return ReportingTaskStatus.UNINITIALIZED; + } +} diff --git a/x-pack/plugins/reporting_export_types/server/routes/lib/request_handler.ts b/x-pack/plugins/reporting_export_types/server/routes/lib/request_handler.ts new file mode 100644 index 0000000000000..ef123c78fb865 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/routes/lib/request_handler.ts @@ -0,0 +1,218 @@ +/* + * 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 moment from 'moment'; +import Boom from '@hapi/boom'; +import { i18n } from '@kbn/i18n'; +import type { KibanaRequest, KibanaResponseFactory, Logger } from '@kbn/core/server'; +import { LayoutParams } from '@kbn/screenshotting-plugin/common'; +import { API_BASE_URL } from '@kbn/reporting-plugin/common/constants'; +import { + BaseParams, + BasePayload, + ReportingRequestHandlerContext, + ReportingUser, +} from '@kbn/reporting-plugin/server/types'; +import { checkParamsVersion, cryptoFactory } from '@kbn/reporting-plugin/server/lib'; +import { Report } from '@kbn/reporting-plugin/server/lib/store'; +import { Counters } from '@kbn/reporting-plugin/server/routes/lib'; +import { ReportingCore } from '@kbn/reporting-plugin/server'; + +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`; +}; + +/** + * Handles the common parts of requests to generate a report + */ +export class RequestHandler { + constructor( + private reporting: ReportingCore, + private user: ReportingUser, + private context: ReportingRequestHandlerContext, + private req: KibanaRequest, + private res: KibanaResponseFactory, + private logger: Logger + ) {} + + private async encryptHeaders() { + const encryptionKey = this.reporting.getConfig().get('encryptionKey'); + const crypto = cryptoFactory(encryptionKey); + return await crypto.encrypt(this.req.headers); + } + + public async enqueueJob(exportTypeId: string, jobParams: BaseParams) { + const { reporting, logger, context, req: request, user } = this; + + const exportType = reporting.getExportTypesRegistry().getById(exportTypeId); + + if (exportType == null) { + throw new Error(`Export type ${exportTypeId} does not exist in the registry!`); + } + + if (!exportType.createJobFnFactory) { + throw new Error(`Export type ${exportTypeId} is not an async job type!`); + } + + const [createJob, store] = await Promise.all([ + exportType.createJobFnFactory(reporting, logger.get(exportType.id)), + reporting.getStore(), + ]); + + if (!createJob) { + throw new Error(`Export type ${exportTypeId} is not an async job type!`); + } + + // 1. ensure the incoming params have a version field (should be set by the UI) + jobParams.version = checkParamsVersion(jobParams, logger); + + // 2. encrypt request headers for the running report job to authenticate itself with Kibana + // 3. call the export type's createJobFn to create the job payload + const [headers, job] = await Promise.all([ + this.encryptHeaders(), + createJob(jobParams, context, this.req), + ]); + + const payload = { + ...job, + headers, + spaceId: reporting.getSpaceId(request, logger), + }; + + // 4. Add the report to ReportingStore to show as pending + const report = await store.addReport( + new Report({ + jobtype: exportType.jobType, + created_by: user ? user.username : false, + payload, + meta: { + // telemetry fields + objectType: jobParams.objectType, + layout: jobParams.layout?.id, + isDeprecated: job.isDeprecated, + }, + }) + ); + logger.debug(`Successfully stored pending job: ${report._index}/${report._id}`); + + // 5. Schedule the report with Task Manager + const task = await reporting.scheduleTask(report.toReportTaskJSON()); + logger.info( + `Scheduled ${exportType.name} reporting task. Task ID: task:${task.id}. Report ID: ${report._id}` + ); + + // 6. Log the action with event log + reporting.getEventLogger(report, task).logScheduleTask(); + + return report; + } + + public async handleGenerateRequest( + exportTypeId: string, + jobParams: BaseParams, + counters: Counters + ) { + // ensure the async dependencies are loaded + if (!this.context.reporting) { + return handleUnavailable(this.res); + } + + const licenseInfo = await this.reporting.getLicenseInfo(); + const licenseResults = licenseInfo[exportTypeId]; + + if (!licenseResults) { + return this.res.badRequest({ body: `Invalid export-type of ${exportTypeId}` }); + } + + if (!licenseResults.enableLinks) { + return this.res.forbidden({ body: licenseResults.message }); + } + + if (jobParams.browserTimezone && !moment.tz.zone(jobParams.browserTimezone)) { + return this.res.badRequest({ + body: `Invalid timezone "${jobParams.browserTimezone ?? ''}".`, + }); + } + + let report: Report | undefined; + try { + report = await this.enqueueJob(exportTypeId, jobParams); + + // return task manager's task information and the download URL + const downloadBaseUrl = getDownloadBaseUrl(this.reporting); + + counters.usageCounter(); + + return this.res.ok({ + headers: { 'content-type': 'application/json' }, + body: { + path: `${downloadBaseUrl}/${report._id}`, + job: report.toApiJSON(), + }, + }); + } catch (err) { + return this.handleError(err, counters, report?.jobtype); + } + } + + private handleError(err: Error | Boom.Boom, counters: Counters, jobtype?: string) { + this.logger.error(err); + + if (err instanceof Boom.Boom) { + const statusCode = err.output.statusCode; + counters?.errorCounter(jobtype, statusCode); + + return this.res.customError({ + statusCode, + body: err.output.payload.message, + }); + } + + counters?.errorCounter(jobtype, 500); + + return this.res.customError({ + statusCode: 500, + body: + err?.message || + i18n.translate('xpack.reportingExportTypes.errorHandler.unknownError', { + defaultMessage: 'Unknown error', + }), + }); + } +} + +interface BaseParamsPDF { + layout: LayoutParams; + relativeUrls: string[]; + isDeprecated?: boolean; +} + +// Job params: structure of incoming user request data, after being parsed from RISON + +/** + * @deprecated + */ +export type JobAppParamsPDF = Omit; + +/** + * Structure of stored job data provided by create_job + */ +export interface TaskPayloadPDF extends BasePayload { + layout: LayoutParams; + forceNow?: string; + objects: Array<{ relativeUrl: string }>; +} + +/** + * @deprecated + */ +export type JobParamsPDFDeprecated = BaseParamsPDF & BaseParams; diff --git a/x-pack/plugins/reporting_export_types/server/services/services.ts b/x-pack/plugins/reporting_export_types/server/services/services.ts new file mode 100644 index 0000000000000..a09442ec32793 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/services/services.ts @@ -0,0 +1,12 @@ +/* + * 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 { FieldFormatsStart } from '@kbn/field-formats-plugin/server'; +import { createGetterSetter } from '@kbn/kibana-utils-plugin/server'; + +export const [getFieldFormats, setFieldFormats] = + createGetterSetter('FieldFormats'); diff --git a/x-pack/plugins/reporting_export_types/server/types.ts b/x-pack/plugins/reporting_export_types/server/types.ts new file mode 100644 index 0000000000000..edda6a7bdbbd7 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/server/types.ts @@ -0,0 +1,13 @@ +import { Logger } from '@kbn/core/server'; +import { ReportingCore } from '@kbn/reporting-plugin/server'; +import { ReportingExportTypesCore } from './core'; + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface ReportingExportTypesPluginSetup {} +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface ReportingExportTypesPluginStart {} + +export type RunTaskFnFactory = ( + reporting: ReportingExportTypesCore | ReportingCore, + logger: Logger +) => RunTaskFnType; diff --git a/x-pack/plugins/reporting_export_types/tsconfig.json b/x-pack/plugins/reporting_export_types/tsconfig.json new file mode 100644 index 0000000000000..5cfc7ecb73e77 --- /dev/null +++ b/x-pack/plugins/reporting_export_types/tsconfig.json @@ -0,0 +1,37 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "target/types" + }, + "include": [ + "common/**/*.ts", + "common/*.ts", + "server/**/**/*", + "server/**/*.ts", + ], + "kbn_references": [ + "@kbn/reporting-common", + "@kbn/screenshotting-plugin", + "@kbn/data-plugin", + "@kbn/core", + "@kbn/i18n", + "@kbn/generate-csv", + "@kbn/core-plugins-server", + "@kbn/reporting-plugin", + "@kbn/field-formats-plugin", + "@kbn/kibana-utils-plugin", + "@kbn/config-schema", + "@kbn/core-test-helpers-test-utils", + "@kbn/security-plugin", + "@kbn/spaces-plugin", + "@kbn/usage-collection-plugin", + "@kbn/rison", + "@kbn/licensing-plugin", + "@kbn/task-manager-plugin", + "@kbn/discover-plugin", + "@kbn/core-http-server", + ], + "exclude": [ + "target/**/*", + ] +} diff --git a/x-pack/plugins/translations/translations/fr-FR.json b/x-pack/plugins/translations/translations/fr-FR.json index 533f04aab9796..06c158676f757 100644 --- a/x-pack/plugins/translations/translations/fr-FR.json +++ b/x-pack/plugins/translations/translations/fr-FR.json @@ -26223,10 +26223,10 @@ "xpack.reporting.deprecations.reportingRoles.title": "Le paramètre \"{fromPath}.roles\" est déclassé", "xpack.reporting.deprecations.reportingRoleUsers.manualStepFive": "Supprimez le rôle \"reporting_user\" pour tous les utilisateurs et ajoutez le rôle personnalisé. Les utilisateurs concernés sont les suivants : {usersRoles}.", "xpack.reporting.deprecations.reportingRoleUsers.title": "Le rôle \"{reportingUserRoleName}\" est déclassé : vérifiez les rôles utilisateur", - "xpack.reporting.diagnostic.browserMissingDependency": "Le navigateur n'a pas pu démarrer correctement en raison de dépendances système manquantes. Veuillez consulter {url}", - "xpack.reporting.diagnostic.browserMissingFonts": "Le navigateur n'a pas réussi à localiser de police par défaut. Consultez {url} pour corriger ce problème.", - "xpack.reporting.diagnostic.noUsableSandbox": "Impossible d'utiliser la sandbox Chromium. Vous pouvez la désactiver à vos risques et périls avec \"xpack.screenshotting.browser.chromium.disableSandbox\". Veuillez consulter {url}", - "xpack.reporting.exportTypes.common.failedToDecryptReportJobDataErrorMessage": "Impossible de déchiffrer les données de la tâche de reporting. Veuillez vous assurer que {encryptionKey} est défini et générez à nouveau ce rapport. {err}", + "xpack.reportingExportTypes.diagnostic.browserMissingDependency": "Le navigateur n'a pas pu démarrer correctement en raison de dépendances système manquantes. Veuillez consulter {url}", + "xpack.reportingExportTypes.diagnostic.browserMissingFonts": "Le navigateur n'a pas réussi à localiser de police par défaut. Consultez {url} pour corriger ce problème.", + "xpack.reportingExportTypes.diagnostic.noUsableSandbox": "Impossible d'utiliser la sandbox Chromium. Vous pouvez la désactiver à vos risques et périls avec \"xpack.screenshotting.browser.chromium.disableSandbox\". Veuillez consulter {url}", + "xpack.reportingExportTypes.failedToDecryptReportJobDataErrorMessage": "Impossible de déchiffrer les données de la tâche de reporting. Veuillez vous assurer que {encryptionKey} est défini et générez à nouveau ce rapport. {err}", "xpack.reporting.jobResponse.errorHandler.notAuthorized": "Désolé, vous n'êtes pas autorisé à afficher ou supprimer les rapports {jobtype}", "xpack.reporting.jobsQuery.deleteError": "Impossible de supprimer le rapport : {error}", "xpack.reporting.jobStatusDetail.attemptXofY": "Tentative {attempts} sur {max_attempts}.", @@ -26254,6 +26254,7 @@ "xpack.reporting.statusIndicator.processingLabel": "En cours de traitement, tentative {attempt}", "xpack.reporting.statusIndicator.processingMaxAttemptsLabel": "En cours de traitement, tentative {attempt} sur {of}", "xpack.reporting.userAccessError.message": "Demandez à votre administrateur un accès aux fonctionnalités de reporting. {grantUserAccessDocs}.", + "xpack.reportingExportTypes.userAccessError.message": "Demandez à votre administrateur un accès aux fonctionnalités de reporting. {grantUserAccessDocs}.", "xpack.reporting.breadcrumb": "Reporting", "xpack.reporting.dashboard.csvDownloadStartedMessage": "Votre CSV sera téléchargé dans un instant.", "xpack.reporting.dashboard.csvDownloadStartedTitle": "Téléchargement du CSV démarré", @@ -26280,9 +26281,10 @@ "xpack.reporting.deprecations.reportingRoleUsers.manualStepOne": "Définissez \"xpack.reporting.roles.enabled\" sur \"false\" dans le fichier kibana.yml.", "xpack.reporting.deprecations.reportingRoleUsers.manualStepThree": "Sous Gestion > Sécurité > Rôles, créez un ou plusieurs rôles permettant d'accorder le privilège de l'application Kibana à Reporting.", "xpack.reporting.deprecations.reportingRoleUsers.manualStepTwo": "Supprimez le paramètre \"xpack.reporting.roles.allow\" du fichier kibana.yml, le cas échéant.", - "xpack.reporting.diagnostic.screenshotFailureMessage": "Impossible d'effectuer une capture d'écran de votre installation Kibana.", + "xpack.reportingExportTypes.diagnostic.screenshotFailureMessage": "Impossible d'effectuer une capture d'écran de votre installation Kibana.", "xpack.reporting.errorHandler.unknownError": "Erreur inconnue", - "xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage": "Les en-têtes de tâche sont manquants", + "xpack.reportingExportTypes.errorHandler.unknownError": "Erreur inconnue", + "xpack.reportingExportTypes.missingJobHeadersErrorMessage": "Les en-têtes de tâche sont manquants", "xpack.reporting.jobCreatedBy.unknownUserPlaceholderText": "Inconnu", "xpack.reporting.jobResponse.errorHandler.unknownError": "Erreur inconnue", "xpack.reporting.jobStatusDetail.deprecatedText": "Il s'agit d'un type d'exportation déclassé. L'automatisation de ce rapport devra être à nouveau créée pour une question de compatibilité avec les futures versions de Kibana.", @@ -26417,8 +26419,9 @@ "xpack.reporting.statusIndicator.pendingLabel": "En attente", "xpack.reporting.statusIndicator.unknownLabel": "Inconnu", "xpack.reporting.uiSettings.validate.customLogo.badFile": "Désolé, ce fichier ne convient pas. Veuillez essayer un autre fichier image.", - "xpack.reporting.uiSettings.validate.customLogo.tooLarge": "Désolé, ce fichier est trop volumineux. Le fichier image doit être inférieur à 200 kilo-octets.", "xpack.reporting.userAccessError.learnMoreLink": "En savoir plus", + "xpack.reporting.uiSettings.validate.customLogo.tooLarge": "Désolé, ce fichier est trop volumineux. Le fichier image doit être inférieur à 200 kilo-octets.", + "xpack.reportingExportTypes.userAccessError.learnMoreLink": "En savoir plus", "generateCsv.esErrorMessage": "Réponse {statusCode} reçue d'Elasticsearch : {message}", "generateCsv.incorrectRowCount": "Une erreur a été rencontrée avec le nombre de lignes CSV générées à partir de la recherche : {expected} prévues, {received} reçues.", "generateCsv.unknownErrorMessage": "Une erreur inconnue est survenue : {message}", diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 6aabae0e6ed5a..06084bf8fce0f 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -26204,10 +26204,10 @@ "xpack.reporting.deprecations.reportingRoles.title": "\"{fromPath}.roles\"設定は廃止予定です", "xpack.reporting.deprecations.reportingRoleUsers.manualStepFive": "すべてのユーザーから「reporting_user」ロールを削除し、カスタムロールを追加します。影響を受けるユーザー:{usersRoles}。", "xpack.reporting.deprecations.reportingRoleUsers.title": "\"{reportingUserRoleName}\"ロールは廃止予定です。ユーザーロールを確認してください", - "xpack.reporting.diagnostic.browserMissingDependency": "システム依存関係が不足しているため、ブラウザーを正常に起動できませんでした。{url}を参照してください", - "xpack.reporting.diagnostic.browserMissingFonts": "ブラウザーはデフォルトフォントを検索できませんでした。この問題を修正するには、{url}を参照してください。", - "xpack.reporting.diagnostic.noUsableSandbox": "Chromiumサンドボックスを使用できません。これは「xpack.screenshotting.browser.chromium.disableSandbox」で無効にすることができます。この作業はご自身の責任で行ってください。{url}を参照してください", - "xpack.reporting.exportTypes.common.failedToDecryptReportJobDataErrorMessage": "レポートジョブデータの解読に失敗しました。{encryptionKey} が設定されていることを確認してこのレポートを再生成してください。{err}", + "xpack.reportingExportTypes.diagnostic.browserMissingDependency": "システム依存関係が不足しているため、ブラウザーを正常に起動できませんでした。{url}を参照してください", + "xpack.reportingExportTypes.diagnostic.browserMissingFonts": "ブラウザーはデフォルトフォントを検索できませんでした。この問題を修正するには、{url}を参照してください。", + "xpack.reportingExportTypes.diagnostic.noUsableSandbox": "Chromiumサンドボックスを使用できません。これは「xpack.screenshotting.browser.chromium.disableSandbox」で無効にすることができます。この作業はご自身の責任で行ってください。{url}を参照してください", + "xpack.reportingExportTypes.failedToDecryptReportJobDataErrorMessage": "レポートジョブデータの解読に失敗しました。{encryptionKey} が設定されていることを確認してこのレポートを再生成してください。{err}", "xpack.reporting.jobResponse.errorHandler.notAuthorized": "{jobtype}レポートを表示または削除する権限がありません", "xpack.reporting.jobsQuery.deleteError": "レポートを削除できません:{error}", "xpack.reporting.jobStatusDetail.attemptXofY": "{max_attempts}回中{attempts}回試行します。", @@ -26234,7 +26234,7 @@ "xpack.reporting.statusIndicator.lastStatusUpdateLabel": "更新日:{date}", "xpack.reporting.statusIndicator.processingLabel": "処理中。{attempt}回試行", "xpack.reporting.statusIndicator.processingMaxAttemptsLabel": "処理中。{attempt}/{of}回試行", - "xpack.reporting.userAccessError.message": "レポート機能にアクセスするには、管理者に問い合わせてください。{grantUserAccessDocs}。", + "xpack.reportingExportTypes.userAccessError.message": "レポート機能にアクセスするには、管理者に問い合わせてください。{grantUserAccessDocs}。", "xpack.reporting.breadcrumb": "レポート", "xpack.reporting.dashboard.csvDownloadStartedMessage": "間もなく CSV がダウンロードされます。", "xpack.reporting.dashboard.csvDownloadStartedTitle": "CSV のダウンロードが開始しました", @@ -26261,9 +26261,10 @@ "xpack.reporting.deprecations.reportingRoleUsers.manualStepOne": "kibana.ymlで「xpack.reporting.roles.enabled」をfalseに設定します。", "xpack.reporting.deprecations.reportingRoleUsers.manualStepThree": "[管理]>[セキュリティ]>[ロール]から、レポートのKibanaアプリケーション権限を付与する1つ以上のロールを作成します。", "xpack.reporting.deprecations.reportingRoleUsers.manualStepTwo": "存在する場合は、kibana.ymlで「xpack.reporting.roles.allow」を削除します。", - "xpack.reporting.diagnostic.screenshotFailureMessage": "Kibanaインストールのスクリーンショットを作成できませんでした。", + "xpack.reportingExportTypes.diagnostic.screenshotFailureMessage": "Kibanaインストールのスクリーンショットを作成できませんでした。", "xpack.reporting.errorHandler.unknownError": "不明なエラー", - "xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage": "ジョブヘッダーがありません", + "xpack.reportingExportTypes.errorHandler.unknownError": "不明なエラー", + "xpack.reportingExportTypes.missingJobHeadersErrorMessage": "ジョブヘッダーがありません", "xpack.reporting.jobCreatedBy.unknownUserPlaceholderText": "不明", "xpack.reporting.jobResponse.errorHandler.unknownError": "不明なエラー", "xpack.reporting.jobStatusDetail.deprecatedText": "これは廃止予定のエクスポートタイプです。将来のバージョンのKibanaとの互換性のためには、このレポートの自動化を再作成する必要があります。", @@ -26398,8 +26399,9 @@ "xpack.reporting.statusIndicator.pendingLabel": "保留中", "xpack.reporting.statusIndicator.unknownLabel": "不明", "xpack.reporting.uiSettings.validate.customLogo.badFile": "このファイルは動作しません。別の画像ファイルを試してください。", - "xpack.reporting.uiSettings.validate.customLogo.tooLarge": "このファイルは大きすぎます。画像ファイルは200キロバイト未満でなければなりません。", "xpack.reporting.userAccessError.learnMoreLink": "詳細", + "xpack.reporting.uiSettings.validate.customLogo.tooLarge": "このファイルは大きすぎます。画像ファイルは200キロバイト未満でなければなりません。", + "xpack.reportingExportTypes.userAccessError.learnMoreLink": "詳細", "generateCsv.esErrorMessage": "Elasticsearchから{statusCode}応答を受け取りました:{message}", "generateCsv.incorrectRowCount": "検索から生成されたCSVの行数でエラーが発生しました。正しい行数:{expected}、実際の行数:{received}。", "generateCsv.unknownErrorMessage": "不明なエラーが発生しました:{message}", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 22fe6e5ab15df..2165a1c819e1e 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -26221,10 +26221,10 @@ "xpack.reporting.deprecations.reportingRoles.title": "“{fromPath}.roles”设置已过时", "xpack.reporting.deprecations.reportingRoleUsers.manualStepFive": "从所有用户中移除“reporting_user”角色,然后添加定制角色。受影响的用户为:{usersRoles}。", "xpack.reporting.deprecations.reportingRoleUsers.title": "“{reportingUserRoleName}”角色已过时:检查用户角色", - "xpack.reporting.diagnostic.browserMissingDependency": "由于缺少系统依赖项,浏览器无法正常启动。请参见 {url}", - "xpack.reporting.diagnostic.browserMissingFonts": "浏览器找不到默认字体。请参见 {url} 以解决此问题。", - "xpack.reporting.diagnostic.noUsableSandbox": "无法使用 Chromium 沙盒。您自行承担使用“xpack.screenshotting.browser.chromium.disableSandbox”禁用此项的风险。请参见 {url}", - "xpack.reporting.exportTypes.common.failedToDecryptReportJobDataErrorMessage": "无法解密报告作业数据。请确保已设置 {encryptionKey},然后重新生成此报告。{err}", + "xpack.reportingExportTypes.diagnostic.browserMissingDependency": "由于缺少系统依赖项,浏览器无法正常启动。请参见 {url}", + "xpack.reportingExportTypes.diagnostic.browserMissingFonts": "浏览器找不到默认字体。请参见 {url} 以解决此问题。", + "xpack.reportingExportTypes.diagnostic.noUsableSandbox": "无法使用 Chromium 沙盒。您自行承担使用“xpack.screenshotting.browser.chromium.disableSandbox”禁用此项的风险。请参见 {url}", + "xpack.reportingExportTypes.failedToDecryptReportJobDataErrorMessage": "无法解密报告作业数据。请确保已设置 {encryptionKey},然后重新生成此报告。{err}", "xpack.reporting.jobResponse.errorHandler.notAuthorized": "抱歉,您无权查看或删除 {jobtype} 报告", "xpack.reporting.jobsQuery.deleteError": "无法删除报告:{error}", "xpack.reporting.jobStatusDetail.attemptXofY": "尝试 {attempts} 次,最多可尝试 {max_attempts} 次。", @@ -26251,7 +26251,7 @@ "xpack.reporting.statusIndicator.lastStatusUpdateLabel": "于 {date}更新", "xpack.reporting.statusIndicator.processingLabel": "正在处理,尝试 {attempt}", "xpack.reporting.statusIndicator.processingMaxAttemptsLabel": "正在处理,尝试 {attempt} {of}", - "xpack.reporting.userAccessError.message": "请联系管理员以访问报告功能。{grantUserAccessDocs}.", + "xpack.reportingExportTypes.userAccessError.message": "请联系管理员以访问报告功能。{grantUserAccessDocs}.", "xpack.reporting.breadcrumb": "Reporting", "xpack.reporting.dashboard.csvDownloadStartedMessage": "您的 CSV 将很快下载。", "xpack.reporting.dashboard.csvDownloadStartedTitle": "CSV 下载已开始", @@ -26278,9 +26278,10 @@ "xpack.reporting.deprecations.reportingRoleUsers.manualStepOne": "在 kibana.yml 中将“xpack.reporting.roles.enabled”设置为“false”。", "xpack.reporting.deprecations.reportingRoleUsers.manualStepThree": "前往“管理”>“安全性”>“角色”以创建一个或多个针对 Reporting 授予 Kibana 应用程序权限的角色。", "xpack.reporting.deprecations.reportingRoleUsers.manualStepTwo": "移除 kibana.yml 中的“xpack.reporting.roles.allow”(如果存在)。", - "xpack.reporting.diagnostic.screenshotFailureMessage": "我们无法拍摄 Kibana 安装的屏幕截图。", + "xpack.reportingExportTypes.diagnostic.screenshotFailureMessage": "我们无法拍摄 Kibana 安装的屏幕截图。", "xpack.reporting.errorHandler.unknownError": "未知错误", - "xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage": "作业标头缺失", + "xpack.reportingExportTypes.errorHandler.unknownError": "未知错误", + "xpack.reportingExportTypes.missingJobHeadersErrorMessage": "作业标头缺失", "xpack.reporting.jobCreatedBy.unknownUserPlaceholderText": "未知", "xpack.reporting.jobResponse.errorHandler.unknownError": "未知错误", "xpack.reporting.jobStatusDetail.deprecatedText": "这是已弃用的导出类型。此报告的自动化将需要重新创建,才能与未来版本的 Kibana 兼容。", @@ -26415,8 +26416,9 @@ "xpack.reporting.statusIndicator.pendingLabel": "待处理", "xpack.reporting.statusIndicator.unknownLabel": "未知", "xpack.reporting.uiSettings.validate.customLogo.badFile": "抱歉,该文件无效。请尝试其他图像文件。", - "xpack.reporting.uiSettings.validate.customLogo.tooLarge": "抱歉,该文件过大。图像文件必须小于 200 千字节。", "xpack.reporting.userAccessError.learnMoreLink": "了解详情", + "xpack.reporting.uiSettings.validate.customLogo.tooLarge": "抱歉,该文件过大。图像文件必须小于 200 千字节。", + "xpack.reportingExportTypes.userAccessError.learnMoreLink": "了解详情", "generateCsv.esErrorMessage": "从 Elasticsearch 收到 {statusCode} 响应:{message}", "generateCsv.incorrectRowCount": "从搜索生成的 CSV 行数出现错误:应为 {expected},但收到 {received}。", "generateCsv.unknownErrorMessage": "出现未知错误:{message}", diff --git a/x-pack/test/reporting_api_integration/reporting_and_security/csv_v2.ts b/x-pack/test/reporting_api_integration/reporting_and_security/csv_v2.ts index 04ff7adc357e3..9f1b54cae4b49 100644 --- a/x-pack/test/reporting_api_integration/reporting_and_security/csv_v2.ts +++ b/x-pack/test/reporting_api_integration/reporting_and_security/csv_v2.ts @@ -7,12 +7,10 @@ import { DISCOVER_APP_LOCATOR } from '@kbn/discover-plugin/common'; import expect from '@kbn/expect'; -import type { - JobParamsCsvFromSavedObject, - ReportApiJSON, -} from '@kbn/reporting-plugin/common/types'; import rison from '@kbn/rison'; import request from 'supertest'; +import { JobParamsCsvFromSavedObject } from '@kbn/reporting-export-types/common'; +import { ReportApiJSON } from '@kbn/reporting-plugin/common/types'; import { FtrProviderContext } from '../ftr_provider_context'; const LOGSTASH_DATA_ARCHIVE = 'test/functional/fixtures/es_archiver/logstash_functional'; diff --git a/x-pack/test/reporting_api_integration/reporting_and_security/download_csv_dashboard.ts b/x-pack/test/reporting_api_integration/reporting_and_security/download_csv_dashboard.ts index 3941037733c70..2b03358902b61 100644 --- a/x-pack/test/reporting_api_integration/reporting_and_security/download_csv_dashboard.ts +++ b/x-pack/test/reporting_api_integration/reporting_and_security/download_csv_dashboard.ts @@ -6,8 +6,8 @@ */ import expect from '@kbn/expect'; +import type { JobParamsDownloadCSV } from '@kbn/reporting-plugin/server'; import supertest from 'supertest'; -import { JobParamsDownloadCSV } from '@kbn/reporting-plugin/server/export_types/csv_searchsource_immediate/types'; import { FtrProviderContext } from '../ftr_provider_context'; const getMockJobParams = (obj: object) => { diff --git a/x-pack/test/reporting_api_integration/reporting_without_security/job_apis_csv.ts b/x-pack/test/reporting_api_integration/reporting_without_security/job_apis_csv.ts index 22be1d776e792..eebdd6bb0adfc 100644 --- a/x-pack/test/reporting_api_integration/reporting_without_security/job_apis_csv.ts +++ b/x-pack/test/reporting_api_integration/reporting_without_security/job_apis_csv.ts @@ -6,8 +6,8 @@ */ import expect from '@kbn/expect'; -import { pick } from 'lodash'; import { ReportApiJSON } from '@kbn/reporting-plugin/common/types'; +import { pick } from 'lodash'; import { FtrProviderContext } from '../ftr_provider_context'; const apiResponseFields = [ diff --git a/x-pack/test/reporting_api_integration/services/scenarios.ts b/x-pack/test/reporting_api_integration/services/scenarios.ts index 181af370e42c6..69c43098ac577 100644 --- a/x-pack/test/reporting_api_integration/services/scenarios.ts +++ b/x-pack/test/reporting_api_integration/services/scenarios.ts @@ -10,12 +10,10 @@ import { API_GET_ILM_POLICY_STATUS, API_MIGRATE_ILM_POLICY_URL, } from '@kbn/reporting-plugin/common/constants'; -import { JobParamsCSV } from '@kbn/reporting-plugin/server/export_types/csv_searchsource/types'; -import { JobParamsDownloadCSV } from '@kbn/reporting-plugin/server/export_types/csv_searchsource_immediate/types'; -import { JobParamsPNGDeprecated } from '@kbn/reporting-plugin/server/export_types/png/types'; -import { JobParamsPDFDeprecated } from '@kbn/reporting-plugin/server/export_types/printable_pdf/types'; +import { JobParamsPDFDeprecated } from '@kbn/reporting-plugin/server/routes/lib'; +import type { JobParamsCSV, JobParamsPNGDeprecated } from '@kbn/reporting-export-types/common'; +import { JobParamsDownloadCSV } from '@kbn/reporting-plugin/server/routes'; import { FtrProviderContext } from '../ftr_provider_context'; - function removeWhitespace(str: string) { return str.replace(/\s/g, ''); } diff --git a/x-pack/test/tsconfig.json b/x-pack/test/tsconfig.json index 91a8e991fcdda..b2f0f482adf84 100644 --- a/x-pack/test/tsconfig.json +++ b/x-pack/test/tsconfig.json @@ -125,5 +125,6 @@ "@kbn/guided-onboarding-plugin", "@kbn/field-formats-plugin", "@kbn/ml-anomaly-utils", + "@kbn/reporting-export-types" ] } diff --git a/yarn.lock b/yarn.lock index ba14036692580..e6eac67978d89 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4798,6 +4798,10 @@ version "0.0.0" uid "" +"@kbn/reporting-export-types@link:x-pack/plugins/reporting_export_types": + version "0.0.0" + uid "" + "@kbn/reporting-plugin@link:x-pack/plugins/reporting": version "0.0.0" uid ""