diff --git a/package.json b/package.json index 13fd9cebdbe8d..69c83edf2c8dc 100644 --- a/package.json +++ b/package.json @@ -871,7 +871,7 @@ "terser-webpack-plugin": "^4.2.3", "tough-cookie": "^4.0.0", "ts-loader": "^7.0.5", - "ts-morph": "^11.0.0", + "ts-morph": "^13.0.2", "tsd": "^0.13.1", "typescript": "4.5.3", "unlazy-loader": "^0.1.3", diff --git a/packages/kbn-docs-utils/src/api_docs/build_api_declarations/build_api_declaration.ts b/packages/kbn-docs-utils/src/api_docs/build_api_declarations/build_api_declaration.ts index 55ab51b1208b4..bf8beadea4d91 100644 --- a/packages/kbn-docs-utils/src/api_docs/build_api_declarations/build_api_declaration.ts +++ b/packages/kbn-docs-utils/src/api_docs/build_api_declarations/build_api_declaration.ts @@ -80,7 +80,7 @@ export function buildApiDeclaration(node: Node, opts: BuildApiDecOpts): ApiDecla Node.isVariableDeclaration(node) ) { return buildVariableDec(node, opts); - } else if (Node.isTypeLiteralNode(node)) { + } else if (Node.isTypeLiteral(node)) { return buildTypeLiteralDec(node, opts); } diff --git a/packages/kbn-docs-utils/src/api_docs/build_api_declarations/get_references.ts b/packages/kbn-docs-utils/src/api_docs/build_api_declarations/get_references.ts index 5055723aa445a..108e018f82c85 100644 --- a/packages/kbn-docs-utils/src/api_docs/build_api_declarations/get_references.ts +++ b/packages/kbn-docs-utils/src/api_docs/build_api_declarations/get_references.ts @@ -73,7 +73,7 @@ export function maybeCollectReferences({ apiDec, captureReferences, }: MaybeCollectReferencesOpt): ApiReference[] | undefined { - if (Node.isReferenceFindableNode(node)) { + if (Node.isReferenceFindable(node)) { return captureReferences || apiDec.deprecated ? getReferences({ node, plugins, currentPluginId, log }) : undefined; diff --git a/packages/kbn-docs-utils/src/api_docs/build_api_declarations/js_doc_utils.ts b/packages/kbn-docs-utils/src/api_docs/build_api_declarations/js_doc_utils.ts index 7b6ac5a6ec5f6..34e9924578e8c 100644 --- a/packages/kbn-docs-utils/src/api_docs/build_api_declarations/js_doc_utils.ts +++ b/packages/kbn-docs-utils/src/api_docs/build_api_declarations/js_doc_utils.ts @@ -30,11 +30,11 @@ export function getCommentsFromNode(node: Node): TextWithLinks | undefined { } export function getJSDocs(node: Node): JSDoc[] | undefined { - if (Node.isJSDocableNode(node)) { + if (Node.isJSDocable(node)) { return node.getJsDocs(); } else if (Node.isVariableDeclaration(node)) { const gparent = node.getParent()?.getParent(); - if (Node.isJSDocableNode(gparent)) { + if (Node.isJSDocable(gparent)) { return gparent.getJsDocs(); } } diff --git a/packages/kbn-docs-utils/src/api_docs/build_api_declarations/utils.ts b/packages/kbn-docs-utils/src/api_docs/build_api_declarations/utils.ts index 6a4177f53a973..a57b1790b27a8 100644 --- a/packages/kbn-docs-utils/src/api_docs/build_api_declarations/utils.ts +++ b/packages/kbn-docs-utils/src/api_docs/build_api_declarations/utils.ts @@ -18,7 +18,10 @@ import { isNamedNode } from '../tsmorph_utils'; export const pathsOutsideScopes: { [key: string]: string } = {}; export function isPrivate(node: ParameterDeclaration | ClassMemberTypes): boolean { - return node.getModifiers().find((mod) => mod.getText() === 'private') !== undefined; + if (Node.isModifierable(node)) { + return node.getModifiers().find((mod) => mod.getText() === 'private') !== undefined; + } + return false; } /** diff --git a/packages/kbn-server-route-repository/src/create_server_route_factory.ts b/packages/kbn-server-route-repository/src/create_server_route_factory.ts index edf9bd657f995..b506b5263e857 100644 --- a/packages/kbn-server-route-repository/src/create_server_route_factory.ts +++ b/packages/kbn-server-route-repository/src/create_server_route_factory.ts @@ -27,12 +27,9 @@ export function createServerRouteFactory< TReturnType, TRouteCreateOptions > -) => ServerRoute< +) => Record< TEndpoint, - TRouteParamsRT, - TRouteHandlerResources, - TReturnType, - TRouteCreateOptions + ServerRoute > { - return (route) => route; + return (route) => ({ [route.endpoint]: route } as any); } diff --git a/packages/kbn-server-route-repository/src/create_server_route_repository.ts b/packages/kbn-server-route-repository/src/create_server_route_repository.ts deleted file mode 100644 index 5ac89ebcac77f..0000000000000 --- a/packages/kbn-server-route-repository/src/create_server_route_repository.ts +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 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 { - ServerRouteHandlerResources, - ServerRouteRepository, - ServerRouteCreateOptions, -} from './typings'; - -export function createServerRouteRepository< - TRouteHandlerResources extends ServerRouteHandlerResources = never, - TRouteCreateOptions extends ServerRouteCreateOptions = never ->(): ServerRouteRepository { - let routes: Record = {}; - - return { - add(route) { - routes = { - ...routes, - [route.endpoint]: route, - }; - - return this as any; - }, - merge(repository) { - routes = { - ...routes, - ...Object.fromEntries(repository.getRoutes().map((route) => [route.endpoint, route])), - }; - - return this as any; - }, - getRoutes: () => Object.values(routes), - }; -} diff --git a/packages/kbn-server-route-repository/src/index.ts b/packages/kbn-server-route-repository/src/index.ts index 7ba2b53159551..39c4110e4e232 100644 --- a/packages/kbn-server-route-repository/src/index.ts +++ b/packages/kbn-server-route-repository/src/index.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -export { createServerRouteRepository } from './create_server_route_repository'; export { createServerRouteFactory } from './create_server_route_factory'; export { formatRequest } from './format_request'; export { parseEndpoint } from './parse_endpoint'; diff --git a/packages/kbn-server-route-repository/src/test_types.ts b/packages/kbn-server-route-repository/src/test_types.ts index c9015e19b82f8..b1d74936d8aa0 100644 --- a/packages/kbn-server-route-repository/src/test_types.ts +++ b/packages/kbn-server-route-repository/src/test_types.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ import * as t from 'io-ts'; -import { createServerRouteRepository } from './create_server_route_repository'; +import { createServerRouteFactory } from './create_server_route_factory'; import { decodeRequestParams } from './decode_request_params'; import { EndpointOf, ReturnOf, RouteRepositoryClient } from './typings'; @@ -14,18 +14,9 @@ function assertType(value: TShape) { return value; } -// Generic arguments for createServerRouteRepository should be set, -// if not, registering routes should not be allowed -createServerRouteRepository().add({ - // @ts-expect-error - endpoint: 'any_endpoint', - // @ts-expect-error - handler: async ({ params }) => {}, -}); - // If a params codec is not set, its type should not be available in // the request handler. -createServerRouteRepository<{}, {}>().add({ +createServerRouteFactory<{}, {}>()({ endpoint: 'endpoint_without_params', handler: async (resources) => { // @ts-expect-error Argument of type '{}' is not assignable to parameter of type '{ params: any; }'. @@ -35,7 +26,7 @@ createServerRouteRepository<{}, {}>().add({ // If a params codec is set, its type _should_ be available in the // request handler. -createServerRouteRepository<{}, {}>().add({ +createServerRouteFactory<{}, {}>()({ endpoint: 'endpoint_with_params', params: t.type({ path: t.type({ @@ -48,7 +39,7 @@ createServerRouteRepository<{}, {}>().add({ }); // Resources should be passed to the request handler. -createServerRouteRepository<{ context: { getSpaceId: () => string } }, {}>().add({ +createServerRouteFactory<{ context: { getSpaceId: () => string } }, {}>()({ endpoint: 'endpoint_with_params', params: t.type({ path: t.type({ @@ -62,7 +53,7 @@ createServerRouteRepository<{ context: { getSpaceId: () => string } }, {}>().add }); // Create options are available when registering a route. -createServerRouteRepository<{}, { options: { tags: string[] } }>().add({ +createServerRouteFactory<{}, { options: { tags: string[] } }>()({ endpoint: 'endpoint_with_params', params: t.type({ path: t.type({ @@ -77,16 +68,18 @@ createServerRouteRepository<{}, { options: { tags: string[] } }>().add({ }, }); -const repository = createServerRouteRepository<{}, {}>() - .add({ +const createServerRoute = createServerRouteFactory<{}, {}>(); + +const repository = { + ...createServerRoute({ endpoint: 'endpoint_without_params', handler: async () => { return { noParamsForMe: true, }; }, - }) - .add({ + }), + ...createServerRoute({ endpoint: 'endpoint_with_params', params: t.type({ path: t.type({ @@ -98,8 +91,8 @@ const repository = createServerRouteRepository<{}, {}>() yesParamsForMe: true, }; }, - }) - .add({ + }), + ...createServerRoute({ endpoint: 'endpoint_with_optional_params', params: t.partial({ query: t.partial({ @@ -111,7 +104,8 @@ const repository = createServerRouteRepository<{}, {}>() someParamsForMe: true, }; }, - }); + }), +}; type TestRepository = typeof repository; @@ -146,26 +140,21 @@ const client: TestClient = {} as any; // It should respect any additional create options. // @ts-expect-error Property 'timeout' is missing -client({ - endpoint: 'endpoint_without_params', -}); +client('endpoint_without_params', {}); -client({ - endpoint: 'endpoint_without_params', +client('endpoint_without_params', { timeout: 1, }); // It does not allow params for routes without a params codec -client({ - endpoint: 'endpoint_without_params', +client('endpoint_without_params', { // @ts-expect-error Object literal may only specify known properties, and 'params' does not exist in type params: {}, timeout: 1, }); // It requires params for routes with a params codec -client({ - endpoint: 'endpoint_with_params', +client('endpoint_with_params', { params: { // @ts-expect-error property 'serviceName' is missing in type '{}' path: {}, @@ -174,14 +163,12 @@ client({ }); // Params are optional if the codec has no required keys -client({ - endpoint: 'endpoint_with_optional_params', +client('endpoint_with_optional_params', { timeout: 1, }); // If optional, an error will still occur if the params do not match -client({ - endpoint: 'endpoint_with_optional_params', +client('endpoint_with_optional_params', { timeout: 1, params: { // @ts-expect-error Object literal may only specify known properties, and 'path' does not exist in type @@ -190,8 +177,7 @@ client({ }); // The return type is correctly inferred -client({ - endpoint: 'endpoint_with_params', +client('endpoint_with_params', { params: { path: { serviceName: '', diff --git a/packages/kbn-server-route-repository/src/typings.ts b/packages/kbn-server-route-repository/src/typings.ts index dde957f469901..3a86a1091d1bf 100644 --- a/packages/kbn-server-route-repository/src/typings.ts +++ b/packages/kbn-server-route-repository/src/typings.ts @@ -50,58 +50,10 @@ export type ServerRoute< : {})) => Promise; } & TRouteCreateOptions; -export interface ServerRouteRepository< - TRouteHandlerResources extends ServerRouteHandlerResources = ServerRouteHandlerResources, - TRouteCreateOptions extends ServerRouteCreateOptions = ServerRouteCreateOptions, - TRouteState extends RouteState = RouteState -> { - add< - TEndpoint extends string, - TReturnType, - TRouteParamsRT extends RouteParamsRT | undefined = undefined - >( - route: ServerRoute< - TEndpoint, - TRouteParamsRT, - TRouteHandlerResources, - TReturnType, - TRouteCreateOptions - > - ): ServerRouteRepository< - TRouteHandlerResources, - TRouteCreateOptions, - TRouteState & { - [key in TEndpoint]: ServerRoute< - TEndpoint, - TRouteParamsRT, - TRouteHandlerResources, - TReturnType, - TRouteCreateOptions - >; - } - >; - merge< - TServerRouteRepository extends ServerRouteRepository< - TRouteHandlerResources, - TRouteCreateOptions - > - >( - repository: TServerRouteRepository - ): TServerRouteRepository extends ServerRouteRepository< - TRouteHandlerResources, - TRouteCreateOptions, - infer TRouteStateToMerge - > - ? ServerRouteRepository< - TRouteHandlerResources, - TRouteCreateOptions, - TRouteState & TRouteStateToMerge - > - : never; - getRoutes: () => Array< - ServerRoute - >; -} +export type ServerRouteRepository = Record< + string, + ServerRoute> +>; type ClientRequestParamsOfType = TRouteParamsRT extends t.Mixed @@ -117,72 +69,62 @@ type DecodedRequestParamsOfType = }> : {}; -export type EndpointOf> = - TServerRouteRepository extends ServerRouteRepository - ? keyof TRouteState - : never; +export type EndpointOf = + keyof TServerRouteRepository; export type ReturnOf< - TServerRouteRepository extends ServerRouteRepository, - TEndpoint extends EndpointOf -> = TServerRouteRepository extends ServerRouteRepository - ? TEndpoint extends keyof TRouteState - ? TRouteState[TEndpoint] extends ServerRoute< - any, - any, - any, - infer TReturnType, - ServerRouteCreateOptions - > - ? TReturnType - : never - : never + TServerRouteRepository extends ServerRouteRepository, + TEndpoint extends keyof TServerRouteRepository +> = TServerRouteRepository[TEndpoint] extends ServerRoute< + any, + any, + any, + infer TReturnType, + ServerRouteCreateOptions +> + ? TReturnType : never; export type DecodedRequestParamsOf< - TServerRouteRepository extends ServerRouteRepository, - TEndpoint extends EndpointOf -> = TServerRouteRepository extends ServerRouteRepository - ? TEndpoint extends keyof TRouteState - ? TRouteState[TEndpoint] extends ServerRoute< - any, - infer TRouteParamsRT, - any, - any, - ServerRouteCreateOptions - > - ? TRouteParamsRT extends RouteParamsRT - ? DecodedRequestParamsOfType - : {} - : never - : never + TServerRouteRepository extends ServerRouteRepository, + TEndpoint extends keyof TServerRouteRepository +> = TServerRouteRepository[TEndpoint] extends ServerRoute< + any, + infer TRouteParamsRT, + any, + any, + ServerRouteCreateOptions +> + ? TRouteParamsRT extends RouteParamsRT + ? DecodedRequestParamsOfType + : {} : never; export type ClientRequestParamsOf< - TServerRouteRepository extends ServerRouteRepository, - TEndpoint extends EndpointOf -> = TServerRouteRepository extends ServerRouteRepository - ? TEndpoint extends keyof TRouteState - ? TRouteState[TEndpoint] extends ServerRoute< - any, - infer TRouteParamsRT, - any, - any, - ServerRouteCreateOptions - > - ? TRouteParamsRT extends RouteParamsRT - ? ClientRequestParamsOfType - : {} - : never - : never + TServerRouteRepository extends ServerRouteRepository, + TEndpoint extends keyof TServerRouteRepository +> = TServerRouteRepository[TEndpoint] extends ServerRoute< + any, + infer TRouteParamsRT, + any, + any, + ServerRouteCreateOptions +> + ? TRouteParamsRT extends RouteParamsRT + ? ClientRequestParamsOfType + : {} : never; +type MaybeOptionalArgs> = RequiredKeys extends never + ? [T] | [] + : [T]; + export type RouteRepositoryClient< - TServerRouteRepository extends ServerRouteRepository, + TServerRouteRepository extends ServerRouteRepository, TAdditionalClientOptions extends Record -> = >( - options: { - endpoint: TEndpoint; - } & ClientRequestParamsOf & - TAdditionalClientOptions +> = ( + endpoint: TEndpoint, + ...args: MaybeOptionalArgs< + ClientRequestParamsOf & TAdditionalClientOptions + > ) => Promise>; diff --git a/x-pack/plugins/apm/common/utils/join_by_key/index.ts b/x-pack/plugins/apm/common/utils/join_by_key/index.ts index b6da95039815d..a4d88b2138985 100644 --- a/x-pack/plugins/apm/common/utils/join_by_key/index.ts +++ b/x-pack/plugins/apm/common/utils/join_by_key/index.ts @@ -24,7 +24,7 @@ import { isEqual, pull, merge, castArray } from 'lodash'; ); */ -type JoinedReturnType< +export type JoinedReturnType< T extends Record, U extends UnionToIntersection > = Array< diff --git a/x-pack/plugins/apm/public/components/alerting/error_count_alert_trigger/index.tsx b/x-pack/plugins/apm/public/components/alerting/error_count_alert_trigger/index.tsx index 91e1f552a5a55..e2ea395426fa3 100644 --- a/x-pack/plugins/apm/public/components/alerting/error_count_alert_trigger/index.tsx +++ b/x-pack/plugins/apm/public/components/alerting/error_count_alert_trigger/index.tsx @@ -60,19 +60,20 @@ export function ErrorCountAlertTrigger(props: Props) { windowUnit: params.windowUnit as TimeUnit, }); if (interval && start && end) { - return callApmApi({ - endpoint: - 'GET /internal/apm/alerts/chart_preview/transaction_error_count', - params: { - query: { - environment: params.environment, - serviceName: params.serviceName, - interval, - start, - end, + return callApmApi( + 'GET /internal/apm/alerts/chart_preview/transaction_error_count', + { + params: { + query: { + environment: params.environment, + serviceName: params.serviceName, + interval, + start, + end, + }, }, - }, - }); + } + ); } }, [ diff --git a/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.tsx b/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.tsx index d15f6e6aee8c5..1c45d9f22d7c7 100644 --- a/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.tsx +++ b/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.tsx @@ -98,21 +98,22 @@ export function TransactionDurationAlertTrigger(props: Props) { windowUnit: params.windowUnit as TimeUnit, }); if (interval && start && end) { - return callApmApi({ - endpoint: - 'GET /internal/apm/alerts/chart_preview/transaction_duration', - params: { - query: { - aggregationType: params.aggregationType, - environment: params.environment, - serviceName: params.serviceName, - transactionType: params.transactionType, - interval, - start, - end, + return callApmApi( + 'GET /internal/apm/alerts/chart_preview/transaction_duration', + { + params: { + query: { + aggregationType: params.aggregationType, + environment: params.environment, + serviceName: params.serviceName, + transactionType: params.transactionType, + interval, + start, + end, + }, }, - }, - }); + } + ); } }, [ diff --git a/x-pack/plugins/apm/public/components/alerting/transaction_error_rate_alert_trigger/index.tsx b/x-pack/plugins/apm/public/components/alerting/transaction_error_rate_alert_trigger/index.tsx index 3a91117a82970..ae0a8d3d91968 100644 --- a/x-pack/plugins/apm/public/components/alerting/transaction_error_rate_alert_trigger/index.tsx +++ b/x-pack/plugins/apm/public/components/alerting/transaction_error_rate_alert_trigger/index.tsx @@ -67,20 +67,21 @@ export function TransactionErrorRateAlertTrigger(props: Props) { windowUnit: params.windowUnit as TimeUnit, }); if (interval && start && end) { - return callApmApi({ - endpoint: - 'GET /internal/apm/alerts/chart_preview/transaction_error_rate', - params: { - query: { - environment: params.environment, - serviceName: params.serviceName, - transactionType: params.transactionType, - interval, - start, - end, + return callApmApi( + 'GET /internal/apm/alerts/chart_preview/transaction_error_rate', + { + params: { + query: { + environment: params.environment, + serviceName: params.serviceName, + transactionType: params.transactionType, + interval, + start, + end, + }, }, - }, - }); + } + ); } }, [ diff --git a/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.tsx index 80169ca77f50a..ad998836961a2 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.tsx @@ -75,8 +75,7 @@ async function saveApmIndices({ }: { apmIndices: Record; }) { - await callApmApi({ - endpoint: 'POST /internal/apm/settings/apm-indices/save', + await callApmApi('POST /internal/apm/settings/apm-indices/save', { signal: null, params: { body: apmIndices, @@ -103,9 +102,7 @@ export function ApmIndices() { const { data = INITIAL_STATE, refetch } = useFetcher( (_callApmApi) => { if (canSave) { - return _callApmApi({ - endpoint: `GET /internal/apm/settings/apm-index-settings`, - }); + return _callApmApi(`GET /internal/apm/settings/apm-index-settings`); } }, [canSave] diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/ServicePage/ServicePage.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/ServicePage/ServicePage.tsx index 50f4e34a1c6b4..3c834e6c46efb 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/ServicePage/ServicePage.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/ServicePage/ServicePage.tsx @@ -28,8 +28,7 @@ interface Props { export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { const { data: serviceNamesData, status: serviceNamesStatus } = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: 'GET /api/apm/settings/agent-configuration/services', + return callApmApi('GET /api/apm/settings/agent-configuration/services', { isCachable: true, }); }, @@ -41,12 +40,14 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { const { data: environmentsData, status: environmentsStatus } = useFetcher( (callApmApi) => { if (newConfig.service.name) { - return callApmApi({ - endpoint: 'GET /api/apm/settings/agent-configuration/environments', - params: { - query: { serviceName: omitAllOption(newConfig.service.name) }, - }, - }); + return callApmApi( + 'GET /api/apm/settings/agent-configuration/environments', + { + params: { + query: { serviceName: omitAllOption(newConfig.service.name) }, + }, + } + ); } }, [newConfig.service.name], @@ -63,10 +64,12 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { return; } - const { agentName } = await callApmApi({ - endpoint: 'GET /api/apm/settings/agent-configuration/agent_name', - params: { query: { serviceName } }, - }); + const { agentName } = await callApmApi( + 'GET /api/apm/settings/agent-configuration/agent_name', + { + params: { query: { serviceName } }, + } + ); setNewConfig((prev) => ({ ...prev, agent_name: agentName })); }, diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts index ae15e65e19949..29cca2ae9d615 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts @@ -25,8 +25,7 @@ export async function saveConfig({ toasts: NotificationsStart['toasts']; }) { try { - await callApmApi({ - endpoint: 'PUT /api/apm/settings/agent-configuration', + await callApmApi('PUT /api/apm/settings/agent-configuration', { signal: null, params: { query: { overwrite: isEditMode }, diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx index 66be766437dee..8132d87ab7001 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx @@ -71,8 +71,7 @@ async function deleteConfig( toasts: NotificationsStart['toasts'] ) { try { - await callApmApi({ - endpoint: 'DELETE /api/apm/settings/agent-configuration', + await callApmApi('DELETE /api/apm/settings/agent-configuration', { signal: null, params: { body: { diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/index.tsx index f443e9e016cb8..0abc5fd3ab809 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/index.tsx @@ -30,8 +30,7 @@ export function AgentConfigurations() { data = INITIAL_DATA, status, } = useFetcher( - (callApmApi) => - callApmApi({ endpoint: 'GET /api/apm/settings/agent-configuration' }), + (callApmApi) => callApmApi('GET /api/apm/settings/agent-configuration'), [], { preservePreviousData: false, showToastOnError: false } ); diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_keys/confirm_delete_modal.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_keys/confirm_delete_modal.tsx index 1fb18499641d9..f2821cc4a51f1 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_keys/confirm_delete_modal.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_keys/confirm_delete_modal.tsx @@ -25,8 +25,7 @@ export function ConfirmDeleteModal({ agentKey, onCancel, onConfirm }: Props) { const deleteAgentKey = async () => { try { - await callApmApi({ - endpoint: 'POST /internal/apm/api_key/invalidate', + await callApmApi('POST /internal/apm/api_key/invalidate', { signal: null, params: { body: { id }, diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_keys/create_agent_key.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_keys/create_agent_key.tsx index 01b5bfe907bbc..934899d30029d 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_keys/create_agent_key.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_keys/create_agent_key.tsx @@ -85,8 +85,7 @@ export function CreateAgentKeyFlyout({ onCancel, onSuccess, onError }: Props) { privileges.push(PrivilegeType.AGENT_CONFIG); } - const { agentKey } = await callApmApi({ - endpoint: 'POST /api/apm/agent_keys', + const { agentKey } = await callApmApi('POST /api/apm/agent_keys', { signal: null, params: { body: { diff --git a/x-pack/plugins/apm/public/components/app/Settings/agent_keys/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_keys/index.tsx index 3305f05dd90f9..858fcc07bb6bf 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/agent_keys/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_keys/index.tsx @@ -44,9 +44,7 @@ export function AgentKeys() { status: privilegesStatus, } = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: 'GET /internal/apm/agent_keys/privileges', - }); + return callApmApi('GET /internal/apm/agent_keys/privileges'); }, [], { showToastOnError: false } @@ -59,9 +57,7 @@ export function AgentKeys() { } = useFetcher( (callApmApi) => { if (areApiKeysEnabled && canManage) { - return callApmApi({ - endpoint: 'GET /internal/apm/agent_keys', - }); + return callApmApi('GET /internal/apm/agent_keys'); } }, [areApiKeysEnabled, canManage], diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx index b130c727cfcfe..2ce9cab01e940 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx @@ -49,9 +49,7 @@ export function AddEnvironments({ const { toasts } = notifications; const { data = INITIAL_DATA, status } = useFetcher( (callApmApi) => - callApmApi({ - endpoint: `GET /internal/apm/settings/anomaly-detection/environments`, - }), + callApmApi(`GET /internal/apm/settings/anomaly-detection/environments`), [], { preservePreviousData: false } ); diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/create_jobs.ts b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/create_jobs.ts index 3e3493d60f839..4c94f50b848a0 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/create_jobs.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/create_jobs.ts @@ -27,8 +27,7 @@ export async function createJobs({ toasts: NotificationsStart['toasts']; }) { try { - await callApmApi({ - endpoint: 'POST /internal/apm/settings/anomaly-detection/jobs', + await callApmApi('POST /internal/apm/settings/anomaly-detection/jobs', { signal: null, params: { body: { environments }, diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx index 15b2d393a97a0..8f2c9cb3ac4a4 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx @@ -172,11 +172,12 @@ export function JobsList({ }} onUpgradeClick={() => { if (setupState === AnomalyDetectionSetupState.UpgradeableJobs) { - return callApmApi({ - endpoint: - 'POST /internal/apm/settings/anomaly-detection/update_to_v3', - signal: null, - }).then(() => { + return callApmApi( + 'POST /internal/apm/settings/anomaly-detection/update_to_v3', + { + signal: null, + } + ).then(() => { core.notifications.toasts.addSuccess({ title: i18n.translate( 'xpack.apm.jobsList.updateCompletedToastTitle', diff --git a/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/DeleteButton.tsx b/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/DeleteButton.tsx index 683fcda4d4a77..8a703c275d971 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/DeleteButton.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/DeleteButton.tsx @@ -48,8 +48,7 @@ async function deleteConfig( toasts: NotificationsStart['toasts'] ) { try { - await callApmApi({ - endpoint: 'DELETE /internal/apm/settings/custom_links/{id}', + await callApmApi('DELETE /internal/apm/settings/custom_links/{id}', { signal: null, params: { path: { id: customLinkId }, diff --git a/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/link_preview.tsx b/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/link_preview.tsx index 1767b5e5eb2b9..d421a31c01558 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/link_preview.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/link_preview.tsx @@ -32,11 +32,13 @@ export interface LinkPreviewProps { const fetchTransaction = debounce( async (filters: Filter[], callback: (transaction: Transaction) => void) => { - const transaction = await callApmApi({ - signal: null, - endpoint: 'GET /internal/apm/settings/custom_links/transaction', - params: { query: convertFiltersToQuery(filters) }, - }); + const transaction = await callApmApi( + 'GET /internal/apm/settings/custom_links/transaction', + { + signal: null, + params: { query: convertFiltersToQuery(filters) }, + } + ); callback(transaction); }, 1000 diff --git a/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/saveCustomLink.ts b/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/saveCustomLink.ts index 5d94f03a6b06d..5d97ab4dcfb5a 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/saveCustomLink.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/custom_link/create_edit_custom_link_flyout/saveCustomLink.ts @@ -34,8 +34,7 @@ export async function saveCustomLink({ }; if (id) { - await callApmApi({ - endpoint: 'PUT /internal/apm/settings/custom_links/{id}', + await callApmApi('PUT /internal/apm/settings/custom_links/{id}', { signal: null, params: { path: { id }, @@ -43,8 +42,7 @@ export async function saveCustomLink({ }, }); } else { - await callApmApi({ - endpoint: 'POST /internal/apm/settings/custom_links', + await callApmApi('POST /internal/apm/settings/custom_links', { signal: null, params: { body: customLink, diff --git a/x-pack/plugins/apm/public/components/app/Settings/custom_link/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/custom_link/index.tsx index 190c61b042f83..060a18cbfc797 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/custom_link/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/custom_link/index.tsx @@ -37,9 +37,7 @@ export function CustomLinkOverview() { const { data, status, refetch } = useFetcher( async (callApmApi) => { if (hasValidLicense) { - return callApmApi({ - endpoint: 'GET /internal/apm/settings/custom_links', - }); + return callApmApi('GET /internal/apm/settings/custom_links'); } }, [hasValidLicense] diff --git a/x-pack/plugins/apm/public/components/app/Settings/schema/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/schema/index.tsx index b13046d34be94..bb5608fb7fc71 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/schema/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/schema/index.tsx @@ -46,8 +46,7 @@ export function Schema() { data = {} as FleetMigrationCheckResponse, status, } = useFetcher( - (callApi) => - callApi({ endpoint: 'GET /internal/apm/fleet/migration_check' }), + (callApi) => callApi('GET /internal/apm/fleet/migration_check'), [], { preservePreviousData: false } ); @@ -120,10 +119,12 @@ async function getUnsupportedApmServerConfigs( toasts: NotificationsStart['toasts'] ) { try { - const { unsupported } = await callApmApi({ - endpoint: 'GET /internal/apm/fleet/apm_server_schema/unsupported', - signal: null, - }); + const { unsupported } = await callApmApi( + 'GET /internal/apm/fleet/apm_server_schema/unsupported', + { + signal: null, + } + ); return unsupported; } catch (error) { toasts.addDanger({ @@ -144,10 +145,12 @@ async function createCloudApmPackagePolicy( ) { updateLocalStorage(FETCH_STATUS.LOADING); try { - const { cloudApmPackagePolicy } = await callApmApi({ - endpoint: 'POST /internal/apm/fleet/cloud_apm_package_policy', - signal: null, - }); + const { cloudApmPackagePolicy } = await callApmApi( + 'POST /internal/apm/fleet/cloud_apm_package_policy', + { + signal: null, + } + ); updateLocalStorage(FETCH_STATUS.SUCCESS); return cloudApmPackagePolicy; } catch (error) { diff --git a/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx b/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx index 1da022f3d933d..21d38e3954f27 100644 --- a/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx @@ -28,14 +28,16 @@ export function TraceLink() { const { data = { transaction: null }, status } = useFetcher( (callApmApi) => { if (traceId) { - return callApmApi({ - endpoint: 'GET /internal/apm/traces/{traceId}/root_transaction', - params: { - path: { - traceId, + return callApmApi( + 'GET /internal/apm/traces/{traceId}/root_transaction', + { + params: { + path: { + traceId, + }, }, - }, - }); + } + ); } }, [traceId] diff --git a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_detail_dependencies_table.tsx b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_detail_dependencies_table.tsx index 4e3f7f4bee811..a72c50ec71c94 100644 --- a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_detail_dependencies_table.tsx +++ b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_detail_dependencies_table.tsx @@ -40,8 +40,7 @@ export function BackendDetailDependenciesTable() { return; } - return callApmApi({ - endpoint: 'GET /internal/apm/backends/upstream_services', + return callApmApi('GET /internal/apm/backends/upstream_services', { params: { query: { backendName, diff --git a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_error_rate_chart.tsx b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_error_rate_chart.tsx index 3b19e8b6dd920..caad9467bebeb 100644 --- a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_error_rate_chart.tsx +++ b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_error_rate_chart.tsx @@ -40,8 +40,7 @@ export function BackendFailedTransactionRateChart({ return; } - return callApmApi({ - endpoint: 'GET /internal/apm/backends/charts/error_rate', + return callApmApi('GET /internal/apm/backends/charts/error_rate', { params: { query: { backendName, diff --git a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_latency_chart.tsx b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_latency_chart.tsx index 2e750141257a5..f18183dd6079e 100644 --- a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_latency_chart.tsx +++ b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_latency_chart.tsx @@ -36,8 +36,7 @@ export function BackendLatencyChart({ height }: { height: number }) { return; } - return callApmApi({ - endpoint: 'GET /internal/apm/backends/charts/latency', + return callApmApi('GET /internal/apm/backends/charts/latency', { params: { query: { backendName, diff --git a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_throughput_chart.tsx b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_throughput_chart.tsx index 6f201f468a9e3..2bae8ac54d1b1 100644 --- a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_throughput_chart.tsx +++ b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_throughput_chart.tsx @@ -32,8 +32,7 @@ export function BackendThroughputChart({ height }: { height: number }) { return; } - return callApmApi({ - endpoint: 'GET /internal/apm/backends/charts/throughput', + return callApmApi('GET /internal/apm/backends/charts/throughput', { params: { query: { backendName, diff --git a/x-pack/plugins/apm/public/components/app/backend_inventory/backend_inventory_dependencies_table/index.tsx b/x-pack/plugins/apm/public/components/app/backend_inventory/backend_inventory_dependencies_table/index.tsx index 9782afc8df3e8..71970e00f6d26 100644 --- a/x-pack/plugins/apm/public/components/app/backend_inventory/backend_inventory_dependencies_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/backend_inventory/backend_inventory_dependencies_table/index.tsx @@ -44,8 +44,7 @@ export function BackendInventoryDependenciesTable() { return; } - return callApmApi({ - endpoint: 'GET /internal/apm/backends/top_backends', + return callApmApi('GET /internal/apm/backends/top_backends', { params: { query: { start, end, environment, numBuckets: 20, offset, kuery }, }, diff --git a/x-pack/plugins/apm/public/components/app/correlations/context_popover/top_values.tsx b/x-pack/plugins/apm/public/components/app/correlations/context_popover/top_values.tsx index fbf33899a2de2..72842c9c6dcf6 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/context_popover/top_values.tsx +++ b/x-pack/plugins/apm/public/components/app/correlations/context_popover/top_values.tsx @@ -185,8 +185,7 @@ export function TopValues({ fieldName !== undefined && fieldValue !== undefined ) { - return callApmApi({ - endpoint: 'GET /internal/apm/correlations/field_value_stats', + return callApmApi('GET /internal/apm/correlations/field_value_stats', { params: { query: { ...params, diff --git a/x-pack/plugins/apm/public/components/app/correlations/use_failed_transactions_correlations.ts b/x-pack/plugins/apm/public/components/app/correlations/use_failed_transactions_correlations.ts index 163223e744a22..ad71f56470616 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/use_failed_transactions_correlations.ts +++ b/x-pack/plugins/apm/public/components/app/correlations/use_failed_transactions_correlations.ts @@ -82,8 +82,7 @@ export function useFailedTransactionsCorrelations() { const [overallHistogramResponse, errorHistogramRespone] = await Promise.all([ // Initial call to fetch the overall distribution for the log-log plot. - callApmApi({ - endpoint: 'POST /internal/apm/latency/overall_distribution', + callApmApi('POST /internal/apm/latency/overall_distribution', { signal: abortCtrl.current.signal, params: { body: { @@ -92,8 +91,7 @@ export function useFailedTransactionsCorrelations() { }, }, }), - callApmApi({ - endpoint: 'POST /internal/apm/latency/overall_distribution', + callApmApi('POST /internal/apm/latency/overall_distribution', { signal: abortCtrl.current.signal, params: { body: { @@ -128,13 +126,15 @@ export function useFailedTransactionsCorrelations() { }); setResponse.flush(); - const { fieldCandidates: candidates } = await callApmApi({ - endpoint: 'GET /internal/apm/correlations/field_candidates', - signal: abortCtrl.current.signal, - params: { - query: fetchParams, - }, - }); + const { fieldCandidates: candidates } = await callApmApi( + 'GET /internal/apm/correlations/field_candidates', + { + signal: abortCtrl.current.signal, + params: { + query: fetchParams, + }, + } + ); if (abortCtrl.current.signal.aborted) { return; @@ -156,13 +156,15 @@ export function useFailedTransactionsCorrelations() { const fieldCandidatesChunks = chunk(fieldCandidates, chunkSize); for (const fieldCandidatesChunk of fieldCandidatesChunks) { - const pValues = await callApmApi({ - endpoint: 'POST /internal/apm/correlations/p_values', - signal: abortCtrl.current.signal, - params: { - body: { ...fetchParams, fieldCandidates: fieldCandidatesChunk }, - }, - }); + const pValues = await callApmApi( + 'POST /internal/apm/correlations/p_values', + { + signal: abortCtrl.current.signal, + params: { + body: { ...fetchParams, fieldCandidates: fieldCandidatesChunk }, + }, + } + ); if (pValues.failedTransactionsCorrelations.length > 0) { pValues.failedTransactionsCorrelations.forEach((d) => { @@ -193,16 +195,18 @@ export function useFailedTransactionsCorrelations() { setResponse.flush(); - const { stats } = await callApmApi({ - endpoint: 'POST /internal/apm/correlations/field_stats', - signal: abortCtrl.current.signal, - params: { - body: { - ...fetchParams, - fieldsToSample: [...fieldsToSample], + const { stats } = await callApmApi( + 'POST /internal/apm/correlations/field_stats', + { + signal: abortCtrl.current.signal, + params: { + body: { + ...fetchParams, + fieldsToSample: [...fieldsToSample], + }, }, - }, - }); + } + ); responseUpdate.fieldStats = stats; setResponse({ ...responseUpdate, loaded: LOADED_DONE, isRunning: false }); diff --git a/x-pack/plugins/apm/public/components/app/correlations/use_latency_correlations.ts b/x-pack/plugins/apm/public/components/app/correlations/use_latency_correlations.ts index 358d436f8f0a5..f5958de43e383 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/use_latency_correlations.ts +++ b/x-pack/plugins/apm/public/components/app/correlations/use_latency_correlations.ts @@ -81,16 +81,18 @@ export function useLatencyCorrelations() { }; // Initial call to fetch the overall distribution for the log-log plot. - const { overallHistogram, percentileThresholdValue } = await callApmApi({ - endpoint: 'POST /internal/apm/latency/overall_distribution', - signal: abortCtrl.current.signal, - params: { - body: { - ...fetchParams, - percentileThreshold: DEFAULT_PERCENTILE_THRESHOLD, + const { overallHistogram, percentileThresholdValue } = await callApmApi( + 'POST /internal/apm/latency/overall_distribution', + { + signal: abortCtrl.current.signal, + params: { + body: { + ...fetchParams, + percentileThreshold: DEFAULT_PERCENTILE_THRESHOLD, + }, }, - }, - }); + } + ); responseUpdate.overallHistogram = overallHistogram; responseUpdate.percentileThresholdValue = percentileThresholdValue; @@ -104,13 +106,15 @@ export function useLatencyCorrelations() { }); setResponse.flush(); - const { fieldCandidates } = await callApmApi({ - endpoint: 'GET /internal/apm/correlations/field_candidates', - signal: abortCtrl.current.signal, - params: { - query: fetchParams, - }, - }); + const { fieldCandidates } = await callApmApi( + 'GET /internal/apm/correlations/field_candidates', + { + signal: abortCtrl.current.signal, + params: { + query: fetchParams, + }, + } + ); if (abortCtrl.current.signal.aborted) { return; @@ -128,16 +132,18 @@ export function useLatencyCorrelations() { const fieldCandidateChunks = chunk(fieldCandidates, chunkSize); for (const fieldCandidateChunk of fieldCandidateChunks) { - const fieldValuePairChunkResponse = await callApmApi({ - endpoint: 'POST /internal/apm/correlations/field_value_pairs', - signal: abortCtrl.current.signal, - params: { - body: { - ...fetchParams, - fieldCandidates: fieldCandidateChunk, + const fieldValuePairChunkResponse = await callApmApi( + 'POST /internal/apm/correlations/field_value_pairs', + { + signal: abortCtrl.current.signal, + params: { + body: { + ...fetchParams, + fieldCandidates: fieldCandidateChunk, + }, }, - }, - }); + } + ); if (fieldValuePairChunkResponse.fieldValuePairs.length > 0) { fieldValuePairs.push(...fieldValuePairChunkResponse.fieldValuePairs); @@ -172,13 +178,15 @@ export function useLatencyCorrelations() { ); for (const fieldValuePairChunk of fieldValuePairChunks) { - const significantCorrelations = await callApmApi({ - endpoint: 'POST /internal/apm/correlations/significant_correlations', - signal: abortCtrl.current.signal, - params: { - body: { ...fetchParams, fieldValuePairs: fieldValuePairChunk }, - }, - }); + const significantCorrelations = await callApmApi( + 'POST /internal/apm/correlations/significant_correlations', + { + signal: abortCtrl.current.signal, + params: { + body: { ...fetchParams, fieldValuePairs: fieldValuePairChunk }, + }, + } + ); if (significantCorrelations.latencyCorrelations.length > 0) { significantCorrelations.latencyCorrelations.forEach((d) => { @@ -207,16 +215,18 @@ export function useLatencyCorrelations() { setResponse.flush(); - const { stats } = await callApmApi({ - endpoint: 'POST /internal/apm/correlations/field_stats', - signal: abortCtrl.current.signal, - params: { - body: { - ...fetchParams, - fieldsToSample: [...fieldsToSample], + const { stats } = await callApmApi( + 'POST /internal/apm/correlations/field_stats', + { + signal: abortCtrl.current.signal, + params: { + body: { + ...fetchParams, + fieldsToSample: [...fieldsToSample], + }, }, - }, - }); + } + ); responseUpdate.fieldStats = stats; setResponse({ diff --git a/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx index 0765e0dd01061..57d7cf58a6cab 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx @@ -136,21 +136,23 @@ export function ErrorGroupDetails() { const { data: errorGroupData } = useFetcher( (callApmApi) => { if (start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/errors/{groupId}', - params: { - path: { - serviceName, - groupId, - }, - query: { - environment, - kuery, - start, - end, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/errors/{groupId}', + { + params: { + path: { + serviceName, + groupId, + }, + query: { + environment, + kuery, + start, + end, + }, }, - }, - }); + } + ); } }, [environment, kuery, serviceName, start, end, groupId] diff --git a/x-pack/plugins/apm/public/components/app/error_group_overview/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_overview/index.tsx index c568771be0b72..b904006ceb904 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_overview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_overview/index.tsx @@ -83,24 +83,25 @@ export function ErrorGroupOverview() { sortDirection === 'asc' ? 'asc' : 'desc'; if (start && end && transactionType) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/errors/groups/main_statistics', - params: { - path: { - serviceName, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/errors/groups/main_statistics', + { + params: { + path: { + serviceName, + }, + query: { + environment, + transactionType, + kuery, + start, + end, + sortField, + sortDirection: normalizedSortDirection, + }, }, - query: { - environment, - transactionType, - kuery, - start, - end, - sortField, - sortDirection: normalizedSortDirection, - }, - }, - }).then((response) => { + } + ).then((response) => { return { // Everytime the main statistics is refetched, updates the requestId making the comparison API to be refetched. requestId: uuid(), @@ -134,26 +135,27 @@ export function ErrorGroupOverview() { end && transactionType ) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/errors/groups/detailed_statistics', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, - numBuckets: 20, - transactionType, - groupIds: JSON.stringify( - errorGroupMainStatistics.map(({ groupId }) => groupId).sort() - ), - comparisonStart, - comparisonEnd, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/errors/groups/detailed_statistics', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + numBuckets: 20, + transactionType, + groupIds: JSON.stringify( + errorGroupMainStatistics.map(({ groupId }) => groupId).sort() + ), + comparisonStart, + comparisonEnd, + }, }, - }, - }); + } + ); } }, // only fetches agg results when requestId changes diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/client_metrics/metrics.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/client_metrics/metrics.tsx index 82dac9cc8f016..f8196db691073 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/client_metrics/metrics.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/client_metrics/metrics.tsx @@ -54,8 +54,7 @@ export function Metrics() { const { data, status } = useFetcher( (callApmApi) => { if (uxQuery) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/client-metrics', + return callApmApi('GET /internal/apm/ux/client-metrics', { params: { query: { ...uxQuery, diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/hooks/use_has_rum_data.ts b/x-pack/plugins/apm/public/components/app/rum_dashboard/hooks/use_has_rum_data.ts index 170ecc235aa6c..4d48135e9edb3 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/hooks/use_has_rum_data.ts +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/hooks/use_has_rum_data.ts @@ -9,8 +9,6 @@ import { useFetcher } from '../../../../hooks/use_fetcher'; export function useHasRumData() { return useFetcher((callApmApi) => { - return callApmApi({ - endpoint: 'GET /api/apm/observability_overview/has_rum_data', - }); + return callApmApi('GET /api/apm/observability_overview/has_rum_data'); }, []); } diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/impactful_metrics/js_errors.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/impactful_metrics/js_errors.tsx index 9f7ad5d053fa4..0c6e6846b2feb 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/impactful_metrics/js_errors.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/impactful_metrics/js_errors.tsx @@ -40,8 +40,7 @@ export function JSErrors() { const { data, status } = useFetcher( (callApmApi) => { if (start && end && serviceName) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/js-errors', + return callApmApi('GET /internal/apm/ux/js-errors', { params: { query: { start, diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/page_load_distribution/index.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/page_load_distribution/index.tsx index e8e24c121ea6d..2df4c9de54f52 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/page_load_distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/page_load_distribution/index.tsx @@ -50,8 +50,7 @@ export function PageLoadDistribution() { const { data, status } = useFetcher( (callApmApi) => { if (start && end && serviceName) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/page-load-distribution', + return callApmApi('GET /internal/apm/ux/page-load-distribution', { params: { query: { start, diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/page_load_distribution/use_breakdowns.ts b/x-pack/plugins/apm/public/components/app/rum_dashboard/page_load_distribution/use_breakdowns.ts index ee3acac73211f..244cb6d051251 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/page_load_distribution/use_breakdowns.ts +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/page_load_distribution/use_breakdowns.ts @@ -23,24 +23,26 @@ export const useBreakdowns = ({ percentileRange, field, value }: Props) => { const { data, status } = useFetcher( (callApmApi) => { if (start && end && field && value) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/page-load-distribution/breakdown', - params: { - query: { - start, - end, - breakdown: value, - uiFilters: JSON.stringify(uxUiFilters), - urlQuery: searchTerm, - ...(minP && maxP - ? { - minPercentile: String(minP), - maxPercentile: String(maxP), - } - : {}), + return callApmApi( + 'GET /internal/apm/ux/page-load-distribution/breakdown', + { + params: { + query: { + start, + end, + breakdown: value, + uiFilters: JSON.stringify(uxUiFilters), + urlQuery: searchTerm, + ...(minP && maxP + ? { + minPercentile: String(minP), + maxPercentile: String(maxP), + } + : {}), + }, }, - }, - }); + } + ); } }, [end, start, uxUiFilters, field, value, minP, maxP, searchTerm] diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/page_views_trend/index.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/page_views_trend/index.tsx index 2510420d3eac4..24d5b3a5ab0d6 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/page_views_trend/index.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/page_views_trend/index.tsx @@ -38,8 +38,7 @@ export function PageViewsTrend() { const { data, status } = useFetcher( (callApmApi) => { if (start && end && serviceName) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/page-view-trends', + return callApmApi('GET /internal/apm/ux/page-view-trends', { params: { query: { start, diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/panels/web_application_select.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/panels/web_application_select.tsx index 9c5494c1ea533..64d9c3da7bdd8 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/panels/web_application_select.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/panels/web_application_select.tsx @@ -19,8 +19,7 @@ export function WebApplicationSelect() { const { data, status } = useFetcher( (callApmApi) => { if (start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/services', + return callApmApi('GET /internal/apm/ux/services', { params: { query: { start, diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/url_filter/url_search/use_url_search.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/url_filter/url_search/use_url_search.tsx index e7a025985fca7..53d74ca9f683f 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/url_filter/url_search/use_url_search.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/url_filter/url_search/use_url_search.tsx @@ -37,8 +37,7 @@ export const useUrlSearch = ({ popoverIsOpen, query }: Props) => { return useFetcher( (callApmApi) => { if (uxQuery && popoverIsOpen) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/url-search', + return callApmApi('GET /internal/apm/ux/url-search', { params: { query: { ...uxQuery, diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_metrics/index.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_metrics/index.tsx index cc1223de7b177..9678090928dd6 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_metrics/index.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_metrics/index.tsx @@ -33,8 +33,7 @@ export function UXMetrics() { const { data, status } = useFetcher( (callApmApi) => { if (uxQuery) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/web-core-vitals', + return callApmApi('GET /internal/apm/ux/web-core-vitals', { params: { query: uxQuery, }, diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_metrics/key_ux_metrics.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_metrics/key_ux_metrics.tsx index 3e1c64c484edb..d95d14c74770b 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_metrics/key_ux_metrics.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_metrics/key_ux_metrics.tsx @@ -55,8 +55,7 @@ export function KeyUXMetrics({ data, loading }: Props) { const { data: longTaskData, status } = useFetcher( (callApmApi) => { if (uxQuery) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/long-task-metrics', + return callApmApi('GET /internal/apm/ux/long-task-metrics', { params: { query: { ...uxQuery, diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_overview_fetchers.ts b/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_overview_fetchers.ts index 61310a5c5ad2c..4d1d7d5264f0d 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_overview_fetchers.ts +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/ux_overview_fetchers.ts @@ -20,8 +20,7 @@ export const fetchUxOverviewDate = async ({ relativeTime, serviceName, }: FetchDataParams): Promise => { - const data = await callApmApi({ - endpoint: 'GET /internal/apm/ux/web-core-vitals', + const data = await callApmApi('GET /internal/apm/ux/web-core-vitals', { signal: null, params: { query: { @@ -41,8 +40,7 @@ export const fetchUxOverviewDate = async ({ export async function hasRumData( params: HasDataParams ): Promise { - return await callApmApi({ - endpoint: 'GET /api/apm/observability_overview/has_rum_data', + return await callApmApi('GET /api/apm/observability_overview/has_rum_data', { signal: null, params: { query: params?.absoluteTime diff --git a/x-pack/plugins/apm/public/components/app/rum_dashboard/visitor_breakdown/index.tsx b/x-pack/plugins/apm/public/components/app/rum_dashboard/visitor_breakdown/index.tsx index 822cb0f591bce..ccf6502575991 100644 --- a/x-pack/plugins/apm/public/components/app/rum_dashboard/visitor_breakdown/index.tsx +++ b/x-pack/plugins/apm/public/components/app/rum_dashboard/visitor_breakdown/index.tsx @@ -22,8 +22,7 @@ export function VisitorBreakdown() { const { serviceName } = uxUiFilters; if (start && end && serviceName) { - return callApmApi({ - endpoint: 'GET /internal/apm/ux/visitor-breakdown', + return callApmApi('GET /internal/apm/ux/visitor-breakdown', { params: { query: { start, diff --git a/x-pack/plugins/apm/public/components/app/service_dependencies/service_dependencies_breakdown_chart.tsx b/x-pack/plugins/apm/public/components/app/service_dependencies/service_dependencies_breakdown_chart.tsx index 979a2404dfdf0..85f56a10399b6 100644 --- a/x-pack/plugins/apm/public/components/app/service_dependencies/service_dependencies_breakdown_chart.tsx +++ b/x-pack/plugins/apm/public/components/app/service_dependencies/service_dependencies_breakdown_chart.tsx @@ -28,21 +28,22 @@ export function ServiceDependenciesBreakdownChart({ const { data, status } = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/dependencies/breakdown', - params: { - path: { - serviceName, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/dependencies/breakdown', + { + params: { + path: { + serviceName, + }, + query: { + start, + end, + kuery, + environment, + }, }, - query: { - start, - end, - kuery, - environment, - }, - }, - }); + } + ); }, [serviceName, start, end, kuery, environment] ); diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx index 549ccc8e69259..6a1847196cc63 100644 --- a/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx @@ -63,8 +63,7 @@ function useServicesFetcher() { const { data = initialData, status: mainStatisticsStatus } = useFetcher( (callApmApi) => { if (start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/services', + return callApmApi('GET /internal/apm/services', { params: { query: { environment, @@ -89,8 +88,7 @@ function useServicesFetcher() { const { data: comparisonData } = useFetcher( (callApmApi) => { if (start && end && mainStatisticsData.items.length) { - return callApmApi({ - endpoint: 'GET /internal/apm/services/detailed_statistics', + return callApmApi('GET /internal/apm/services/detailed_statistics', { params: { query: { environment, diff --git a/x-pack/plugins/apm/public/components/app/service_logs/index.tsx b/x-pack/plugins/apm/public/components/app/service_logs/index.tsx index 4f1c517d14b26..441d8ebcb69be 100644 --- a/x-pack/plugins/apm/public/components/app/service_logs/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_logs/index.tsx @@ -35,18 +35,20 @@ export function ServiceLogs() { const { data, status } = useFetcher( (callApmApi) => { if (start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/infrastructure', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/infrastructure', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + }, }, - }, - }); + } + ); } }, [environment, kuery, serviceName, start, end] diff --git a/x-pack/plugins/apm/public/components/app/service_map/Popover/backend_contents.tsx b/x-pack/plugins/apm/public/components/app/service_map/Popover/backend_contents.tsx index a1e4cbe67e65c..ebc948d1f3ef1 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Popover/backend_contents.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Popover/backend_contents.tsx @@ -54,8 +54,7 @@ export function BackendContents({ const { data = INITIAL_STATE, status } = useFetcher( (callApmApi) => { if (backendName) { - return callApmApi({ - endpoint: 'GET /internal/apm/service-map/backend', + return callApmApi('GET /internal/apm/service-map/backend', { params: { query: { backendName, diff --git a/x-pack/plugins/apm/public/components/app/service_map/Popover/service_contents.tsx b/x-pack/plugins/apm/public/components/app/service_map/Popover/service_contents.tsx index b0ca933e64819..113aad554614a 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Popover/service_contents.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Popover/service_contents.tsx @@ -67,13 +67,15 @@ export function ServiceContents({ const { data = INITIAL_STATE, status } = useFetcher( (callApmApi) => { if (serviceName && start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/service-map/service/{serviceName}', - params: { - path: { serviceName }, - query: { environment, start, end, offset }, - }, - }); + return callApmApi( + 'GET /internal/apm/service-map/service/{serviceName}', + { + params: { + path: { serviceName }, + query: { environment, start, end, offset }, + }, + } + ); } }, [environment, serviceName, start, end, offset] diff --git a/x-pack/plugins/apm/public/components/app/service_map/index.tsx b/x-pack/plugins/apm/public/components/app/service_map/index.tsx index ff19029243d07..a1fb69a9fe975 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/index.tsx @@ -122,9 +122,8 @@ export function ServiceMap({ return; } - return callApmApi({ + return callApmApi('GET /internal/apm/service-map', { isCachable: false, - endpoint: 'GET /internal/apm/service-map', params: { query: { start, diff --git a/x-pack/plugins/apm/public/components/app/service_node_metrics/index.tsx b/x-pack/plugins/apm/public/components/app/service_node_metrics/index.tsx index f8041b2e4a8e8..0bf38d9d57e3f 100644 --- a/x-pack/plugins/apm/public/components/app/service_node_metrics/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_node_metrics/index.tsx @@ -83,18 +83,19 @@ export function ServiceNodeMetrics() { const { data: { host, containerId } = INITIAL_DATA, status } = useFetcher( (callApmApi) => { if (start && end) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/node/{serviceNodeName}/metadata', - params: { - path: { serviceName, serviceNodeName }, - query: { - kuery, - start, - end, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/node/{serviceNodeName}/metadata', + { + params: { + path: { serviceName, serviceNodeName }, + query: { + kuery, + start, + end, + }, }, - }, - }); + } + ); } }, [kuery, serviceName, serviceNodeName, start, end] diff --git a/x-pack/plugins/apm/public/components/app/service_node_overview/index.tsx b/x-pack/plugins/apm/public/components/app/service_node_overview/index.tsx index 379632d33a808..9c14c683018e8 100644 --- a/x-pack/plugins/apm/public/components/app/service_node_overview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_node_overview/index.tsx @@ -46,20 +46,22 @@ function ServiceNodeOverview() { if (!start || !end) { return undefined; } - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/serviceNodes', - params: { - path: { - serviceName, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/serviceNodes', + { + params: { + path: { + serviceName, + }, + query: { + kuery, + environment, + start, + end, + }, }, - query: { - kuery, - environment, - start, - end, - }, - }, - }); + } + ); }, [kuery, environment, serviceName, start, end] ); diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx index 255dfbdeb427a..d9c1a0220d151 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx @@ -60,13 +60,15 @@ export function ServiceOverviewDependenciesTable({ return; } - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/dependencies', - params: { - path: { serviceName }, - query: { start, end, environment, numBuckets: 20, offset }, - }, - }); + return callApmApi( + 'GET /internal/apm/services/{serviceName}/dependencies', + { + params: { + path: { serviceName }, + query: { start, end, environment, numBuckets: 20, offset }, + }, + } + ); }, [start, end, serviceName, environment, offset] ); diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx index d9658f9d5e047..2718ae393e535 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx @@ -95,20 +95,21 @@ export function ServiceOverviewErrorsTable({ serviceName }: Props) { if (!start || !end || !transactionType) { return; } - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/errors/groups/main_statistics', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, - transactionType, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/errors/groups/main_statistics', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + transactionType, + }, }, - }, - }).then((response) => { + } + ).then((response) => { const currentPageErrorGroups = orderBy( response.errorGroups, field, @@ -148,26 +149,27 @@ export function ServiceOverviewErrorsTable({ serviceName }: Props) { } = useFetcher( (callApmApi) => { if (requestId && items.length && start && end && transactionType) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/errors/groups/detailed_statistics', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, - numBuckets: 20, - transactionType, - groupIds: JSON.stringify( - items.map(({ groupId: groupId }) => groupId).sort() - ), - comparisonStart, - comparisonEnd, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/errors/groups/detailed_statistics', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + numBuckets: 20, + transactionType, + groupIds: JSON.stringify( + items.map(({ groupId: groupId }) => groupId).sort() + ), + comparisonStart, + comparisonEnd, + }, }, - }, - }); + } + ); } }, // only fetches agg results when requestId changes diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx index 07e4e81e4d216..b8802d946eb7a 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx @@ -98,25 +98,26 @@ export function ServiceOverviewInstancesChartAndTable({ return; } - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/service_overview_instances/main_statistics', - params: { - path: { - serviceName, - }, - query: { - environment, - kuery, - latencyAggregationType, - start, - end, - transactionType, - comparisonStart, - comparisonEnd, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/service_overview_instances/main_statistics', + { + params: { + path: { + serviceName, + }, + query: { + environment, + kuery, + latencyAggregationType, + start, + end, + transactionType, + comparisonStart, + comparisonEnd, + }, }, - }, - }).then((response) => { + } + ).then((response) => { return { // Everytime the main statistics is refetched, updates the requestId making the detailed API to be refetched. requestId: uuid(), @@ -179,29 +180,30 @@ export function ServiceOverviewInstancesChartAndTable({ return; } - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/service_overview_instances/detailed_statistics', - params: { - path: { - serviceName, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/service_overview_instances/detailed_statistics', + { + params: { + path: { + serviceName, + }, + query: { + environment, + kuery, + latencyAggregationType, + start, + end, + numBuckets: 20, + transactionType, + serviceNodeIds: JSON.stringify( + currentPeriodOrderedItems.map((item) => item.serviceNodeName) + ), + comparisonStart, + comparisonEnd, + }, }, - query: { - environment, - kuery, - latencyAggregationType, - start, - end, - numBuckets: 20, - transactionType, - serviceNodeIds: JSON.stringify( - currentPeriodOrderedItems.map((item) => item.serviceNodeName) - ), - comparisonStart, - comparisonEnd, - }, - }, - }); + } + ); }, // only fetches detailed statistics when requestId is invalidated by main statistics api call // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/use_instance_details_fetcher.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/use_instance_details_fetcher.tsx index de833b9b3be11..7bf1eda219a72 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/use_instance_details_fetcher.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/use_instance_details_fetcher.tsx @@ -26,17 +26,18 @@ export function useInstanceDetailsFetcher({ if (!start || !end) { return; } - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/service_overview_instances/details/{serviceNodeName}', - params: { - path: { - serviceName, - serviceNodeName, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/service_overview_instances/details/{serviceNodeName}', + { + params: { + path: { + serviceName, + serviceNodeName, + }, + query: { start, end }, }, - query: { start, end }, - }, - }); + } + ); }, [serviceName, serviceNodeName, start, end] ); diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_throughput_chart.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_throughput_chart.tsx index 81628171f6a11..c3554a68f4f8e 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_throughput_chart.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_throughput_chart.tsx @@ -74,24 +74,26 @@ export function ServiceOverviewThroughputChart({ const { data = INITIAL_STATE, status } = useFetcher( (callApmApi) => { if (serviceName && transactionType && start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/throughput', - params: { - path: { - serviceName, - }, - query: { - environment, - kuery, - start, - end, - transactionType, - comparisonStart, - comparisonEnd, - transactionName, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/throughput', + { + params: { + path: { + serviceName, + }, + query: { + environment, + kuery, + start, + end, + transactionType, + comparisonStart, + comparisonEnd, + transactionName, + }, }, - }, - }); + } + ); } }, [ diff --git a/x-pack/plugins/apm/public/components/app/service_profiling/index.tsx b/x-pack/plugins/apm/public/components/app/service_profiling/index.tsx index 5342ae8e0db28..150daca8520e0 100644 --- a/x-pack/plugins/apm/public/components/app/service_profiling/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_profiling/index.tsx @@ -37,18 +37,20 @@ export function ServiceProfiling() { return; } - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/profiling/timeline', - params: { - path: { serviceName }, - query: { - kuery, - start, - end, - environment, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/profiling/timeline', + { + params: { + path: { serviceName }, + query: { + kuery, + start, + end, + environment, + }, }, - }, - }); + } + ); }, [kuery, start, end, serviceName, environment] ); diff --git a/x-pack/plugins/apm/public/components/app/service_profiling/service_profiling_flamegraph.tsx b/x-pack/plugins/apm/public/components/app/service_profiling/service_profiling_flamegraph.tsx index 8626c4a3b061c..6f8c1d685ba2b 100644 --- a/x-pack/plugins/apm/public/components/app/service_profiling/service_profiling_flamegraph.tsx +++ b/x-pack/plugins/apm/public/components/app/service_profiling/service_profiling_flamegraph.tsx @@ -146,22 +146,23 @@ export function ServiceProfilingFlamegraph({ return undefined; } - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/profiling/statistics', - params: { - path: { - serviceName, - }, - query: { - kuery, - start, - end, - environment, - valueType, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/profiling/statistics', + { + params: { + path: { + serviceName, + }, + query: { + kuery, + start, + end, + environment, + valueType, + }, }, - }, - }); + } + ); }, [kuery, start, end, environment, serviceName, valueType] ); diff --git a/x-pack/plugins/apm/public/components/app/trace_overview/index.tsx b/x-pack/plugins/apm/public/components/app/trace_overview/index.tsx index 9725df9809ea0..6505f08224687 100644 --- a/x-pack/plugins/apm/public/components/app/trace_overview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/trace_overview/index.tsx @@ -34,8 +34,7 @@ export function TraceOverview() { const { status, data = DEFAULT_RESPONSE } = useFetcher( (callApmApi) => { if (start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/traces', + return callApmApi('GET /internal/apm/traces', { params: { query: { environment, diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts index 6d690415d8c6c..ae5763749a272 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts +++ b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts @@ -37,8 +37,7 @@ export const useTransactionDistributionChartData = () => { params.start && params.end ) { - return callApmApi({ - endpoint: 'POST /internal/apm/latency/overall_distribution', + return callApmApi('POST /internal/apm/latency/overall_distribution', { params: { body: { ...params, @@ -84,8 +83,7 @@ export const useTransactionDistributionChartData = () => { params.start && params.end ) { - return callApmApi({ - endpoint: 'POST /internal/apm/latency/overall_distribution', + return callApmApi('POST /internal/apm/latency/overall_distribution', { params: { body: { ...params, diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts b/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts index c35de9d510951..dea15b952a41b 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts +++ b/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts @@ -35,8 +35,7 @@ export function useWaterfallFetcher() { } = useFetcher( (callApmApi) => { if (traceId && start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/traces/{traceId}', + return callApmApi('GET /internal/apm/traces/{traceId}', { params: { path: { traceId }, query: { diff --git a/x-pack/plugins/apm/public/components/app/transaction_link/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_link/index.tsx index 251daf3d0d032..937ab60e6b7cb 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_link/index.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_link/index.tsx @@ -27,8 +27,7 @@ export function TransactionLink() { const { data = { transaction: null }, status } = useFetcher( (callApmApi) => { if (transactionId) { - return callApmApi({ - endpoint: 'GET /internal/apm/transactions/{transactionId}', + return callApmApi('GET /internal/apm/transactions/{transactionId}', { params: { path: { transactionId, diff --git a/x-pack/plugins/apm/public/components/routing/settings/edit_agent_configuration_route_view.tsx b/x-pack/plugins/apm/public/components/routing/settings/edit_agent_configuration_route_view.tsx index 70f1ce4d1d9db..20e0a923a3c6b 100644 --- a/x-pack/plugins/apm/public/components/routing/settings/edit_agent_configuration_route_view.tsx +++ b/x-pack/plugins/apm/public/components/routing/settings/edit_agent_configuration_route_view.tsx @@ -21,8 +21,7 @@ export function EditAgentConfigurationRouteView() { const res = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: 'GET /api/apm/settings/agent-configuration/view', + return callApmApi('GET /api/apm/settings/agent-configuration/view', { params: { query: { name, environment } }, }); }, diff --git a/x-pack/plugins/apm/public/components/routing/templates/apm_main_template.tsx b/x-pack/plugins/apm/public/components/routing/templates/apm_main_template.tsx index fcc69c5055bad..4a5bc86ff4636 100644 --- a/x-pack/plugins/apm/public/components/routing/templates/apm_main_template.tsx +++ b/x-pack/plugins/apm/public/components/routing/templates/apm_main_template.tsx @@ -51,7 +51,7 @@ export function ApmMainTemplate({ const ObservabilityPageTemplate = observability.navigation.PageTemplate; const { data } = useFetcher((callApmApi) => { - return callApmApi({ endpoint: 'GET /internal/apm/has_data' }); + return callApmApi('GET /internal/apm/has_data'); }, []); const noDataConfig = getNoDataConfig({ diff --git a/x-pack/plugins/apm/public/components/routing/templates/backend_detail_template.tsx b/x-pack/plugins/apm/public/components/routing/templates/backend_detail_template.tsx index f87e9a46df584..ac3d576019384 100644 --- a/x-pack/plugins/apm/public/components/routing/templates/backend_detail_template.tsx +++ b/x-pack/plugins/apm/public/components/routing/templates/backend_detail_template.tsx @@ -31,8 +31,7 @@ export function BackendDetailTemplate({ title, children }: Props) { return; } - return callApmApi({ - endpoint: 'GET /internal/apm/backends/metadata', + return callApmApi('GET /internal/apm/backends/metadata', { params: { query: { backendName, diff --git a/x-pack/plugins/apm/public/components/shared/charts/failed_transaction_rate_chart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/failed_transaction_rate_chart/index.tsx index 349a487ff1f19..7e3752565af2f 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/failed_transaction_rate_chart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/failed_transaction_rate_chart/index.tsx @@ -85,25 +85,26 @@ export function FailedTransactionRateChart({ const { data = INITIAL_STATE, status } = useFetcher( (callApmApi) => { if (transactionType && serviceName && start && end) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/transactions/charts/error_rate', - params: { - path: { - serviceName, - }, - query: { - environment, - kuery, - start, - end, - transactionType, - transactionName, - comparisonStart, - comparisonEnd, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/transactions/charts/error_rate', + { + params: { + path: { + serviceName, + }, + query: { + environment, + kuery, + start, + end, + transactionType, + transactionName, + comparisonStart, + comparisonEnd, + }, }, - }, - }); + } + ); } }, [ diff --git a/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts b/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts index a32f7ededea40..bbade4435be64 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts +++ b/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts @@ -37,21 +37,22 @@ export function useTransactionBreakdown({ } = useFetcher( (callApmApi) => { if (serviceName && start && end && transactionType) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/transaction/charts/breakdown', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, - transactionName, - transactionType, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/transaction/charts/breakdown', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + transactionName, + transactionType, + }, }, - }, - }); + } + ); } }, [ diff --git a/x-pack/plugins/apm/public/components/shared/metadata_table/error_metadata/index.tsx b/x-pack/plugins/apm/public/components/shared/metadata_table/error_metadata/index.tsx index a0cf2a1aec485..cfc15905dbe0b 100644 --- a/x-pack/plugins/apm/public/components/shared/metadata_table/error_metadata/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/metadata_table/error_metadata/index.tsx @@ -19,15 +19,17 @@ interface Props { export function ErrorMetadata({ error }: Props) { const { data: errorEvent, status } = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: 'GET /internal/apm/event_metadata/{processorEvent}/{id}', - params: { - path: { - processorEvent: ProcessorEvent.error, - id: error.error.id, + return callApmApi( + 'GET /internal/apm/event_metadata/{processorEvent}/{id}', + { + params: { + path: { + processorEvent: ProcessorEvent.error, + id: error.error.id, + }, }, - }, - }); + } + ); }, [error.error.id] ); diff --git a/x-pack/plugins/apm/public/components/shared/metadata_table/span_metadata/index.tsx b/x-pack/plugins/apm/public/components/shared/metadata_table/span_metadata/index.tsx index 166440d0975b0..922f83586805c 100644 --- a/x-pack/plugins/apm/public/components/shared/metadata_table/span_metadata/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/metadata_table/span_metadata/index.tsx @@ -19,15 +19,17 @@ interface Props { export function SpanMetadata({ span }: Props) { const { data: spanEvent, status } = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: 'GET /internal/apm/event_metadata/{processorEvent}/{id}', - params: { - path: { - processorEvent: ProcessorEvent.span, - id: span.span.id, + return callApmApi( + 'GET /internal/apm/event_metadata/{processorEvent}/{id}', + { + params: { + path: { + processorEvent: ProcessorEvent.span, + id: span.span.id, + }, }, - }, - }); + } + ); }, [span.span.id] ); diff --git a/x-pack/plugins/apm/public/components/shared/metadata_table/transaction_metadata/index.tsx b/x-pack/plugins/apm/public/components/shared/metadata_table/transaction_metadata/index.tsx index b437173c4b632..bc2eb72a4f8ca 100644 --- a/x-pack/plugins/apm/public/components/shared/metadata_table/transaction_metadata/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/metadata_table/transaction_metadata/index.tsx @@ -19,15 +19,17 @@ interface Props { export function TransactionMetadata({ transaction }: Props) { const { data: transactionEvent, status } = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: 'GET /internal/apm/event_metadata/{processorEvent}/{id}', - params: { - path: { - processorEvent: ProcessorEvent.transaction, - id: transaction.transaction.id, + return callApmApi( + 'GET /internal/apm/event_metadata/{processorEvent}/{id}', + { + params: { + path: { + processorEvent: ProcessorEvent.transaction, + id: transaction.transaction.id, + }, }, - }, - }); + } + ); }, [transaction.transaction.id] ); diff --git a/x-pack/plugins/apm/public/components/shared/service_icons/index.test.tsx b/x-pack/plugins/apm/public/components/shared/service_icons/index.test.tsx index b04fe26e1a8bc..891b18168793d 100644 --- a/x-pack/plugins/apm/public/components/shared/service_icons/index.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/service_icons/index.test.tsx @@ -180,8 +180,7 @@ describe('ServiceIcons', () => { describe('details', () => { const callApmApi = - (apisMockData: Record) => - ({ endpoint }: { endpoint: string }) => { + (apisMockData: Record) => (endpoint: string) => { return apisMockData[endpoint]; }; it('Shows loading spinner while fetching data', () => { diff --git a/x-pack/plugins/apm/public/components/shared/service_icons/index.tsx b/x-pack/plugins/apm/public/components/shared/service_icons/index.tsx index b0c6a66d849d8..52c5ca37d818e 100644 --- a/x-pack/plugins/apm/public/components/shared/service_icons/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/service_icons/index.tsx @@ -69,13 +69,15 @@ export function ServiceIcons({ start, end, serviceName }: Props) { const { data: icons, status: iconsFetchStatus } = useFetcher( (callApmApi) => { if (serviceName && start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/metadata/icons', - params: { - path: { serviceName }, - query: { start, end }, - }, - }); + return callApmApi( + 'GET /internal/apm/services/{serviceName}/metadata/icons', + { + params: { + path: { serviceName }, + query: { start, end }, + }, + } + ); } }, [serviceName, start, end] @@ -84,14 +86,16 @@ export function ServiceIcons({ start, end, serviceName }: Props) { const { data: details, status: detailsFetchStatus } = useFetcher( (callApmApi) => { if (selectedIconPopover && serviceName && start && end) { - return callApmApi({ - isCachable: true, - endpoint: 'GET /internal/apm/services/{serviceName}/metadata/details', - params: { - path: { serviceName }, - query: { start, end }, - }, - }); + return callApmApi( + 'GET /internal/apm/services/{serviceName}/metadata/details', + { + isCachable: true, + params: { + path: { serviceName }, + query: { start, end }, + }, + } + ); } }, [selectedIconPopover, serviceName, start, end] diff --git a/x-pack/plugins/apm/public/components/shared/suggestions_select/index.tsx b/x-pack/plugins/apm/public/components/shared/suggestions_select/index.tsx index e5ad6e2ad6438..2d735ec4ea708 100644 --- a/x-pack/plugins/apm/public/components/shared/suggestions_select/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/suggestions_select/index.tsx @@ -44,8 +44,7 @@ export function SuggestionsSelect({ const { data, status } = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: 'GET /internal/apm/suggestions', + return callApmApi('GET /internal/apm/suggestions', { params: { query: { field, string: searchValue }, }, diff --git a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.tsx index 7e377f2a756ee..31c8146c953c9 100644 --- a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.tsx @@ -59,9 +59,8 @@ export function CustomLinkMenuSection({ const { data, status, refetch } = useFetcher( (callApmApi) => - callApmApi({ + callApmApi('GET /internal/apm/settings/custom_links', { isCachable: false, - endpoint: 'GET /internal/apm/settings/custom_links', params: { query: convertFiltersToQuery(filters) }, }), [filters] diff --git a/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx b/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx index a98eda2d3b961..d2b1c925e7180 100644 --- a/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx @@ -112,21 +112,22 @@ export function TransactionsTable({ if (!start || !end || !latencyAggregationType || !transactionType) { return; } - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/transactions/groups/main_statistics', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, - transactionType, - latencyAggregationType, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/transactions/groups/main_statistics', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + transactionType, + latencyAggregationType, + }, }, - }, - }).then((response) => { + } + ).then((response) => { const currentPageTransactionGroups = orderBy( response.transactionGroups, field, @@ -185,27 +186,28 @@ export function TransactionsTable({ transactionType && latencyAggregationType ) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/transactions/groups/detailed_statistics', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, - numBuckets: 20, - transactionType, - latencyAggregationType, - transactionNames: JSON.stringify( - transactionGroups.map(({ name }) => name).sort() - ), - comparisonStart, - comparisonEnd, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/transactions/groups/detailed_statistics', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + numBuckets: 20, + transactionType, + latencyAggregationType, + transactionNames: JSON.stringify( + transactionGroups.map(({ name }) => name).sort() + ), + comparisonStart, + comparisonEnd, + }, }, - }, - }); + } + ); } }, // only fetches detailed statistics when requestId is invalidated by main statistics api call diff --git a/x-pack/plugins/apm/public/context/annotations/annotations_context.tsx b/x-pack/plugins/apm/public/context/annotations/annotations_context.tsx index 7cf43c1024fc1..0bd2bc189bd38 100644 --- a/x-pack/plugins/apm/public/context/annotations/annotations_context.tsx +++ b/x-pack/plugins/apm/public/context/annotations/annotations_context.tsx @@ -31,19 +31,21 @@ export function AnnotationsContextProvider({ const { data = INITIAL_STATE } = useFetcher( (callApmApi) => { if (start && end && serviceName) { - return callApmApi({ - endpoint: 'GET /api/apm/services/{serviceName}/annotation/search', - params: { - path: { - serviceName, + return callApmApi( + 'GET /api/apm/services/{serviceName}/annotation/search', + { + params: { + path: { + serviceName, + }, + query: { + environment, + start, + end, + }, }, - query: { - environment, - start, - end, - }, - }, - }); + } + ); } }, [environment, start, end, serviceName] diff --git a/x-pack/plugins/apm/public/context/anomaly_detection_jobs/anomaly_detection_jobs_context.tsx b/x-pack/plugins/apm/public/context/anomaly_detection_jobs/anomaly_detection_jobs_context.tsx index 3b9cea7b88998..cb67d57668160 100644 --- a/x-pack/plugins/apm/public/context/anomaly_detection_jobs/anomaly_detection_jobs_context.tsx +++ b/x-pack/plugins/apm/public/context/anomaly_detection_jobs/anomaly_detection_jobs_context.tsx @@ -45,9 +45,7 @@ export function AnomalyDetectionJobsContextProvider({ if (!isAuthorized) { return; } - return callApmApi({ - endpoint: `GET /internal/apm/settings/anomaly-detection/jobs`, - }); + return callApmApi(`GET /internal/apm/settings/anomaly-detection/jobs`); }, [isAuthorized], { showToastOnError: false } diff --git a/x-pack/plugins/apm/public/context/apm_service/use_service_agent_fetcher.ts b/x-pack/plugins/apm/public/context/apm_service/use_service_agent_fetcher.ts index 0202ff3a10123..3eb6b0e1f9856 100644 --- a/x-pack/plugins/apm/public/context/apm_service/use_service_agent_fetcher.ts +++ b/x-pack/plugins/apm/public/context/apm_service/use_service_agent_fetcher.ts @@ -28,8 +28,7 @@ export function useServiceAgentFetcher({ } = useFetcher( (callApmApi) => { if (serviceName) { - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/agent', + return callApmApi('GET /internal/apm/services/{serviceName}/agent', { params: { path: { serviceName }, query: { start, end }, diff --git a/x-pack/plugins/apm/public/context/apm_service/use_service_alerts_fetcher.tsx b/x-pack/plugins/apm/public/context/apm_service/use_service_alerts_fetcher.tsx index d0e1edc775a81..c39bed3bac6cb 100644 --- a/x-pack/plugins/apm/public/context/apm_service/use_service_alerts_fetcher.tsx +++ b/x-pack/plugins/apm/public/context/apm_service/use_service_alerts_fetcher.tsx @@ -40,8 +40,7 @@ export function useServiceAlertsFetcher({ return; } - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/alerts', + return callApmApi('GET /internal/apm/services/{serviceName}/alerts', { params: { path: { serviceName, diff --git a/x-pack/plugins/apm/public/context/apm_service/use_service_transaction_types_fetcher.tsx b/x-pack/plugins/apm/public/context/apm_service/use_service_transaction_types_fetcher.tsx index e81a2d956bf3c..96a4141e824cc 100644 --- a/x-pack/plugins/apm/public/context/apm_service/use_service_transaction_types_fetcher.tsx +++ b/x-pack/plugins/apm/public/context/apm_service/use_service_transaction_types_fetcher.tsx @@ -21,14 +21,15 @@ export function useServiceTransactionTypesFetcher({ const { data = INITIAL_DATA } = useFetcher( (callApmApi) => { if (serviceName && start && end) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/transaction_types', - params: { - path: { serviceName }, - query: { start, end }, - }, - }); + return callApmApi( + 'GET /internal/apm/services/{serviceName}/transaction_types', + { + params: { + path: { serviceName }, + query: { start, end }, + }, + } + ); } }, [serviceName, start, end] diff --git a/x-pack/plugins/apm/public/context/service_anomaly_timeseries/service_anomaly_timeseries_context.tsx b/x-pack/plugins/apm/public/context/service_anomaly_timeseries/service_anomaly_timeseries_context.tsx index 77095d847e3c5..62bd2ea583592 100644 --- a/x-pack/plugins/apm/public/context/service_anomaly_timeseries/service_anomaly_timeseries_context.tsx +++ b/x-pack/plugins/apm/public/context/service_anomaly_timeseries/service_anomaly_timeseries_context.tsx @@ -53,19 +53,21 @@ export function ServiceAnomalyTimeseriesContextProvider({ return; } - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/anomaly_charts', - params: { - path: { - serviceName, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/anomaly_charts', + { + params: { + path: { + serviceName, + }, + query: { + start, + end, + transactionType, + }, }, - query: { - start, - end, - transactionType, - }, - }, - }); + } + ); }, [serviceName, canGetAnomalies, transactionType, start, end] ); diff --git a/x-pack/plugins/apm/public/hooks/use_dynamic_data_view.ts b/x-pack/plugins/apm/public/hooks/use_dynamic_data_view.ts index dfd1fa927b00e..04d289d9e49a2 100644 --- a/x-pack/plugins/apm/public/hooks/use_dynamic_data_view.ts +++ b/x-pack/plugins/apm/public/hooks/use_dynamic_data_view.ts @@ -9,8 +9,7 @@ import { useFetcher } from './use_fetcher'; export function useDynamicDataViewFetcher() { const { data, status } = useFetcher((callApmApi) => { - return callApmApi({ - endpoint: 'GET /internal/apm/data_view/dynamic', + return callApmApi('GET /internal/apm/data_view/dynamic', { isCachable: true, }); }, []); diff --git a/x-pack/plugins/apm/public/hooks/use_environments_fetcher.tsx b/x-pack/plugins/apm/public/hooks/use_environments_fetcher.tsx index caec2c3d3556f..edd1b59be144e 100644 --- a/x-pack/plugins/apm/public/hooks/use_environments_fetcher.tsx +++ b/x-pack/plugins/apm/public/hooks/use_environments_fetcher.tsx @@ -37,8 +37,7 @@ export function useEnvironmentsFetcher({ const { data = INITIAL_DATA, status } = useFetcher( (callApmApi) => { if (start && end) { - return callApmApi({ - endpoint: 'GET /internal/apm/environments', + return callApmApi('GET /internal/apm/environments', { params: { query: { start, diff --git a/x-pack/plugins/apm/public/hooks/use_error_group_distribution_fetcher.tsx b/x-pack/plugins/apm/public/hooks/use_error_group_distribution_fetcher.tsx index 2878353da8eb7..d843067b48e91 100644 --- a/x-pack/plugins/apm/public/hooks/use_error_group_distribution_fetcher.tsx +++ b/x-pack/plugins/apm/public/hooks/use_error_group_distribution_fetcher.tsx @@ -35,22 +35,23 @@ export function useErrorGroupDistributionFetcher({ const { data, status } = useFetcher( (callApmApi) => { if (start && end) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/errors/distribution', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, - comparisonStart, - comparisonEnd, - groupId, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/errors/distribution', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + comparisonStart, + comparisonEnd, + groupId, + }, }, - }, - }); + } + ); } }, [ diff --git a/x-pack/plugins/apm/public/hooks/use_fallback_to_transactions_fetcher.tsx b/x-pack/plugins/apm/public/hooks/use_fallback_to_transactions_fetcher.tsx index 3dfb02cec5fbc..477a8632c9a2f 100644 --- a/x-pack/plugins/apm/public/hooks/use_fallback_to_transactions_fetcher.tsx +++ b/x-pack/plugins/apm/public/hooks/use_fallback_to_transactions_fetcher.tsx @@ -18,8 +18,7 @@ export function useFallbackToTransactionsFetcher({ kuery }: { kuery: string }) { const { data = { fallbackToTransactions: false } } = useFetcher( (callApmApi) => { - return callApmApi({ - endpoint: 'GET /internal/apm/fallback_to_transactions', + return callApmApi('GET /internal/apm/fallback_to_transactions', { params: { query: { kuery, start, end }, }, diff --git a/x-pack/plugins/apm/public/hooks/use_fetcher.tsx b/x-pack/plugins/apm/public/hooks/use_fetcher.tsx index b77f6f9cf0fbb..15e729b7c6276 100644 --- a/x-pack/plugins/apm/public/hooks/use_fetcher.tsx +++ b/x-pack/plugins/apm/public/hooks/use_fetcher.tsx @@ -49,8 +49,11 @@ function getDetailsFromErrorResponse( const createAutoAbortedAPMClient = ( signal: AbortSignal ): AutoAbortedAPMClient => { - return ((options: Parameters[0]) => { - return callApmApi({ ...options, signal }); + return ((endpoint, options) => { + return callApmApi(endpoint, { + ...options, + signal, + } as any); }) as AutoAbortedAPMClient; }; diff --git a/x-pack/plugins/apm/public/hooks/use_service_metric_charts_fetcher.ts b/x-pack/plugins/apm/public/hooks/use_service_metric_charts_fetcher.ts index 15037ecf6adb8..ec75a38e39b90 100644 --- a/x-pack/plugins/apm/public/hooks/use_service_metric_charts_fetcher.ts +++ b/x-pack/plugins/apm/public/hooks/use_service_metric_charts_fetcher.ts @@ -41,20 +41,22 @@ export function useServiceMetricChartsFetcher({ } = useFetcher( (callApmApi) => { if (serviceName && start && end && agentName) { - return callApmApi({ - endpoint: 'GET /internal/apm/services/{serviceName}/metrics/charts', - params: { - path: { serviceName }, - query: { - environment, - kuery, - serviceNodeName, - start, - end, - agentName, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/metrics/charts', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + serviceNodeName, + start, + end, + agentName, + }, }, - }, - }); + } + ); } }, [environment, kuery, serviceName, start, end, agentName, serviceNodeName] diff --git a/x-pack/plugins/apm/public/hooks/use_transaction_latency_chart_fetcher.ts b/x-pack/plugins/apm/public/hooks/use_transaction_latency_chart_fetcher.ts index 0ed3de14c129f..1ce5f0a4fa4e3 100644 --- a/x-pack/plugins/apm/public/hooks/use_transaction_latency_chart_fetcher.ts +++ b/x-pack/plugins/apm/public/hooks/use_transaction_latency_chart_fetcher.ts @@ -55,24 +55,25 @@ export function useTransactionLatencyChartsFetcher({ transactionType && latencyAggregationType ) { - return callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/transactions/charts/latency', - params: { - path: { serviceName }, - query: { - environment, - kuery, - start, - end, - transactionType, - transactionName, - latencyAggregationType, - comparisonStart, - comparisonEnd, + return callApmApi( + 'GET /internal/apm/services/{serviceName}/transactions/charts/latency', + { + params: { + path: { serviceName }, + query: { + environment, + kuery, + start, + end, + transactionType, + transactionName, + latencyAggregationType, + comparisonStart, + comparisonEnd, + }, }, - }, - }); + } + ); } }, [ diff --git a/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts b/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts index 93349d3f955b8..e04735821aaec 100644 --- a/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts +++ b/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts @@ -48,27 +48,28 @@ export function useTransactionTraceSamplesFetcher({ } = useFetcher( async (callApmApi) => { if (serviceName && start && end && transactionType && transactionName) { - const response = await callApmApi({ - endpoint: - 'GET /internal/apm/services/{serviceName}/transactions/traces/samples', - params: { - path: { - serviceName, + const response = await callApmApi( + 'GET /internal/apm/services/{serviceName}/transactions/traces/samples', + { + params: { + path: { + serviceName, + }, + query: { + environment, + kuery, + start, + end, + transactionType, + transactionName, + transactionId, + traceId, + sampleRangeFrom, + sampleRangeTo, + }, }, - query: { - environment, - kuery, - start, - end, - transactionType, - transactionName, - transactionId, - traceId, - sampleRangeFrom, - sampleRangeTo, - }, - }, - }); + } + ); return response; } diff --git a/x-pack/plugins/apm/public/services/callApmApi.test.ts b/x-pack/plugins/apm/public/services/callApmApi.test.ts index b1d31586c2cee..f10f6a82610ab 100644 --- a/x-pack/plugins/apm/public/services/callApmApi.test.ts +++ b/x-pack/plugins/apm/public/services/callApmApi.test.ts @@ -23,8 +23,8 @@ describe('callApmApi', () => { }); it('should format the pathname with the given path params', async () => { - await callApmApi({ - endpoint: 'GET /internal/apm/{param1}/to/{param2}', + // @ts-expect-error + await callApmApi('GET /internal/apm/{param1}/to/{param2}', { params: { path: { param1: 'foo', @@ -42,8 +42,8 @@ describe('callApmApi', () => { }); it('should add the query parameters to the options object', async () => { - await callApmApi({ - endpoint: 'GET /internal/apm', + // @ts-expect-error + await callApmApi('GET /internal/apm', { params: { query: { foo: 'bar', @@ -65,8 +65,8 @@ describe('callApmApi', () => { }); it('should stringify the body and add it to the options object', async () => { - await callApmApi({ - endpoint: 'POST /internal/apm', + // @ts-expect-error + await callApmApi('POST /internal/apm', { params: { body: { foo: 'bar', diff --git a/x-pack/plugins/apm/public/services/rest/apm_observability_overview_fetchers.ts b/x-pack/plugins/apm/public/services/rest/apm_observability_overview_fetchers.ts index 4e7114ebb9e35..a8aac24c08516 100644 --- a/x-pack/plugins/apm/public/services/rest/apm_observability_overview_fetchers.ts +++ b/x-pack/plugins/apm/public/services/rest/apm_observability_overview_fetchers.ts @@ -17,8 +17,7 @@ export const fetchObservabilityOverviewPageData = async ({ bucketSize, intervalString, }: FetchDataParams): Promise => { - const data = await callApmApi({ - endpoint: 'GET /internal/apm/observability_overview', + const data = await callApmApi('GET /internal/apm/observability_overview', { signal: null, params: { query: { @@ -53,8 +52,7 @@ export const fetchObservabilityOverviewPageData = async ({ }; export async function getHasData() { - return await callApmApi({ - endpoint: 'GET /internal/apm/observability_overview/has_data', + return await callApmApi('GET /internal/apm/observability_overview/has_data', { signal: null, }); } diff --git a/x-pack/plugins/apm/public/services/rest/createCallApmApi.ts b/x-pack/plugins/apm/public/services/rest/createCallApmApi.ts index 388d88bbc2a92..a8a1cff853432 100644 --- a/x-pack/plugins/apm/public/services/rest/createCallApmApi.ts +++ b/x-pack/plugins/apm/public/services/rest/createCallApmApi.ts @@ -6,14 +6,12 @@ */ import { CoreSetup, CoreStart } from 'kibana/public'; -import * as t from 'io-ts'; import type { ClientRequestParamsOf, formatRequest as formatRequestType, ReturnOf, RouteRepositoryClient, ServerRouteRepository, - ServerRoute, } from '@kbn/server-route-repository'; // @ts-expect-error cannot find module or correspondent type declarations // The code and types are at separated folders on @kbn/server-route-repository @@ -21,10 +19,9 @@ import type { // an error is expected here import { formatRequest } from '@kbn/server-route-repository/target_node/format_request'; import { FetchOptions } from '../../../common/fetch_options'; -import { callApi } from './callApi'; +import { CallApi, callApi } from './callApi'; import type { APMServerRouteRepository, - APMRouteHandlerResources, APIEndpoint, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../../server'; @@ -57,14 +54,7 @@ export type APIReturnType = ReturnOf< export type APIClientRequestParamsOf = ClientRequestParamsOf; -export type AbstractAPMRepository = ServerRouteRepository< - APMRouteHandlerResources, - {}, - Record< - string, - ServerRoute - > ->; +export type AbstractAPMRepository = ServerRouteRepository; export type AbstractAPMClient = RouteRepositoryClient< AbstractAPMRepository, @@ -78,8 +68,7 @@ export let callApmApi: APMClient = () => { }; export function createCallApmApi(core: CoreStart | CoreSetup) { - callApmApi = ((options) => { - const { endpoint, ...opts } = options; + callApmApi = ((endpoint, options) => { const { params } = options as unknown as { params?: Partial>; }; @@ -90,11 +79,11 @@ export function createCallApmApi(core: CoreStart | CoreSetup) { ) as ReturnType; return callApi(core, { - ...opts, + ...options, method, pathname, body: params?.body, query: params?.query, - }); + } as unknown as Parameters[1]); }) as APMClient; } diff --git a/x-pack/plugins/apm/public/services/rest/data_view.ts b/x-pack/plugins/apm/public/services/rest/data_view.ts index 322c122e1969c..00a4664ab8351 100644 --- a/x-pack/plugins/apm/public/services/rest/data_view.ts +++ b/x-pack/plugins/apm/public/services/rest/data_view.ts @@ -8,8 +8,7 @@ import { callApmApi } from './createCallApmApi'; export const createStaticDataView = async () => { - return await callApmApi({ - endpoint: 'POST /internal/apm/data_view/static', + return await callApmApi('POST /internal/apm/data_view/static', { signal: null, }); }; diff --git a/x-pack/plugins/apm/public/tutorial/tutorial_apm_fleet_check.ts b/x-pack/plugins/apm/public/tutorial/tutorial_apm_fleet_check.ts index 8502689724d04..45ece40a59cea 100644 --- a/x-pack/plugins/apm/public/tutorial/tutorial_apm_fleet_check.ts +++ b/x-pack/plugins/apm/public/tutorial/tutorial_apm_fleet_check.ts @@ -8,10 +8,12 @@ import { callApmApi } from '../services/rest/createCallApmApi'; export async function hasFleetApmIntegrations() { try { - const { hasData = false } = await callApmApi({ - endpoint: 'GET /internal/apm/fleet/has_data', - signal: null, - }); + const { hasData = false } = await callApmApi( + 'GET /internal/apm/fleet/has_data', + { + signal: null, + } + ); return hasData; } catch (e) { console.error('Something went wrong while fetching apm fleet data', e); diff --git a/x-pack/plugins/apm/scripts/infer_route_return_types.js b/x-pack/plugins/apm/scripts/infer_route_return_types.js new file mode 100644 index 0000000000000..cd973ff36d3ab --- /dev/null +++ b/x-pack/plugins/apm/scripts/infer_route_return_types.js @@ -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. + */ + +// compile typescript on the fly +// eslint-disable-next-line import/no-extraneous-dependencies +require('@kbn/optimizer').registerNodeAutoTranspilation(); + +require('./infer_route_return_types/index.ts'); diff --git a/x-pack/plugins/apm/scripts/infer_route_return_types/index.ts b/x-pack/plugins/apm/scripts/infer_route_return_types/index.ts new file mode 100644 index 0000000000000..081d7cacef801 --- /dev/null +++ b/x-pack/plugins/apm/scripts/infer_route_return_types/index.ts @@ -0,0 +1,143 @@ +/* + * 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 { + Project, + Node, + FunctionDeclaration, + FunctionExpression, + ArrowFunction, + MethodDeclaration, + SourceFile, + SyntaxKind, + PropertyAssignment, + ts, + TypeFormatFlags, +} from 'ts-morph'; +import Path from 'path'; +import { execSync } from 'child_process'; +import { argv } from 'yargs'; +// @ts-expect-error +import { optimizeTsConfig } from '../optimize_tsconfig/optimize'; + +// This script adds explicit return types to route handlers, +// for performance reasons. See https://github.com/elastic/kibana/pull/123266 +// for more background. + +type ConvertibleDeclaration = + | FunctionDeclaration + | FunctionExpression + | ArrowFunction + | MethodDeclaration; + +optimizeTsConfig().then(() => { + const project = new Project({ + tsConfigFilePath: Path.resolve(__dirname, '../../../../../tsconfig.json'), + }); + + const glob = + (argv.glob as string | undefined) || + 'x-pack/plugins/apm/server/**/route.ts'; + + const files = project.getSourceFiles(glob); + + const changedFiles: SourceFile[] = []; + + files.forEach((file) => { + file.getVariableDeclarations().forEach((declaration) => { + const initializer = declaration.getInitializerIfKind( + SyntaxKind.CallExpression + ); + + const argument = initializer?.getArguments()[0]; + + if (Node.isObjectLiteralExpression(argument)) { + // this gets the `handler` function + const handler = argument.getProperty('handler') as + | PropertyAssignment + | MethodDeclaration + | undefined; + + if (!handler) { + return; + } + + let fnDeclaration = ( + Node.isPropertyAssignment(handler) + ? (handler.getInitializer() as ConvertibleDeclaration) + : handler + ) + // remove any explicit return type + .removeReturnType(); + + const signature = fnDeclaration.getSignature(); + + if (!signature) { + return; + } + + const returnType = signature.getReturnType(); + + const txt = returnType.getText( + fnDeclaration, + TypeFormatFlags.NoTruncation + ); + + fnDeclaration = fnDeclaration.setReturnType(txt); + + let hasAny: boolean = false; + + fnDeclaration.transform((traversal) => { + const node = traversal.visitChildren(); + + if (node.kind === SyntaxKind.AnyKeyword) { + hasAny = true; + } + + if (ts.isImportTypeNode(node)) { + const literal = (node.argument as ts.LiteralTypeNode) + .literal as ts.StringLiteral; + + // replace absolute paths with relative paths + return ts.updateImportTypeNode( + node, + ts.createLiteralTypeNode( + ts.createStringLiteral( + `./${Path.relative( + Path.dirname(file.getFilePath()), + literal.text + )}` + ) + ), + node.qualifier!, + node.typeArguments + ); + } + + return node; + }); + + if (hasAny) { + // eslint-disable-next-line no-console + console.warn(`Any type detected in ${file.getFilePath()}: ${txt}`); + } + + changedFiles.push(file); + } + }); + }); + + changedFiles.forEach((file) => file.saveSync()); + + const root = Path.join(__dirname, '../../../../..'); + + // run ESLint on the changed files + execSync(`node scripts/eslint ${glob} --fix`, { + cwd: root, + stdio: 'inherit', + }); +}); diff --git a/x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json b/x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json index 2ece69d491fca..25f44f14dc080 100644 --- a/x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json +++ b/x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json @@ -2,7 +2,6 @@ "include": [ "./x-pack/plugins/apm/**/*", "./x-pack/plugins/observability/**/*", - "./x-pack/plugins/rule_registry/**/*", "./typings/**/*" ], "exclude": [ diff --git a/x-pack/plugins/apm/server/routes/agent_keys/route.ts b/x-pack/plugins/apm/server/routes/agent_keys/route.ts index 5878ce75680ac..90ffbbf8a656e 100644 --- a/x-pack/plugins/apm/server/routes/agent_keys/route.ts +++ b/x-pack/plugins/apm/server/routes/agent_keys/route.ts @@ -9,7 +9,6 @@ import Boom from '@hapi/boom'; import { i18n } from '@kbn/i18n'; import * as t from 'io-ts'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { getAgentKeys } from './get_agent_keys'; import { getAgentKeysPrivileges } from './get_agent_keys_privileges'; import { invalidateAgentKey } from './invalidate_agent_key'; @@ -20,7 +19,11 @@ const agentKeysRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/agent_keys', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + agentKeys: Array; + }> => { const { context } = resources; const agentKeys = await getAgentKeys({ context, @@ -34,7 +37,13 @@ const agentKeysPrivilegesRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/agent_keys/privileges', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + areApiKeysEnabled: boolean; + isAdmin: boolean; + canManage: boolean; + }> => { const { plugins: { security }, context, @@ -60,7 +69,7 @@ const invalidateAgentKeyRoute = createApmServerRoute({ params: t.type({ body: t.type({ id: t.string }), }), - handler: async (resources) => { + handler: async (resources): Promise<{ invalidatedAgentKeys: string[] }> => { const { context, params } = resources; const { @@ -85,7 +94,11 @@ const createAgentKeyRoute = createApmServerRoute({ privileges: privilegesTypeRt, }), }), - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + agentKey: import('./../../../../../../node_modules/@elastic/elasticsearch/lib/api/types').SecurityCreateApiKeyResponse; + }> => { const { context, params } = resources; const { body: requestBody } = params; @@ -99,11 +112,12 @@ const createAgentKeyRoute = createApmServerRoute({ }, }); -export const agentKeysRouteRepository = createApmServerRouteRepository() - .add(agentKeysRoute) - .add(agentKeysPrivilegesRoute) - .add(invalidateAgentKeyRoute) - .add(createAgentKeyRoute); +export const agentKeysRouteRepository = { + ...agentKeysRoute, + ...agentKeysPrivilegesRoute, + ...invalidateAgentKeyRoute, + ...createAgentKeyRoute, +}; const SECURITY_REQUIRED_MESSAGE = i18n.translate( 'xpack.apm.api.apiKeys.securityRequired', diff --git a/x-pack/plugins/apm/server/routes/alerts/route.ts b/x-pack/plugins/apm/server/routes/alerts/route.ts index 49baeda8d3a47..cac1aea70698e 100644 --- a/x-pack/plugins/apm/server/routes/alerts/route.ts +++ b/x-pack/plugins/apm/server/routes/alerts/route.ts @@ -11,7 +11,6 @@ import { getTransactionErrorCountChartPreview } from './chart_preview/get_transa import { getTransactionErrorRateChartPreview } from './chart_preview/get_transaction_error_rate'; import { setupRequest } from '../../lib/helpers/setup_request'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { environmentRt, rangeRt } from '../default_api_types'; const alertParamsRt = t.intersection([ @@ -37,7 +36,9 @@ const transactionErrorRateChartPreview = createApmServerRoute({ endpoint: 'GET /internal/apm/alerts/chart_preview/transaction_error_rate', params: t.type({ query: alertParamsRt }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ errorRateChartPreview: Array<{ x: number; y: number }> }> => { const setup = await setupRequest(resources); const { params } = resources; const { _inspect, ...alertParams } = params.query; @@ -55,7 +56,9 @@ const transactionErrorCountChartPreview = createApmServerRoute({ endpoint: 'GET /internal/apm/alerts/chart_preview/transaction_error_count', params: t.type({ query: alertParamsRt }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ errorCountChartPreview: Array<{ x: number; y: number }> }> => { const setup = await setupRequest(resources); const { params } = resources; @@ -74,7 +77,11 @@ const transactionDurationChartPreview = createApmServerRoute({ endpoint: 'GET /internal/apm/alerts/chart_preview/transaction_duration', params: t.type({ query: alertParamsRt }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + latencyChartPreview: Array<{ x: number; y: number | null }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; @@ -90,9 +97,9 @@ const transactionDurationChartPreview = createApmServerRoute({ }, }); -export const alertsChartPreviewRouteRepository = - createApmServerRouteRepository() - .add(transactionErrorRateChartPreview) - .add(transactionDurationChartPreview) - .add(transactionErrorCountChartPreview) - .add(transactionDurationChartPreview); +export const alertsChartPreviewRouteRepository = { + ...transactionErrorRateChartPreview, + ...transactionDurationChartPreview, + ...transactionErrorCountChartPreview, + ...transactionDurationChartPreview, +}; diff --git a/x-pack/plugins/apm/server/routes/apm_routes/create_apm_server_route_repository.ts b/x-pack/plugins/apm/server/routes/apm_routes/create_apm_server_route_repository.ts deleted file mode 100644 index 43a5c2e33c9f8..0000000000000 --- a/x-pack/plugins/apm/server/routes/apm_routes/create_apm_server_route_repository.ts +++ /dev/null @@ -1,15 +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 { createServerRouteRepository } from '@kbn/server-route-repository'; -import { APMRouteCreateOptions, APMRouteHandlerResources } from '../typings'; - -export function createApmServerRouteRepository() { - return createServerRouteRepository< - APMRouteHandlerResources, - APMRouteCreateOptions - >(); -} diff --git a/x-pack/plugins/apm/server/routes/apm_routes/get_global_apm_server_route_repository.ts b/x-pack/plugins/apm/server/routes/apm_routes/get_global_apm_server_route_repository.ts index 1462e7540650a..0af279b276d6c 100644 --- a/x-pack/plugins/apm/server/routes/apm_routes/get_global_apm_server_route_repository.ts +++ b/x-pack/plugins/apm/server/routes/apm_routes/get_global_apm_server_route_repository.ts @@ -13,7 +13,6 @@ import { PickByValue } from 'utility-types'; import { correlationsRouteRepository } from '../correlations/route'; import { alertsChartPreviewRouteRepository } from '../alerts/route'; import { backendsRouteRepository } from '../backends/route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { environmentsRouteRepository } from '../environments/route'; import { errorsRouteRepository } from '../errors/route'; import { apmFleetRouteRepository } from '../fleet/route'; @@ -33,47 +32,46 @@ import { customLinkRouteRepository } from '../settings/custom_link/route'; import { sourceMapsRouteRepository } from '../source_maps/route'; import { traceRouteRepository } from '../traces/route'; import { transactionRouteRepository } from '../transactions/route'; -import { APMRouteHandlerResources } from '../typings'; -import { historicalDataRouteRepository } from '../historical_data'; +import { historicalDataRouteRepository } from '../historical_data/route'; import { eventMetadataRouteRepository } from '../event_metadata/route'; import { suggestionsRouteRepository } from '../suggestions/route'; import { agentKeysRouteRepository } from '../agent_keys/route'; const getTypedGlobalApmServerRouteRepository = () => { - const repository = createApmServerRouteRepository() - .merge(dataViewRouteRepository) - .merge(environmentsRouteRepository) - .merge(errorsRouteRepository) - .merge(latencyDistributionRouteRepository) - .merge(metricsRouteRepository) - .merge(observabilityOverviewRouteRepository) - .merge(rumRouteRepository) - .merge(serviceMapRouteRepository) - .merge(serviceNodeRouteRepository) - .merge(serviceRouteRepository) - .merge(suggestionsRouteRepository) - .merge(traceRouteRepository) - .merge(transactionRouteRepository) - .merge(alertsChartPreviewRouteRepository) - .merge(agentConfigurationRouteRepository) - .merge(anomalyDetectionRouteRepository) - .merge(apmIndicesRouteRepository) - .merge(customLinkRouteRepository) - .merge(sourceMapsRouteRepository) - .merge(apmFleetRouteRepository) - .merge(backendsRouteRepository) - .merge(correlationsRouteRepository) - .merge(fallbackToTransactionsRouteRepository) - .merge(historicalDataRouteRepository) - .merge(eventMetadataRouteRepository) - .merge(eventMetadataRouteRepository) - .merge(agentKeysRouteRepository); + const repository = { + ...dataViewRouteRepository, + ...environmentsRouteRepository, + ...errorsRouteRepository, + ...latencyDistributionRouteRepository, + ...metricsRouteRepository, + ...observabilityOverviewRouteRepository, + ...rumRouteRepository, + ...serviceMapRouteRepository, + ...serviceNodeRouteRepository, + ...serviceRouteRepository, + ...suggestionsRouteRepository, + ...traceRouteRepository, + ...transactionRouteRepository, + ...alertsChartPreviewRouteRepository, + ...agentConfigurationRouteRepository, + ...anomalyDetectionRouteRepository, + ...apmIndicesRouteRepository, + ...customLinkRouteRepository, + ...sourceMapsRouteRepository, + ...apmFleetRouteRepository, + ...backendsRouteRepository, + ...correlationsRouteRepository, + ...fallbackToTransactionsRouteRepository, + ...historicalDataRouteRepository, + ...eventMetadataRouteRepository, + ...agentKeysRouteRepository, + }; return repository; }; -const getGlobalApmServerRouteRepository = () => { - return getTypedGlobalApmServerRouteRepository() as ServerRouteRepository; +const getGlobalApmServerRouteRepository = (): ServerRouteRepository => { + return getTypedGlobalApmServerRouteRepository(); }; export type APMServerRouteRepository = ReturnType< diff --git a/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.test.ts b/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.test.ts index c2391967f1cd2..c795bbb53d13f 100644 --- a/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.test.ts +++ b/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.test.ts @@ -6,8 +6,10 @@ */ import { jsonRt } from '@kbn/io-ts-utils'; -import { createServerRouteRepository } from '@kbn/server-route-repository'; -import { ServerRoute } from '@kbn/server-route-repository'; +import { + ServerRoute, + ServerRouteRepository, +} from '@kbn/server-route-repository'; import * as t from 'io-ts'; import { CoreSetup, Logger } from 'src/core/server'; import { APMConfig } from '../..'; @@ -56,12 +58,6 @@ const getRegisterRouteDependencies = () => { }; }; -const getRepository = () => - createServerRouteRepository< - APMRouteHandlerResources, - APMRouteCreateOptions - >(); - const initApi = ( routes: Array< ServerRoute< @@ -75,11 +71,10 @@ const initApi = ( ) => { const { mocks, dependencies } = getRegisterRouteDependencies(); - let repository = getRepository(); - - routes.forEach((route) => { - repository = repository.add(route); - }); + const repository: ServerRouteRepository = {}; + for (const route of routes) { + repository[route.endpoint] = route; + } registerRoutes({ ...dependencies, diff --git a/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.ts b/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.ts index e84f97c70691b..aa8b5feec4afc 100644 --- a/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.ts +++ b/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.ts @@ -54,13 +54,13 @@ export function registerRoutes({ core: APMRouteHandlerResources['core']; plugins: APMRouteHandlerResources['plugins']; logger: APMRouteHandlerResources['logger']; - repository: ServerRouteRepository; + repository: ServerRouteRepository; config: APMRouteHandlerResources['config']; ruleDataClient: APMRouteHandlerResources['ruleDataClient']; telemetryUsageCounter?: TelemetryUsageCounter; kibanaVersion: string; }) { - const routes = repository.getRoutes(); + const routes = Object.values(repository); const router = core.setup.http.createRouter(); @@ -117,10 +117,10 @@ export function registerRoutes({ ), ruleDataClient, kibanaVersion, - }).then((value) => { + }).then((value: Record | undefined | null) => { return { aborted: false, - data: value as Record | undefined | null, + data: value, }; }), request.events.aborted$.toPromise().then(() => { diff --git a/x-pack/plugins/apm/server/routes/backends/route.ts b/x-pack/plugins/apm/server/routes/backends/route.ts index 4f8d404fc529f..02dac877715a9 100644 --- a/x-pack/plugins/apm/server/routes/backends/route.ts +++ b/x-pack/plugins/apm/server/routes/backends/route.ts @@ -15,7 +15,6 @@ import { rangeRt, } from '../default_api_types'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { getMetadataForBackend } from './get_metadata_for_backend'; import { getLatencyChartsForBackend } from './get_latency_charts_for_backend'; import { getTopBackends } from './get_top_backends'; @@ -41,7 +40,59 @@ const topBackendsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + backends: Array<{ + currentStats: { + latency: { + value: number | null; + timeseries: Array; + }; + throughput: { + value: number | null; + timeseries: Array; + }; + errorRate: { + value: number | null; + timeseries: Array; + }; + totalTime: { + value: number | null; + timeseries: Array; + }; + } & { impact: number }; + previousStats: + | ({ + latency: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + throughput: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + errorRate: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + totalTime: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + } & { impact: number }) + | null; + location: import('./../../../common/connections').Node; + }>; + }> => { const setup = await setupRequest(resources); const { environment, offset, numBuckets, kuery, start, end } = resources.params.query; @@ -86,7 +137,59 @@ const upstreamServicesForBackendRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + services: Array<{ + currentStats: { + latency: { + value: number | null; + timeseries: Array; + }; + throughput: { + value: number | null; + timeseries: Array; + }; + errorRate: { + value: number | null; + timeseries: Array; + }; + totalTime: { + value: number | null; + timeseries: Array; + }; + } & { impact: number }; + previousStats: + | ({ + latency: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + throughput: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + errorRate: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + totalTime: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + } & { impact: number }) + | null; + location: import('./../../../common/connections').Node; + }>; + }> => { const setup = await setupRequest(resources); const { query: { @@ -141,7 +244,11 @@ const backendMetadataRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + metadata: { spanType: string | undefined; spanSubtype: string | undefined }; + }> => { const setup = await setupRequest(resources); const { params } = resources; @@ -172,7 +279,12 @@ const backendLatencyChartsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentTimeseries: Array<{ x: number; y: number }>; + comparisonTimeseries: Array<{ x: number; y: number }> | null; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { backendName, kuery, environment, offset, start, end } = @@ -218,7 +330,12 @@ const backendThroughputChartsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentTimeseries: Array<{ x: number; y: number | null }>; + comparisonTimeseries: Array<{ x: number; y: number | null }> | null; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { backendName, kuery, environment, offset, start, end } = @@ -264,7 +381,12 @@ const backendFailedTransactionRateChartsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentTimeseries: Array<{ x: number; y: number }>; + comparisonTimeseries: Array<{ x: number; y: number }> | null; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { backendName, kuery, environment, offset, start, end } = @@ -296,10 +418,11 @@ const backendFailedTransactionRateChartsRoute = createApmServerRoute({ }, }); -export const backendsRouteRepository = createApmServerRouteRepository() - .add(topBackendsRoute) - .add(upstreamServicesForBackendRoute) - .add(backendMetadataRoute) - .add(backendLatencyChartsRoute) - .add(backendThroughputChartsRoute) - .add(backendFailedTransactionRateChartsRoute); +export const backendsRouteRepository = { + ...topBackendsRoute, + ...upstreamServicesForBackendRoute, + ...backendMetadataRoute, + ...backendLatencyChartsRoute, + ...backendThroughputChartsRoute, + ...backendFailedTransactionRateChartsRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/correlations/route.ts b/x-pack/plugins/apm/server/routes/correlations/route.ts index af267cd7294eb..0e1707cc55222 100644 --- a/x-pack/plugins/apm/server/routes/correlations/route.ts +++ b/x-pack/plugins/apm/server/routes/correlations/route.ts @@ -26,7 +26,6 @@ import { fetchFieldsStats } from './queries/field_stats/get_fields_stats'; import { withApmSpan } from '../../utils/with_apm_span'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; const INVALID_LICENSE = i18n.translate('xpack.apm.correlations.license.text', { @@ -49,7 +48,7 @@ const fieldCandidatesRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ fieldCandidates: string[] }> => { const { context } = resources; if (!isActivePlatinumLicense(context.licensing.license)) { throw Boom.forbidden(INVALID_LICENSE); @@ -87,7 +86,14 @@ const fieldStatsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + stats: Array< + import('./../../../common/correlations/field_stats_types').FieldStats + >; + errors: any[]; + }> => { const { context } = resources; if (!isActivePlatinumLicense(context.licensing.license)) { throw Boom.forbidden(INVALID_LICENSE); @@ -132,7 +138,11 @@ const fieldValueStatsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise< + import('./../../../common/correlations/field_stats_types').TopValuesStats + > => { const { context } = resources; if (!isActivePlatinumLicense(context.licensing.license)) { throw Boom.forbidden(INVALID_LICENSE); @@ -176,7 +186,14 @@ const fieldValuePairsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + fieldValuePairs: Array< + import('./../../../common/correlations/types').FieldValuePair + >; + errors: any[]; + }> => { const { context } = resources; if (!isActivePlatinumLicense(context.licensing.license)) { throw Boom.forbidden(INVALID_LICENSE); @@ -225,7 +242,15 @@ const significantCorrelationsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + latencyCorrelations: Array< + import('./../../../common/correlations/latency_correlations/types').LatencyCorrelation + >; + ccsWarning: boolean; + totalDocCount: number; + }> => { const { context } = resources; if (!isActivePlatinumLicense(context.licensing.license)) { throw Boom.forbidden(INVALID_LICENSE); @@ -271,7 +296,14 @@ const pValuesRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + failedTransactionsCorrelations: Array< + import('./../../../common/correlations/failed_transactions_correlations/types').FailedTransactionsCorrelation + >; + ccsWarning: boolean; + }> => { const { context } = resources; if (!isActivePlatinumLicense(context.licensing.license)) { throw Boom.forbidden(INVALID_LICENSE); @@ -294,10 +326,11 @@ const pValuesRoute = createApmServerRoute({ }, }); -export const correlationsRouteRepository = createApmServerRouteRepository() - .add(pValuesRoute) - .add(fieldCandidatesRoute) - .add(fieldStatsRoute) - .add(fieldValueStatsRoute) - .add(fieldValuePairsRoute) - .add(significantCorrelationsRoute); +export const correlationsRouteRepository = { + ...pValuesRoute, + ...fieldCandidatesRoute, + ...fieldStatsRoute, + ...fieldValueStatsRoute, + ...fieldValuePairsRoute, + ...significantCorrelationsRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/data_view/route.ts b/x-pack/plugins/apm/server/routes/data_view/route.ts index 83d2ac35b3672..b918e687bd7cd 100644 --- a/x-pack/plugins/apm/server/routes/data_view/route.ts +++ b/x-pack/plugins/apm/server/routes/data_view/route.ts @@ -6,7 +6,6 @@ */ import { createStaticDataView } from './create_static_data_view'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { setupRequest } from '../../lib/helpers/setup_request'; import { getDynamicDataView } from './get_dynamic_data_view'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; @@ -14,7 +13,7 @@ import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; const staticDataViewRoute = createApmServerRoute({ endpoint: 'POST /internal/apm/data_view/static', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ created: boolean }> => { const { request, core, @@ -46,7 +45,15 @@ const staticDataViewRoute = createApmServerRoute({ const dynamicDataViewRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/data_view/dynamic', options: { tags: ['access:apm'] }, - handler: async ({ context, config, logger }) => { + handler: async ({ + context, + config, + logger, + }): Promise<{ + dynamicDataView: + | import('./get_dynamic_data_view').DataViewTitleAndFields + | undefined; + }> => { const dynamicDataView = await getDynamicDataView({ context, config, @@ -56,6 +63,7 @@ const dynamicDataViewRoute = createApmServerRoute({ }, }); -export const dataViewRouteRepository = createApmServerRouteRepository() - .add(staticDataViewRoute) - .add(dynamicDataViewRoute); +export const dataViewRouteRepository = { + ...staticDataViewRoute, + ...dynamicDataViewRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/environments/route.ts b/x-pack/plugins/apm/server/routes/environments/route.ts index 6c980187cd331..0b01f6193ff2f 100644 --- a/x-pack/plugins/apm/server/routes/environments/route.ts +++ b/x-pack/plugins/apm/server/routes/environments/route.ts @@ -12,7 +12,6 @@ import { setupRequest } from '../../lib/helpers/setup_request'; import { getEnvironments } from './get_environments'; import { rangeRt } from '../default_api_types'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; const environmentsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/environments', @@ -25,7 +24,18 @@ const environmentsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + environments: Array< + | 'ENVIRONMENT_NOT_DEFINED' + | 'ENVIRONMENT_ALL' + | t.Branded< + string, + import('./../../../../../../node_modules/@types/kbn__io-ts-utils/index').NonEmptyStringBrand + > + >; + }> => { const setup = await setupRequest(resources); const { context, params } = resources; const { serviceName, start, end } = params.query; @@ -52,5 +62,4 @@ const environmentsRoute = createApmServerRoute({ }, }); -export const environmentsRouteRepository = - createApmServerRouteRepository().add(environmentsRoute); +export const environmentsRouteRepository = environmentsRoute; diff --git a/x-pack/plugins/apm/server/routes/errors/route.ts b/x-pack/plugins/apm/server/routes/errors/route.ts index 2ead97f74d373..f1d1c79b24f18 100644 --- a/x-pack/plugins/apm/server/routes/errors/route.ts +++ b/x-pack/plugins/apm/server/routes/errors/route.ts @@ -16,7 +16,6 @@ import { rangeRt, comparisonRangeRt, } from '../default_api_types'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { getErrorGroupMainStatistics } from './get_error_groups/get_error_group_main_statistics'; import { getErrorGroupPeriods } from './get_error_groups/get_error_group_detailed_statistics'; import { getErrorGroupSample } from './get_error_groups/get_error_group_sample'; @@ -42,7 +41,19 @@ const errorsMainStatisticsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + errorGroups: Array<{ + groupId: string; + name: string; + lastSeen: number; + occurrences: number; + culprit: string | undefined; + handled: boolean | undefined; + type: string | undefined; + }>; + }> => { const { params } = resources; const setup = await setupRequest(resources); const { serviceName } = params.path; @@ -92,7 +103,21 @@ const errorsDetailedStatisticsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: import('./../../../../../../node_modules/@types/lodash/ts3.1/index').Dictionary<{ + groupId: string; + timeseries: Array; + }>; + previousPeriod: import('./../../../../../../node_modules/@types/lodash/ts3.1/index').Dictionary<{ + timeseries: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + groupId: string; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; @@ -137,7 +162,15 @@ const errorGroupsRoute = createApmServerRoute({ query: t.intersection([environmentRt, kueryRt, rangeRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + transaction: + | import('./../../../typings/es_schemas/ui/transaction').Transaction + | undefined; + error: import('./../../../typings/es_schemas/ui/apm_error').APMError; + occurrencesCount: number; + }> => { const { params } = resources; const setup = await setupRequest(resources); const { serviceName, groupId } = params.path; @@ -172,7 +205,16 @@ const errorDistributionRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: Array<{ x: number; y: number }>; + previousPeriod: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + bucketSize: number; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -199,8 +241,9 @@ const errorDistributionRoute = createApmServerRoute({ }, }); -export const errorsRouteRepository = createApmServerRouteRepository() - .add(errorsMainStatisticsRoute) - .add(errorsDetailedStatisticsRoute) - .add(errorGroupsRoute) - .add(errorDistributionRoute); +export const errorsRouteRepository = { + ...errorsMainStatisticsRoute, + ...errorsDetailedStatisticsRoute, + ...errorGroupsRoute, + ...errorDistributionRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/event_metadata/route.ts b/x-pack/plugins/apm/server/routes/event_metadata/route.ts index 3140372aa69de..a057be53ef43f 100644 --- a/x-pack/plugins/apm/server/routes/event_metadata/route.ts +++ b/x-pack/plugins/apm/server/routes/event_metadata/route.ts @@ -6,7 +6,6 @@ */ import * as t from 'io-ts'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; import { getEventMetadata } from './get_event_metadata'; import { processorEventRt } from '../../../common/processor_event'; @@ -21,7 +20,9 @@ const eventMetadataRoute = createApmServerRoute({ id: t.string, }), }), - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ metadata: Partial> }> => { const setup = await setupRequest(resources); const { @@ -40,5 +41,4 @@ const eventMetadataRoute = createApmServerRoute({ }, }); -export const eventMetadataRouteRepository = - createApmServerRouteRepository().add(eventMetadataRoute); +export const eventMetadataRouteRepository = eventMetadataRoute; diff --git a/x-pack/plugins/apm/server/routes/fallback_to_transactions/route.ts b/x-pack/plugins/apm/server/routes/fallback_to_transactions/route.ts index 77b5aeeac6ee8..60355b5447b85 100644 --- a/x-pack/plugins/apm/server/routes/fallback_to_transactions/route.ts +++ b/x-pack/plugins/apm/server/routes/fallback_to_transactions/route.ts @@ -9,7 +9,6 @@ import * as t from 'io-ts'; import { getIsUsingTransactionEvents } from '../../lib/helpers/transactions/get_is_using_transaction_events'; import { setupRequest } from '../../lib/helpers/setup_request'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { kueryRt, rangeRt } from '../default_api_types'; const fallbackToTransactionsRoute = createApmServerRoute({ @@ -18,7 +17,7 @@ const fallbackToTransactionsRoute = createApmServerRoute({ query: t.intersection([kueryRt, t.partial(rangeRt.props)]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ fallbackToTransactions: boolean }> => { const setup = await setupRequest(resources); const { params: { @@ -37,4 +36,4 @@ const fallbackToTransactionsRoute = createApmServerRoute({ }); export const fallbackToTransactionsRouteRepository = - createApmServerRouteRepository().add(fallbackToTransactionsRoute); + fallbackToTransactionsRoute; diff --git a/x-pack/plugins/apm/server/routes/fleet/route.ts b/x-pack/plugins/apm/server/routes/fleet/route.ts index 5c176ffaab84d..668d4e207208c 100644 --- a/x-pack/plugins/apm/server/routes/fleet/route.ts +++ b/x-pack/plugins/apm/server/routes/fleet/route.ts @@ -25,12 +25,11 @@ import { isSuperuser } from './is_superuser'; import { getInternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client'; import { setupRequest } from '../../lib/helpers/setup_request'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; const hasFleetDataRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/fleet/has_data', options: { tags: [] }, - handler: async ({ core, plugins }) => { + handler: async ({ core, plugins }): Promise<{ hasData: boolean }> => { const fleetPluginStart = await plugins.fleet?.start(); if (!fleetPluginStart) { return { hasData: false }; @@ -46,7 +45,36 @@ const hasFleetDataRoute = createApmServerRoute({ const fleetAgentsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/fleet/agents', options: { tags: [] }, - handler: async ({ core, plugins }) => { + handler: async ({ + core, + plugins, + }): Promise< + | { + cloudStandaloneSetup: + | { + apmServerUrl: string | undefined; + secretToken: string | undefined; + } + | undefined; + fleetAgents: never[]; + isFleetEnabled: false; + } + | { + cloudStandaloneSetup: + | { + apmServerUrl: string | undefined; + secretToken: string | undefined; + } + | undefined; + isFleetEnabled: true; + fleetAgents: Array<{ + id: string; + name: string; + apmServerUrl: any; + secretToken: any; + }>; + } + > => { const cloudSetup = plugins.cloud?.setup; const cloudStandaloneSetup = cloudSetup ? { @@ -99,7 +127,7 @@ const saveApmServerSchemaRoute = createApmServerRoute({ schema: t.record(t.string, t.unknown), }), }), - handler: async (resources) => { + handler: async (resources): Promise => { const { params, logger, core } = resources; const savedObjectsClient = await getInternalSavedObjectsClient(core.setup); const { schema } = params.body; @@ -115,7 +143,9 @@ const saveApmServerSchemaRoute = createApmServerRoute({ const getUnsupportedApmServerSchemaRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/fleet/apm_server_schema/unsupported', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ unsupported: Array<{ key: string; value: any }> }> => { const { context } = resources; const savedObjectsClient = context.core.savedObjects.client; return { @@ -127,7 +157,18 @@ const getUnsupportedApmServerSchemaRoute = createApmServerRoute({ const getMigrationCheckRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/fleet/migration_check', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + has_cloud_agent_policy: boolean; + has_cloud_apm_package_policy: boolean; + cloud_apm_migration_enabled: boolean; + has_required_role: boolean | undefined; + cloud_apm_package_policy: + | import('./../../../../fleet/common/index').PackagePolicy + | undefined; + has_apm_integrations: boolean; + }> => { const { core, plugins, context, config, request } = resources; const cloudApmMigrationEnabled = config.agent.migrations.enabled; if (!plugins.fleet || !plugins.security) { @@ -164,7 +205,11 @@ const getMigrationCheckRoute = createApmServerRoute({ const createCloudApmPackagePolicyRoute = createApmServerRoute({ endpoint: 'POST /internal/apm/fleet/cloud_apm_package_policy', options: { tags: ['access:apm', 'access:apm_write'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + cloudApmPackagePolicy: import('./../../../../fleet/common/index').PackagePolicy; + }> => { const { plugins, context, config, request, logger, kibanaVersion } = resources; const cloudApmMigrationEnabled = config.agent.migrations.enabled; @@ -200,13 +245,14 @@ const createCloudApmPackagePolicyRoute = createApmServerRoute({ }, }); -export const apmFleetRouteRepository = createApmServerRouteRepository() - .add(hasFleetDataRoute) - .add(fleetAgentsRoute) - .add(saveApmServerSchemaRoute) - .add(getUnsupportedApmServerSchemaRoute) - .add(getMigrationCheckRoute) - .add(createCloudApmPackagePolicyRoute); +export const apmFleetRouteRepository = { + ...hasFleetDataRoute, + ...fleetAgentsRoute, + ...saveApmServerSchemaRoute, + ...getUnsupportedApmServerSchemaRoute, + ...getMigrationCheckRoute, + ...createCloudApmPackagePolicyRoute, +}; const FLEET_SECURITY_REQUIRED_MESSAGE = i18n.translate( 'xpack.apm.api.fleet.fleetSecurityRequired', diff --git a/x-pack/plugins/apm/server/routes/historical_data/index.ts b/x-pack/plugins/apm/server/routes/historical_data/route.ts similarity index 75% rename from x-pack/plugins/apm/server/routes/historical_data/index.ts rename to x-pack/plugins/apm/server/routes/historical_data/route.ts index f488669fffa11..e9836df61acbf 100644 --- a/x-pack/plugins/apm/server/routes/historical_data/index.ts +++ b/x-pack/plugins/apm/server/routes/historical_data/route.ts @@ -7,18 +7,16 @@ import { setupRequest } from '../../lib/helpers/setup_request'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { hasHistoricalAgentData } from './has_historical_agent_data'; const hasDataRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/has_data', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ hasData: boolean }> => { const setup = await setupRequest(resources); const hasData = await hasHistoricalAgentData(setup); return { hasData }; }, }); -export const historicalDataRouteRepository = - createApmServerRouteRepository().add(hasDataRoute); +export const historicalDataRouteRepository = hasDataRoute; diff --git a/x-pack/plugins/apm/server/routes/latency_distribution/route.ts b/x-pack/plugins/apm/server/routes/latency_distribution/route.ts index 675429df9df3f..a51c03238709e 100644 --- a/x-pack/plugins/apm/server/routes/latency_distribution/route.ts +++ b/x-pack/plugins/apm/server/routes/latency_distribution/route.ts @@ -10,7 +10,6 @@ import { toNumberRt } from '@kbn/io-ts-utils'; import { getOverallLatencyDistribution } from './get_overall_latency_distribution'; import { setupRequest } from '../../lib/helpers/setup_request'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; const latencyOverallDistributionRoute = createApmServerRoute({ @@ -37,7 +36,9 @@ const latencyOverallDistributionRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise => { const setup = await setupRequest(resources); const { @@ -68,4 +69,4 @@ const latencyOverallDistributionRoute = createApmServerRoute({ }); export const latencyDistributionRouteRepository = - createApmServerRouteRepository().add(latencyOverallDistributionRoute); + latencyOverallDistributionRoute; diff --git a/x-pack/plugins/apm/server/routes/metrics/route.ts b/x-pack/plugins/apm/server/routes/metrics/route.ts index 4e15188827e9b..3ee0c3b0fac84 100644 --- a/x-pack/plugins/apm/server/routes/metrics/route.ts +++ b/x-pack/plugins/apm/server/routes/metrics/route.ts @@ -9,7 +9,6 @@ import * as t from 'io-ts'; import { setupRequest } from '../../lib/helpers/setup_request'; import { getMetricsChartDataByAgent } from './get_metrics_chart_data_by_agent'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; const metricsChartsRoute = createApmServerRoute({ @@ -31,7 +30,23 @@ const metricsChartsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + charts: Array<{ + title: string; + key: string; + yUnit: import('./../../../typings/timeseries').YUnit; + series: Array<{ + title: string; + key: string; + type: import('./../../../typings/timeseries').ChartType; + color: string; + overallValue: number; + data: Array<{ x: number; y: number | null }>; + }>; + }>; + }> => { const { params } = resources; const setup = await setupRequest(resources); const { serviceName } = params.path; @@ -53,5 +68,4 @@ const metricsChartsRoute = createApmServerRoute({ }, }); -export const metricsRouteRepository = - createApmServerRouteRepository().add(metricsChartsRoute); +export const metricsRouteRepository = metricsChartsRoute; diff --git a/x-pack/plugins/apm/server/routes/observability_overview/route.ts b/x-pack/plugins/apm/server/routes/observability_overview/route.ts index b94fcf2f32a02..faccd5eb29602 100644 --- a/x-pack/plugins/apm/server/routes/observability_overview/route.ts +++ b/x-pack/plugins/apm/server/routes/observability_overview/route.ts @@ -14,13 +14,17 @@ import { getHasData } from './has_data'; import { rangeRt } from '../default_api_types'; import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; import { withApmSpan } from '../../utils/with_apm_span'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; const observabilityOverviewHasDataRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/observability_overview/has_data', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + hasData: boolean; + indices: import('./../../../../observability/common/typings').ApmIndicesConfig; + }> => { const setup = await setupRequest(resources); return await getHasData({ setup }); }, @@ -35,7 +39,14 @@ const observabilityOverviewRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + serviceCount: number; + transactionPerMinute: + | { value: undefined; timeseries: never[] } + | { value: number; timeseries: Array<{ x: number; y: number | null }> }; + }> => { const setup = await setupRequest(resources); const { bucketSize, intervalString, start, end } = resources.params.query; @@ -69,7 +80,7 @@ const observabilityOverviewRoute = createApmServerRoute({ }, }); -export const observabilityOverviewRouteRepository = - createApmServerRouteRepository() - .add(observabilityOverviewRoute) - .add(observabilityOverviewHasDataRoute); +export const observabilityOverviewRouteRepository = { + ...observabilityOverviewRoute, + ...observabilityOverviewHasDataRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/rum_client/route.ts b/x-pack/plugins/apm/server/routes/rum_client/route.ts index 1b1b87f5d1198..660f1c6afc275 100644 --- a/x-pack/plugins/apm/server/routes/rum_client/route.ts +++ b/x-pack/plugins/apm/server/routes/rum_client/route.ts @@ -20,7 +20,6 @@ import { getVisitorBreakdown } from './get_visitor_breakdown'; import { getWebCoreVitals } from './get_web_core_vitals'; import { hasRumData } from './has_rum_data'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { rangeRt } from '../default_api_types'; import { UxUIFilters } from '../../../typings/ui_filters'; import { APMRouteHandlerResources } from '../typings'; @@ -70,7 +69,14 @@ const rumClientMetricsRoute = createApmServerRoute({ query: uxQueryRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + pageViews: { value: number }; + totalPageLoadDuration: { value: number }; + backEnd: { value: number }; + frontEnd: { value: number }; + }> => { const setup = await setupUXRequest(resources); const { @@ -93,7 +99,16 @@ const rumPageLoadDistributionRoute = createApmServerRoute({ query: t.intersection([uxQueryRt, percentileRangeRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + pageLoadDistribution: { + pageLoadDistribution: Array<{ x: number; y: number }>; + percentiles: Record | undefined; + minDuration: number; + maxDuration: number; + } | null; + }> => { const setup = await setupUXRequest(resources); const { @@ -123,7 +138,13 @@ const rumPageLoadDistBreakdownRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + pageLoadDistBreakdown: + | Array<{ name: string; data: Array<{ x: number; y: number }> }> + | undefined; + }> => { const setup = await setupUXRequest(resources); const { @@ -150,7 +171,9 @@ const rumPageViewsTrendRoute = createApmServerRoute({ query: t.intersection([uxQueryRt, t.partial({ breakdowns: t.string })]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ topItems: string[]; items: Array> }> => { const setup = await setupUXRequest(resources); const { @@ -173,7 +196,7 @@ const rumServicesRoute = createApmServerRoute({ query: t.intersection([uiFiltersRt, rangeRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ rumServices: string[] }> => { const setup = await setupUXRequest(resources); const { query: { start, end }, @@ -189,7 +212,12 @@ const rumVisitorsBreakdownRoute = createApmServerRoute({ query: uxQueryRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + os: Array<{ count: number; name: string }>; + browsers: Array<{ count: number; name: string }>; + }> => { const setup = await setupUXRequest(resources); const { @@ -211,7 +239,19 @@ const rumWebCoreVitals = createApmServerRoute({ query: uxQueryRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + coreVitalPages: number; + cls: number | null; + fid: number | null | undefined; + lcp: number | null | undefined; + tbt: number; + fcp: number | null | undefined; + lcpRanks: number[]; + fidRanks: number[]; + clsRanks: number[]; + }> => { const setup = await setupUXRequest(resources); const { @@ -234,7 +274,13 @@ const rumLongTaskMetrics = createApmServerRoute({ query: uxQueryRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + noOfLongTasks: number; + sumOfLongTasks: number; + longestLongTask: number; + }> => { const setup = await setupUXRequest(resources); const { @@ -257,7 +303,12 @@ const rumUrlSearch = createApmServerRoute({ query: uxQueryRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + total: number; + items: Array<{ url: string; count: number; pld: number }>; + }> => { const setup = await setupUXRequest(resources); const { @@ -285,7 +336,20 @@ const rumJSErrors = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + totalErrorPages: number; + totalErrors: number; + totalErrorGroups: number; + items: + | Array<{ + count: number; + errorGroupId: string | number; + errorMessage: string; + }> + | undefined; + }> => { const setup = await setupUXRequest(resources); const { @@ -313,7 +377,13 @@ const rumHasDataRoute = createApmServerRoute({ }), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + indices: string; + hasData: boolean; + serviceName: string | number | undefined; + }> => { const setup = await setupUXRequest(resources); const { query: { start, end }, @@ -350,15 +420,16 @@ async function setupUXRequest( }; } -export const rumRouteRepository = createApmServerRouteRepository() - .add(rumClientMetricsRoute) - .add(rumPageLoadDistributionRoute) - .add(rumPageLoadDistBreakdownRoute) - .add(rumPageViewsTrendRoute) - .add(rumServicesRoute) - .add(rumVisitorsBreakdownRoute) - .add(rumWebCoreVitals) - .add(rumLongTaskMetrics) - .add(rumUrlSearch) - .add(rumJSErrors) - .add(rumHasDataRoute); +export const rumRouteRepository = { + ...rumClientMetricsRoute, + ...rumPageLoadDistributionRoute, + ...rumPageLoadDistBreakdownRoute, + ...rumPageViewsTrendRoute, + ...rumServicesRoute, + ...rumVisitorsBreakdownRoute, + ...rumWebCoreVitals, + ...rumLongTaskMetrics, + ...rumUrlSearch, + ...rumJSErrors, + ...rumHasDataRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/service_map/route.ts b/x-pack/plugins/apm/server/routes/service_map/route.ts index 6b002e913204b..e3a6bb91441ae 100644 --- a/x-pack/plugins/apm/server/routes/service_map/route.ts +++ b/x-pack/plugins/apm/server/routes/service_map/route.ts @@ -16,7 +16,6 @@ import { getServiceMap } from './get_service_map'; import { getServiceMapBackendNodeInfo } from './get_service_map_backend_node_info'; import { getServiceMapServiceNodeInfo } from './get_service_map_service_node_info'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { environmentRt, offsetRt, rangeRt } from '../default_api_types'; const serviceMapRoute = createApmServerRoute({ @@ -31,7 +30,57 @@ const serviceMapRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + elements: Array< + | import('./../../../common/service_map').ConnectionElement + | { + data: { + id: string; + 'span.type': string; + label: string; + groupedConnections: Array< + | { + 'service.name': string; + 'service.environment': string | null; + 'agent.name': string; + serviceAnomalyStats?: + | import('./../../../common/anomaly_detection/index').ServiceAnomalyStats + | undefined; + label: string | undefined; + id?: string | undefined; + parent?: string | undefined; + position?: + | import('./../../../../../../node_modules/@types/cytoscape/index').Position + | undefined; + } + | { + 'span.destination.service.resource': string; + 'span.type': string; + 'span.subtype': string; + label: string | undefined; + id?: string | undefined; + parent?: string | undefined; + position?: + | import('./../../../../../../node_modules/@types/cytoscape/index').Position + | undefined; + } + | { + id: string; + source: string | undefined; + target: string | undefined; + label: string | undefined; + bidirectional?: boolean | undefined; + isInverseEdge?: boolean | undefined; + } + | undefined + >; + }; + } + | { data: { id: string; source: string; target: string } } + >; + }> => { const { config, context, params, logger } = resources; if (!config.serviceMapEnabled) { throw Boom.notFound(); @@ -78,7 +127,14 @@ const serviceMapServiceNodeRoute = createApmServerRoute({ query: t.intersection([environmentRt, rangeRt, offsetRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: import('./../../../common/service_map').NodeStats; + previousPeriod: + | import('./../../../common/service_map').NodeStats + | undefined; + }> => { const { config, context, params } = resources; if (!config.serviceMapEnabled) { @@ -133,7 +189,14 @@ const serviceMapBackendNodeRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: import('./../../../common/service_map').NodeStats; + previousPeriod: + | import('./../../../common/service_map').NodeStats + | undefined; + }> => { const { config, context, params } = resources; if (!config.serviceMapEnabled) { @@ -161,7 +224,8 @@ const serviceMapBackendNodeRoute = createApmServerRoute({ }, }); -export const serviceMapRouteRepository = createApmServerRouteRepository() - .add(serviceMapRoute) - .add(serviceMapServiceNodeRoute) - .add(serviceMapBackendNodeRoute); +export const serviceMapRouteRepository = { + ...serviceMapRoute, + ...serviceMapServiceNodeRoute, + ...serviceMapBackendNodeRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/service_nodes/route.ts b/x-pack/plugins/apm/server/routes/service_nodes/route.ts index 027a907dd2659..eef2b29b1e373 100644 --- a/x-pack/plugins/apm/server/routes/service_nodes/route.ts +++ b/x-pack/plugins/apm/server/routes/service_nodes/route.ts @@ -6,7 +6,6 @@ */ import * as t from 'io-ts'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; import { setupRequest } from '../../lib/helpers/setup_request'; import { getServiceNodes } from './get_service_nodes'; @@ -22,7 +21,18 @@ const serviceNodesRoute = createApmServerRoute({ query: t.intersection([kueryRt, rangeRt, environmentRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + serviceNodes: Array<{ + name: string; + cpu: number | null; + heapMemory: number | null; + hostName: string | null | undefined; + nonHeapMemory: number | null; + threadCount: number | null; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -40,5 +50,4 @@ const serviceNodesRoute = createApmServerRoute({ }, }); -export const serviceNodeRouteRepository = - createApmServerRouteRepository().add(serviceNodesRoute); +export const serviceNodeRouteRepository = serviceNodesRoute; diff --git a/x-pack/plugins/apm/server/routes/services/route.ts b/x-pack/plugins/apm/server/routes/services/route.ts index de5f457f18dec..db7793568676b 100644 --- a/x-pack/plugins/apm/server/routes/services/route.ts +++ b/x-pack/plugins/apm/server/routes/services/route.ts @@ -30,7 +30,6 @@ import { getServiceProfilingTimeline } from './profiling/get_service_profiling_t import { getServiceInfrastructure } from './get_service_infrastructure'; import { withApmSpan } from '../../utils/with_apm_span'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { comparisonRangeRt, environmentRt, @@ -57,7 +56,45 @@ const servicesRoute = createApmServerRoute({ query: t.intersection([environmentRt, kueryRt, rangeRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + async handler(resources): Promise<{ + items: import('./../../../common/utils/join_by_key/index').JoinedReturnType< + | { + serviceName: string; + transactionType: string; + environments: string[]; + agentName: import('./../../../typings/es_schemas/ui/fields/agent').AgentName; + latency: number | null; + transactionErrorRate: number; + throughput: number; + } + | { + serviceName: string; + environments: string[]; + agentName: import('./../../../typings/es_schemas/ui/fields/agent').AgentName; + } + | { + serviceName: string; + healthStatus: import('./../../../common/service_health_status').ServiceHealthStatus; + }, + { + serviceName: string; + transactionType: string; + environments: string[]; + agentName: import('./../../../typings/es_schemas/ui/fields/agent').AgentName; + latency: number | null; + transactionErrorRate: number; + throughput: number; + } & { + serviceName: string; + environments: string[]; + agentName: import('./../../../typings/es_schemas/ui/fields/agent').AgentName; + } & { + serviceName: string; + healthStatus: import('./../../../common/service_health_status').ServiceHealthStatus; + } + >; + hasLegacyData: boolean; + }> { const setup = await setupRequest(resources); const { params, logger } = resources; const { environment, kuery, start, end } = params.query; @@ -92,7 +129,40 @@ const servicesDetailedStatisticsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: import('./../../../../../../node_modules/@types/lodash/ts3.1/index').Dictionary<{ + serviceName: string; + latency: Array<{ + x: number; + y: number | null; + }>; + transactionErrorRate: Array<{ + x: number; + y: number; + }>; + throughput: Array<{ + x: number; + y: number; + }>; + }>; + previousPeriod: import('./../../../../../../node_modules/@types/lodash/ts3.1/index').Dictionary<{ + serviceName: string; + latency: Array<{ + x: number; + y: number | null; + }>; + transactionErrorRate: Array<{ + x: number; + y: number; + }>; + throughput: Array<{ + x: number; + y: number; + }>; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { environment, kuery, offset, serviceNames, start, end } = @@ -128,7 +198,11 @@ const serviceMetadataDetailsRoute = createApmServerRoute({ query: rangeRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise< + import('./get_service_metadata_details').ServiceMetadataDetails + > => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -159,7 +233,9 @@ const serviceMetadataIconsRoute = createApmServerRoute({ query: rangeRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -192,7 +268,12 @@ const serviceAgentRoute = createApmServerRoute({ query: rangeRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise< + | { agentName?: undefined; runtimeName?: undefined } + | { agentName: string | undefined; runtimeName: string | undefined } + > => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -216,7 +297,7 @@ const serviceTransactionTypesRoute = createApmServerRoute({ query: rangeRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ transactionTypes: string[] }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -249,7 +330,9 @@ const serviceNodeMetadataRoute = createApmServerRoute({ query: t.intersection([kueryRt, rangeRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ host: string | number; containerId: string | number }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName, serviceNodeName } = params.path; @@ -275,7 +358,11 @@ const serviceAnnotationsRoute = createApmServerRoute({ query: t.intersection([environmentRt, rangeRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + annotations: Array; + }> => { const setup = await setupRequest(resources); const { params, plugins, context, request, logger } = resources; const { serviceName } = params.path; @@ -341,7 +428,13 @@ const serviceAnnotationsCreateRoute = createApmServerRoute({ }), ]), }), - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + _id: string; + _index: string; + _source: import('./../../../../observability/common/annotations').Annotation; + }> => { const { request, context, @@ -392,7 +485,15 @@ const serviceThroughputRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: Array<{ x: number; y: number | null }>; + previousPeriod: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -476,7 +577,26 @@ const serviceInstancesMainStatisticsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: Array<{ + serviceNodeName: string; + errorRate?: number | undefined; + latency?: number | undefined; + throughput?: number | undefined; + cpuUsage?: number | null | undefined; + memoryUsage?: number | null | undefined; + }>; + previousPeriod: Array<{ + serviceNodeName: string; + errorRate?: number | undefined; + latency?: number | undefined; + throughput?: number | undefined; + cpuUsage?: number | null | undefined; + memoryUsage?: number | null | undefined; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -552,7 +672,51 @@ const serviceInstancesDetailedStatisticsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: import('./../../../../../../node_modules/@types/lodash/ts3.1/index').Dictionary<{ + serviceNodeName: string; + errorRate?: + | Array + | undefined; + latency?: + | Array + | undefined; + throughput?: + | Array + | undefined; + cpuUsage?: + | Array + | undefined; + memoryUsage?: + | Array + | undefined; + }>; + previousPeriod: import('./../../../../../../node_modules/@types/lodash/ts3.1/index').Dictionary<{ + cpuUsage: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + errorRate: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + latency: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + memoryUsage: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + throughput: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + serviceNodeName: string; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -605,7 +769,57 @@ export const serviceInstancesMetadataDetails = createApmServerRoute({ query: rangeRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + '@timestamp': string; + agent: + | (import('./../../../typings/es_schemas/ui/fields/agent').Agent & { + name: string; + version: string; + }) + | ({ + name: string; + version: string; + } & import('./../../../typings/es_schemas/ui/fields/agent').Agent); + service: + | import('./../../../typings/es_schemas/raw/fields/service').Service + | (import('./../../../typings/es_schemas/raw/fields/service').Service & { + name: string; + node?: { name: string } | undefined; + environment?: string | undefined; + version?: string | undefined; + }) + | (import('./../../../typings/es_schemas/raw/fields/service').Service & { + node?: { name: string } | undefined; + }) + | (import('./../../../typings/es_schemas/raw/fields/service').Service & { + name: string; + node?: { name: string } | undefined; + environment?: string | undefined; + version?: string | undefined; + } & { node?: { name: string } | undefined }) + | (import('./../../../typings/es_schemas/raw/fields/service').Service & { + node?: { name: string } | undefined; + } & { + name: string; + node?: { name: string } | undefined; + environment?: string | undefined; + version?: string | undefined; + }); + container: + | import('./../../../typings/es_schemas/raw/fields/container').Container + | undefined; + kubernetes: + | import('./../../../typings/es_schemas/raw/fields/kubernetes').Kubernetes + | undefined; + host: + | import('./../../../typings/es_schemas/raw/fields/host').Host + | undefined; + cloud: + | import('./../../../typings/es_schemas/raw/fields/cloud').Cloud + | undefined; + }> => { const setup = await setupRequest(resources); const { serviceName, serviceNodeName } = resources.params.path; const { start, end } = resources.params.query; @@ -638,7 +852,59 @@ export const serviceDependenciesRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + serviceDependencies: Array<{ + currentStats: { + latency: { + value: number | null; + timeseries: Array; + }; + throughput: { + value: number | null; + timeseries: Array; + }; + errorRate: { + value: number | null; + timeseries: Array; + }; + totalTime: { + value: number | null; + timeseries: Array; + }; + } & { impact: number }; + previousStats: + | ({ + latency: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + throughput: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + errorRate: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + totalTime: { + value: number | null; + timeseries: Array< + import('./../../../typings/timeseries').Coordinate + >; + }; + } & { impact: number }) + | null; + location: import('./../../../common/connections').Node; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -686,7 +952,11 @@ export const serviceDependenciesBreakdownRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + breakdown: Array<{ title: string; data: Array<{ x: number; y: number }> }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -718,7 +988,23 @@ const serviceProfilingTimelineRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + profilingTimeline: Array<{ + x: number; + valueTypes: { + wall_time: number; + cpu_time: number; + samples: number; + alloc_objects: number; + alloc_space: number; + inuse_objects: number; + inuse_space: number; + unknown: number; + }; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { @@ -765,7 +1051,12 @@ const serviceProfilingStatisticsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + nodes: Record; + rootNodes: string[]; + }> => { const setup = await setupRequest(resources); const { params, logger } = resources; @@ -805,7 +1096,11 @@ const serviceAlertsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async ({ context, params, ruleDataClient }) => { + handler: async ({ + context, + params, + ruleDataClient, + }): Promise<{ alerts: Array>> }> => { const { query: { start, end, environment, transactionType }, path: { serviceName }, @@ -833,7 +1128,11 @@ const serviceInfrastructureRoute = createApmServerRoute({ query: t.intersection([kueryRt, rangeRt, environmentRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + serviceInfrastructure: { containerIds: string[]; hostNames: string[] }; + }> => { const setup = await setupRequest(resources); const { params } = resources; @@ -866,7 +1165,13 @@ const serviceAnomalyChartsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + allAnomalyTimeseries: Array< + import('./../../../common/anomaly_detection/service_anomaly_timeseries').ServiceAnomalyTimeseries + >; + }> => { const setup = await setupRequest(resources); if (!setup.ml) { @@ -904,24 +1209,25 @@ const serviceAnomalyChartsRoute = createApmServerRoute({ }, }); -export const serviceRouteRepository = createApmServerRouteRepository() - .add(servicesRoute) - .add(servicesDetailedStatisticsRoute) - .add(serviceMetadataDetailsRoute) - .add(serviceMetadataIconsRoute) - .add(serviceAgentRoute) - .add(serviceTransactionTypesRoute) - .add(serviceNodeMetadataRoute) - .add(serviceAnnotationsRoute) - .add(serviceAnnotationsCreateRoute) - .add(serviceInstancesMetadataDetails) - .add(serviceThroughputRoute) - .add(serviceInstancesMainStatisticsRoute) - .add(serviceInstancesDetailedStatisticsRoute) - .add(serviceDependenciesRoute) - .add(serviceDependenciesBreakdownRoute) - .add(serviceProfilingTimelineRoute) - .add(serviceProfilingStatisticsRoute) - .add(serviceAlertsRoute) - .add(serviceInfrastructureRoute) - .add(serviceAnomalyChartsRoute); +export const serviceRouteRepository = { + ...servicesRoute, + ...servicesDetailedStatisticsRoute, + ...serviceMetadataDetailsRoute, + ...serviceMetadataIconsRoute, + ...serviceAgentRoute, + ...serviceTransactionTypesRoute, + ...serviceNodeMetadataRoute, + ...serviceAnnotationsRoute, + ...serviceAnnotationsCreateRoute, + ...serviceInstancesMetadataDetails, + ...serviceThroughputRoute, + ...serviceInstancesMainStatisticsRoute, + ...serviceInstancesDetailedStatisticsRoute, + ...serviceDependenciesRoute, + ...serviceDependenciesBreakdownRoute, + ...serviceProfilingTimelineRoute, + ...serviceProfilingStatisticsRoute, + ...serviceAlertsRoute, + ...serviceInfrastructureRoute, + ...serviceAnomalyChartsRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts b/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts index b8245a8efaa94..53a55cc1b99b4 100644 --- a/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts +++ b/x-pack/plugins/apm/server/routes/settings/agent_configuration/route.ts @@ -25,14 +25,19 @@ import { agentConfigurationIntakeRt, } from '../../../../common/agent_configuration/runtime_types/agent_configuration_intake_rt'; import { getSearchAggregatedTransactions } from '../../../lib/helpers/transactions'; -import { createApmServerRouteRepository } from '../../apm_routes/create_apm_server_route_repository'; import { syncAgentConfigsToApmPackagePolicies } from '../../fleet/sync_agent_configs_to_apm_package_policies'; // get list of configurations const agentConfigurationRoute = createApmServerRoute({ endpoint: 'GET /api/apm/settings/agent-configuration', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + configurations: Array< + import('./../../../../common/agent_configuration/configuration_types').AgentConfiguration + >; + }> => { const setup = await setupRequest(resources); const configurations = await listConfigurations({ setup }); return { configurations }; @@ -46,7 +51,11 @@ const getSingleAgentConfigurationRoute = createApmServerRoute({ query: serviceRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise< + import('./../../../../common/agent_configuration/configuration_types').AgentConfiguration + > => { const setup = await setupRequest(resources); const { params, logger } = resources; @@ -78,7 +87,7 @@ const deleteAgentConfigurationRoute = createApmServerRoute({ service: serviceRt, }), }), - handler: async (resources) => { + handler: async (resources): Promise<{ result: string }> => { const setup = await setupRequest(resources); const { params, logger, core, telemetryUsageCounter } = resources; @@ -128,7 +137,7 @@ const createOrUpdateAgentConfigurationRoute = createApmServerRoute({ t.partial({ query: t.partial({ overwrite: toBooleanRt }) }), t.type({ body: agentConfigurationIntakeRt }), ]), - handler: async (resources) => { + handler: async (resources): Promise => { const setup = await setupRequest(resources); const { params, logger, core, telemetryUsageCounter } = resources; const { body, query } = params; @@ -187,7 +196,16 @@ const agentConfigurationSearchRoute = createApmServerRoute({ body: searchParamsRt, }), options: { tags: ['access:apm'], disableTelemetry: true }, - handler: async (resources) => { + handler: async ( + resources + ): Promise< + | import('./../../../../../../../src/core/types/elasticsearch/search').SearchHit< + import('./../../../../common/agent_configuration/configuration_types').AgentConfiguration, + undefined, + undefined + > + | null + > => { const { params, logger } = resources; const { @@ -242,7 +260,7 @@ const agentConfigurationSearchRoute = createApmServerRoute({ const listAgentConfigurationServicesRoute = createApmServerRoute({ endpoint: 'GET /api/apm/settings/agent-configuration/services', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ serviceNames: string[] }> => { const setup = await setupRequest(resources); const { start, end } = resources.params.query; const searchAggregatedTransactions = await getSearchAggregatedTransactions({ @@ -272,7 +290,11 @@ const listAgentConfigurationEnvironmentsRoute = createApmServerRoute({ query: t.partial({ serviceName: t.string }), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + environments: Array<{ name: string; alreadyConfigured: boolean }>; + }> => { const setup = await setupRequest(resources); const { context, params } = resources; @@ -305,7 +327,7 @@ const agentConfigurationAgentNameRoute = createApmServerRoute({ query: t.type({ serviceName: t.string }), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ agentName: string | undefined }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.query; @@ -314,13 +336,13 @@ const agentConfigurationAgentNameRoute = createApmServerRoute({ }, }); -export const agentConfigurationRouteRepository = - createApmServerRouteRepository() - .add(agentConfigurationRoute) - .add(getSingleAgentConfigurationRoute) - .add(deleteAgentConfigurationRoute) - .add(createOrUpdateAgentConfigurationRoute) - .add(agentConfigurationSearchRoute) - .add(listAgentConfigurationServicesRoute) - .add(listAgentConfigurationEnvironmentsRoute) - .add(agentConfigurationAgentNameRoute); +export const agentConfigurationRouteRepository = { + ...agentConfigurationRoute, + ...getSingleAgentConfigurationRoute, + ...deleteAgentConfigurationRoute, + ...createOrUpdateAgentConfigurationRoute, + ...agentConfigurationSearchRoute, + ...listAgentConfigurationServicesRoute, + ...listAgentConfigurationEnvironmentsRoute, + ...agentConfigurationAgentNameRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts b/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts index 35089acf38688..44dac0d9bc4a0 100644 --- a/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts +++ b/x-pack/plugins/apm/server/routes/settings/anomaly_detection/route.ts @@ -16,7 +16,6 @@ import { setupRequest } from '../../../lib/helpers/setup_request'; import { getAllEnvironments } from '../../environments/get_all_environments'; import { getSearchAggregatedTransactions } from '../../../lib/helpers/transactions'; import { notifyFeatureUsage } from '../../../feature'; -import { createApmServerRouteRepository } from '../../apm_routes/create_apm_server_route_repository'; import { updateToV3 } from './update_to_v3'; import { environmentStringRt } from '../../../../common/environment_rt'; import { getMlJobsWithAPMGroup } from '../../../lib/anomaly_detection/get_ml_jobs_with_apm_group'; @@ -27,7 +26,14 @@ const anomalyDetectionJobsRoute = createApmServerRoute({ options: { tags: ['access:apm', 'access:ml:canGetJobs'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + jobs: Array< + import('./../../../../common/anomaly_detection/apm_ml_job').ApmMlJob + >; + hasLegacyJobs: boolean; + }> => { const setup = await setupRequest(resources); const { context } = resources; @@ -59,7 +65,7 @@ const createAnomalyDetectionJobsRoute = createApmServerRoute({ environments: t.array(environmentStringRt), }), }), - handler: async (resources) => { + handler: async (resources): Promise<{ jobCreated: true }> => { const { params, context, logger } = resources; const { environments } = params.body; @@ -84,7 +90,7 @@ const createAnomalyDetectionJobsRoute = createApmServerRoute({ const anomalyDetectionEnvironmentsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/settings/anomaly-detection/environments', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ environments: string[] }> => { const setup = await setupRequest(resources); const searchAggregatedTransactions = await getSearchAggregatedTransactions({ @@ -117,7 +123,7 @@ const anomalyDetectionUpdateToV3Route = createApmServerRoute({ 'access:ml:canCloseJob', ], }, - handler: async (resources) => { + handler: async (resources): Promise<{ update: boolean }> => { const [setup, esClient] = await Promise.all([ setupRequest(resources), resources.core @@ -133,8 +139,9 @@ const anomalyDetectionUpdateToV3Route = createApmServerRoute({ }, }); -export const anomalyDetectionRouteRepository = createApmServerRouteRepository() - .add(anomalyDetectionJobsRoute) - .add(createAnomalyDetectionJobsRoute) - .add(anomalyDetectionEnvironmentsRoute) - .add(anomalyDetectionUpdateToV3Route); +export const anomalyDetectionRouteRepository = { + ...anomalyDetectionJobsRoute, + ...createAnomalyDetectionJobsRoute, + ...anomalyDetectionEnvironmentsRoute, + ...anomalyDetectionUpdateToV3Route, +}; diff --git a/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts index 485ff8af88843..f0d19050954d9 100644 --- a/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts +++ b/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts @@ -6,7 +6,6 @@ */ import * as t from 'io-ts'; -import { createApmServerRouteRepository } from '../../apm_routes/create_apm_server_route_repository'; import { createApmServerRoute } from '../../apm_routes/create_apm_server_route'; import { getApmIndices, getApmIndexSettings } from './get_apm_indices'; import { saveApmIndices } from './save_apm_indices'; @@ -16,7 +15,22 @@ import { APMConfig } from '../../../'; const apmIndexSettingsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/settings/apm-index-settings', options: { tags: ['access:apm'] }, - handler: async ({ config, context }) => { + handler: async ({ + config, + context, + }): Promise<{ + apmIndexSettings: Array<{ + configurationName: + | 'transaction' + | 'span' + | 'error' + | 'metric' + | 'sourcemap' + | 'onboarding'; + defaultValue: string; + savedValue: string | undefined; + }>; + }> => { const apmIndexSettings = await getApmIndexSettings({ config, context }); return { apmIndexSettings }; }, @@ -26,7 +40,11 @@ const apmIndexSettingsRoute = createApmServerRoute({ const apmIndicesRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/settings/apm-indices', options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise< + import('./../../../../../observability/common/typings').ApmIndicesConfig + > => { const { context, config } = resources; return await getApmIndices({ savedObjectsClient: context.core.savedObjects.client, @@ -55,7 +73,11 @@ const saveApmIndicesRoute = createApmServerRoute({ metric: t.string, } as SaveApmIndicesBodySchema), }), - handler: async (resources) => { + handler: async ( + resources + ): Promise< + import('./../../../../../../../src/core/types/saved_objects').SavedObject<{}> + > => { const { params, context } = resources; const { body } = params; const savedObjectsClient = context.core.savedObjects.client; @@ -63,7 +85,8 @@ const saveApmIndicesRoute = createApmServerRoute({ }, }); -export const apmIndicesRouteRepository = createApmServerRouteRepository() - .add(apmIndexSettingsRoute) - .add(apmIndicesRoute) - .add(saveApmIndicesRoute); +export const apmIndicesRouteRepository = { + ...apmIndexSettingsRoute, + ...apmIndicesRoute, + ...saveApmIndicesRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts b/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts index 42232581f1af3..ca111a50ce924 100644 --- a/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts +++ b/x-pack/plugins/apm/server/routes/settings/custom_link/route.ts @@ -19,7 +19,6 @@ import { deleteCustomLink } from './delete_custom_link'; import { getTransaction } from './get_transaction'; import { listCustomLinks } from './list_custom_links'; import { createApmServerRoute } from '../../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../../apm_routes/create_apm_server_route_repository'; const customLinkTransactionRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/settings/custom_links/transaction', @@ -27,7 +26,11 @@ const customLinkTransactionRoute = createApmServerRoute({ params: t.partial({ query: filterOptionsRt, }), - handler: async (resources) => { + handler: async ( + resources + ): Promise< + import('./../../../../typings/es_schemas/ui/transaction').Transaction + > => { const setup = await setupRequest(resources); const { params } = resources; const { query } = params; @@ -43,7 +46,13 @@ const listCustomLinksRoute = createApmServerRoute({ params: t.partial({ query: filterOptionsRt, }), - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + customLinks: Array< + import('./../../../../common/custom_link/custom_link_types').CustomLink + >; + }> => { const { context, params } = resources; if (!isActiveGoldLicense(context.licensing.license)) { throw Boom.forbidden(INVALID_LICENSE); @@ -65,7 +74,7 @@ const createCustomLinkRoute = createApmServerRoute({ body: payloadRt, }), options: { tags: ['access:apm', 'access:apm_write'] }, - handler: async (resources) => { + handler: async (resources): Promise => { const { context, params } = resources; if (!isActiveGoldLicense(context.licensing.license)) { throw Boom.forbidden(INVALID_LICENSE); @@ -93,7 +102,7 @@ const updateCustomLinkRoute = createApmServerRoute({ options: { tags: ['access:apm', 'access:apm_write'], }, - handler: async (resources) => { + handler: async (resources): Promise => { const { params, context } = resources; if (!isActiveGoldLicense(context.licensing.license)) { @@ -122,7 +131,7 @@ const deleteCustomLinkRoute = createApmServerRoute({ options: { tags: ['access:apm', 'access:apm_write'], }, - handler: async (resources) => { + handler: async (resources): Promise<{ result: string }> => { const { context, params } = resources; if (!isActiveGoldLicense(context.licensing.license)) { @@ -138,9 +147,10 @@ const deleteCustomLinkRoute = createApmServerRoute({ }, }); -export const customLinkRouteRepository = createApmServerRouteRepository() - .add(customLinkTransactionRoute) - .add(listCustomLinksRoute) - .add(createCustomLinkRoute) - .add(updateCustomLinkRoute) - .add(deleteCustomLinkRoute); +export const customLinkRouteRepository = { + ...customLinkTransactionRoute, + ...listCustomLinksRoute, + ...createCustomLinkRoute, + ...updateCustomLinkRoute, + ...deleteCustomLinkRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/source_maps/route.ts b/x-pack/plugins/apm/server/routes/source_maps/route.ts index a60c59c03589d..6e172e8ed3663 100644 --- a/x-pack/plugins/apm/server/routes/source_maps/route.ts +++ b/x-pack/plugins/apm/server/routes/source_maps/route.ts @@ -14,11 +14,12 @@ import { listArtifacts, updateSourceMapsOnFleetPolicies, getCleanedBundleFilePath, + ArtifactSourceMap, } from '../fleet/source_maps'; import { getInternalSavedObjectsClient } from '../../lib/helpers/get_internal_saved_objects_client'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { stringFromBufferRt } from '../../utils/string_from_buffer_rt'; +import { Artifact } from '../../../../fleet/server'; export const sourceMapRt = t.intersection([ t.type({ @@ -39,7 +40,9 @@ export type SourceMap = t.TypeOf; const listSourceMapRoute = createApmServerRoute({ endpoint: 'GET /api/apm/sourcemaps', options: { tags: ['access:apm'] }, - handler: async ({ plugins }) => { + async handler({ + plugins, + }): Promise<{ artifacts: ArtifactSourceMap[] } | undefined> { try { const fleetPluginStart = await plugins.fleet?.start(); if (fleetPluginStart) { @@ -72,7 +75,7 @@ const uploadSourceMapRoute = createApmServerRoute({ .pipe(sourceMapRt), }), }), - handler: async ({ params, plugins, core }) => { + handler: async ({ params, plugins, core }): Promise => { const { service_name: serviceName, service_version: serviceVersion, @@ -122,7 +125,7 @@ const deleteSourceMapRoute = createApmServerRoute({ id: t.string, }), }), - handler: async ({ params, plugins, core }) => { + handler: async ({ params, plugins, core }): Promise => { const fleetPluginStart = await plugins.fleet?.start(); const { id } = params.path; const coreStart = await core.start(); @@ -148,7 +151,8 @@ const deleteSourceMapRoute = createApmServerRoute({ }, }); -export const sourceMapsRouteRepository = createApmServerRouteRepository() - .add(listSourceMapRoute) - .add(uploadSourceMapRoute) - .add(deleteSourceMapRoute); +export const sourceMapsRouteRepository = { + ...listSourceMapRoute, + ...uploadSourceMapRoute, + ...deleteSourceMapRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/suggestions/route.ts b/x-pack/plugins/apm/server/routes/suggestions/route.ts index de3636c2c1502..5db74e64c9a2e 100644 --- a/x-pack/plugins/apm/server/routes/suggestions/route.ts +++ b/x-pack/plugins/apm/server/routes/suggestions/route.ts @@ -11,7 +11,6 @@ import { getSuggestions } from '../suggestions/get_suggestions'; import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; import { setupRequest } from '../../lib/helpers/setup_request'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; const suggestionsRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/suggestions', @@ -19,7 +18,7 @@ const suggestionsRoute = createApmServerRoute({ query: t.type({ field: t.string, string: t.string }), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async (resources): Promise<{ terms: string[] }> => { const setup = await setupRequest(resources); const { context, params } = resources; const { field, string } = params.query; @@ -43,5 +42,4 @@ const suggestionsRoute = createApmServerRoute({ }, }); -export const suggestionsRouteRepository = - createApmServerRouteRepository().add(suggestionsRoute); +export const suggestionsRouteRepository = suggestionsRoute; diff --git a/x-pack/plugins/apm/server/routes/traces/route.ts b/x-pack/plugins/apm/server/routes/traces/route.ts index 33f78b7bca11a..05aa27f27196d 100644 --- a/x-pack/plugins/apm/server/routes/traces/route.ts +++ b/x-pack/plugins/apm/server/routes/traces/route.ts @@ -13,7 +13,6 @@ import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; import { environmentRt, kueryRt, rangeRt } from '../default_api_types'; import { getSearchAggregatedTransactions } from '../../lib/helpers/transactions'; import { getRootTransactionByTraceId } from '../transactions/get_transaction_by_trace'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { getTransaction } from '../transactions/get_transaction'; const tracesRoute = createApmServerRoute({ @@ -22,7 +21,20 @@ const tracesRoute = createApmServerRoute({ query: t.intersection([environmentRt, kueryRt, rangeRt]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + items: Array<{ + key: import('./get_top_traces_primary_stats').BucketKey; + serviceName: string; + transactionName: string; + averageResponseTime: number | null; + transactionsPerMinute: number; + transactionType: string; + impact: number; + agentName: import('./../../../typings/es_schemas/ui/fields/agent').AgentName; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { environment, kuery, start, end } = params.query; @@ -53,7 +65,18 @@ const tracesByIdRoute = createApmServerRoute({ query: rangeRt, }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + exceedsMax: boolean; + traceDocs: Array< + | import('./../../../typings/es_schemas/ui/transaction').Transaction + | import('./../../../typings/es_schemas/ui/span').Span + >; + errorDocs: Array< + import('./../../../typings/es_schemas/ui/apm_error').APMError + >; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { traceId } = params.path; @@ -71,7 +94,11 @@ const rootTransactionByTraceIdRoute = createApmServerRoute({ }), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + transaction: import('./../../../typings/es_schemas/ui/transaction').Transaction; + }> => { const { params } = resources; const { traceId } = params.path; const setup = await setupRequest(resources); @@ -87,7 +114,11 @@ const transactionByIdRoute = createApmServerRoute({ }), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + transaction: import('./../../../typings/es_schemas/ui/transaction').Transaction; + }> => { const { params } = resources; const { transactionId } = params.path; const setup = await setupRequest(resources); @@ -97,8 +128,9 @@ const transactionByIdRoute = createApmServerRoute({ }, }); -export const traceRouteRepository = createApmServerRouteRepository() - .add(tracesByIdRoute) - .add(tracesRoute) - .add(rootTransactionByTraceIdRoute) - .add(transactionByIdRoute); +export const traceRouteRepository = { + ...tracesByIdRoute, + ...tracesRoute, + ...rootTransactionByTraceIdRoute, + ...transactionByIdRoute, +}; diff --git a/x-pack/plugins/apm/server/routes/transactions/route.ts b/x-pack/plugins/apm/server/routes/transactions/route.ts index 49c50f5a9100d..e22e521c699ec 100644 --- a/x-pack/plugins/apm/server/routes/transactions/route.ts +++ b/x-pack/plugins/apm/server/routes/transactions/route.ts @@ -20,7 +20,6 @@ import { getTransactionTraceSamples } from './trace_samples'; import { getLatencyPeriods } from './get_latency_charts'; import { getFailedTransactionRatePeriods } from './get_failed_transaction_rate_periods'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; -import { createApmServerRouteRepository } from '../apm_routes/create_apm_server_route_repository'; import { comparisonRangeRt, environmentRt, @@ -46,7 +45,20 @@ const transactionGroupsMainStatisticsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + transactionGroups: Array<{ + transactionType: string; + name: string; + latency: number | null; + throughput: number; + errorRate: number; + impact: number; + }>; + isAggregationAccurate: boolean; + bucketSize: number; + }> => { const { params } = resources; const setup = await setupRequest(resources); const { @@ -103,7 +115,33 @@ const transactionGroupsDetailedStatisticsRoute = createApmServerRoute({ options: { tags: ['access:apm'], }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: import('./../../../../../../node_modules/@types/lodash/ts3.1/index').Dictionary<{ + transactionName: string; + latency: Array; + throughput: Array; + errorRate: Array; + impact: number; + }>; + previousPeriod: import('./../../../../../../node_modules/@types/lodash/ts3.1/index').Dictionary<{ + errorRate: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + throughput: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + latency: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + transactionName: string; + impact: number; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; @@ -165,7 +203,29 @@ const transactionLatencyChartsRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: { + overallAvgDuration: number | null; + latencyTimeseries: Array<{ x: number; y: number | null }>; + }; + previousPeriod: + | { + latencyTimeseries: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + overallAvgDuration: number | null; + } + | { + latencyTimeseries: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + overallAvgDuration: null; + }; + }> => { const setup = await setupRequest(resources); const { params, logger } = resources; @@ -240,7 +300,11 @@ const transactionTraceSamplesRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + traceSamples: Array<{ transactionId: string; traceId: string }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; const { serviceName } = params.path; @@ -290,7 +354,18 @@ const transactionChartsBreakdownRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + timeseries: Array<{ + title: string; + color: string; + type: string; + data: Array<{ x: number; y: number | null }>; + hideLegend: boolean; + legendValue: string; + }>; + }> => { const setup = await setupRequest(resources); const { params } = resources; @@ -325,7 +400,29 @@ const transactionChartsErrorRateRoute = createApmServerRoute({ ]), }), options: { tags: ['access:apm'] }, - handler: async (resources) => { + handler: async ( + resources + ): Promise<{ + currentPeriod: { + timeseries: Array; + average: number | null; + }; + previousPeriod: + | { + timeseries: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + average: number | null; + } + | { + timeseries: Array<{ + x: number; + y: import('./../../../typings/common').Maybe; + }>; + average: null; + }; + }> => { const setup = await setupRequest(resources); const { params } = resources; @@ -364,10 +461,11 @@ const transactionChartsErrorRateRoute = createApmServerRoute({ }, }); -export const transactionRouteRepository = createApmServerRouteRepository() - .add(transactionGroupsMainStatisticsRoute) - .add(transactionGroupsDetailedStatisticsRoute) - .add(transactionLatencyChartsRoute) - .add(transactionTraceSamplesRoute) - .add(transactionChartsBreakdownRoute) - .add(transactionChartsErrorRateRoute); +export const transactionRouteRepository = { + ...transactionGroupsMainStatisticsRoute, + ...transactionGroupsDetailedStatisticsRoute, + ...transactionLatencyChartsRoute, + ...transactionTraceSamplesRoute, + ...transactionChartsBreakdownRoute, + ...transactionChartsErrorRateRoute, +}; diff --git a/x-pack/plugins/observability/public/pages/alerts/containers/alerts_page/alerts_page.tsx b/x-pack/plugins/observability/public/pages/alerts/containers/alerts_page/alerts_page.tsx index 93a01f7e51231..dc7eab6b0ca40 100644 --- a/x-pack/plugins/observability/public/pages/alerts/containers/alerts_page/alerts_page.tsx +++ b/x-pack/plugins/observability/public/pages/alerts/containers/alerts_page/alerts_page.tsx @@ -140,9 +140,8 @@ function AlertsPage() { const manageRulesHref = prepend('/app/management/insightsAndAlerting/triggersActions/alerts'); const { data: indexNames = NO_INDEX_NAMES } = useFetcher(({ signal }) => { - return callObservabilityApi({ + return callObservabilityApi('GET /api/observability/rules/alerts/dynamic_index_pattern', { signal, - endpoint: 'GET /api/observability/rules/alerts/dynamic_index_pattern', params: { query: { namespace: 'default', diff --git a/x-pack/plugins/observability/public/services/call_observability_api/index.ts b/x-pack/plugins/observability/public/services/call_observability_api/index.ts index 7b1b9d222b36e..9cb17373bfe48 100644 --- a/x-pack/plugins/observability/public/services/call_observability_api/index.ts +++ b/x-pack/plugins/observability/public/services/call_observability_api/index.ts @@ -16,8 +16,8 @@ export let callObservabilityApi: ObservabilityClient = () => { }; export function createCallObservabilityApi(http: HttpSetup) { - const client: AbstractObservabilityClient = (options) => { - const { params: { path, body, query } = {}, endpoint, ...rest } = options; + const client: AbstractObservabilityClient = (endpoint, options) => { + const { params: { path, body, query } = {}, ...rest } = options; const { method, pathname } = formatRequest(endpoint, path) as ReturnType< typeof formatRequestType diff --git a/x-pack/plugins/observability/server/routes/create_observability_server_route_repository.ts b/x-pack/plugins/observability/server/routes/create_observability_server_route_repository.ts deleted file mode 100644 index dab1ecdef7cf8..0000000000000 --- a/x-pack/plugins/observability/server/routes/create_observability_server_route_repository.ts +++ /dev/null @@ -1,15 +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 { createServerRouteRepository } from '@kbn/server-route-repository'; -import { ObservabilityRouteHandlerResources, ObservabilityRouteCreateOptions } from './types'; - -export const createObservabilityServerRouteRepository = () => { - return createServerRouteRepository< - ObservabilityRouteHandlerResources, - ObservabilityRouteCreateOptions - >(); -}; diff --git a/x-pack/plugins/observability/server/routes/register_routes.ts b/x-pack/plugins/observability/server/routes/register_routes.ts index 66d8940b615b3..15651e9e73986 100644 --- a/x-pack/plugins/observability/server/routes/register_routes.ts +++ b/x-pack/plugins/observability/server/routes/register_routes.ts @@ -31,7 +31,7 @@ export function registerRoutes({ logger: Logger; ruleDataService: RuleDataPluginService; }) { - const routes = repository.getRoutes(); + const routes = Object.values(repository); const router = core.setup.http.createRouter(); diff --git a/x-pack/plugins/observability/server/routes/rules.ts b/x-pack/plugins/observability/server/routes/rules.ts index b4682116f1205..845ac00a70eec 100644 --- a/x-pack/plugins/observability/server/routes/rules.ts +++ b/x-pack/plugins/observability/server/routes/rules.ts @@ -8,7 +8,6 @@ import * as t from 'io-ts'; import { Dataset } from '../../../rule_registry/server'; import { createObservabilityServerRoute } from './create_observability_server_route'; -import { createObservabilityServerRouteRepository } from './create_observability_server_route_repository'; const alertsDynamicIndexPatternRoute = createObservabilityServerRoute({ endpoint: 'GET /api/observability/rules/alerts/dynamic_index_pattern', @@ -39,6 +38,4 @@ const alertsDynamicIndexPatternRoute = createObservabilityServerRoute({ }, }); -export const rulesRouteRepository = createObservabilityServerRouteRepository().add( - alertsDynamicIndexPatternRoute -); +export const rulesRouteRepository = alertsDynamicIndexPatternRoute; diff --git a/x-pack/plugins/observability/server/routes/types.ts b/x-pack/plugins/observability/server/routes/types.ts index b316b1fffc770..adb29bcd4f8cb 100644 --- a/x-pack/plugins/observability/server/routes/types.ts +++ b/x-pack/plugins/observability/server/routes/types.ts @@ -4,13 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import * as t from 'io-ts'; -import type { - EndpointOf, - ReturnOf, - ServerRoute, - ServerRouteRepository, -} from '@kbn/server-route-repository'; +import type { EndpointOf, ReturnOf, ServerRouteRepository } from '@kbn/server-route-repository'; import { CoreSetup, CoreStart, KibanaRequest, Logger } from 'kibana/server'; import { RuleDataPluginService } from '../../../rule_registry/server'; @@ -36,20 +30,7 @@ export interface ObservabilityRouteCreateOptions { }; } -export type AbstractObservabilityServerRouteRepository = ServerRouteRepository< - ObservabilityRouteHandlerResources, - ObservabilityRouteCreateOptions, - Record< - string, - ServerRoute< - string, - t.Mixed | undefined, - ObservabilityRouteHandlerResources, - any, - ObservabilityRouteCreateOptions - > - > ->; +export type AbstractObservabilityServerRouteRepository = ServerRouteRepository; export type ObservabilityAPIReturnType< TEndpoint extends EndpointOf diff --git a/yarn.lock b/yarn.lock index 85260ad6a46e3..5bd438ba1a180 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4948,12 +4948,12 @@ resolved "https://registry.yarnpkg.com/@tootallnate/once/-/once-1.1.2.tgz#ccb91445360179a04e7fe6aff78c00ffc1eeaf82" integrity sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw== -"@ts-morph/common@~0.10.1": - version "0.10.1" - resolved "https://registry.yarnpkg.com/@ts-morph/common/-/common-0.10.1.tgz#be15b9ab13a32bbc1f6a6bd7dc056b2247b272eb" - integrity sha512-rKN/VtZUUlW4M+6vjLFSaFc1Z9sK+1hh0832ucPtPkXqOw/mSWE80Lau4z2zTPNTqtxAjfZbvKpQcEwJy0KIEg== +"@ts-morph/common@~0.12.2": + version "0.12.2" + resolved "https://registry.yarnpkg.com/@ts-morph/common/-/common-0.12.2.tgz#61d07a47d622d231e833c44471ab306faaa41aed" + integrity sha512-m5KjptpIf1K0t0QL38uE+ol1n+aNn9MgRq++G3Zym1FlqfN+rThsXlp3cAgib14pIeXF7jk3UtJQOviwawFyYg== dependencies: - fast-glob "^3.2.5" + fast-glob "^3.2.7" minimatch "^3.0.4" mkdirp "^1.0.4" path-browserify "^1.0.1" @@ -10023,10 +10023,12 @@ coa@^2.0.2: chalk "^2.4.1" q "^1.1.2" -code-block-writer@^10.1.1: - version "10.1.1" - resolved "https://registry.yarnpkg.com/code-block-writer/-/code-block-writer-10.1.1.tgz#ad5684ed4bfb2b0783c8b131281ae84ee640a42f" - integrity sha512-67ueh2IRGst/51p0n6FvPrnRjAGHY5F8xdjkgrYE7DDzpJe6qA07RYQ9VcoUeo5ATOjSOiWpSL3SWBRRbempMw== +code-block-writer@^11.0.0: + version "11.0.0" + resolved "https://registry.yarnpkg.com/code-block-writer/-/code-block-writer-11.0.0.tgz#5956fb186617f6740e2c3257757fea79315dd7d4" + integrity sha512-GEqWvEWWsOvER+g9keO4ohFoD3ymwyCnqY3hoTr7GZipYFwEhMHJw+TtV0rfgRhNImM6QWZGO2XYjlJVyYT62w== + dependencies: + tslib "2.3.1" code-point-at@^1.0.0: version "1.1.0" @@ -13827,7 +13829,7 @@ fast-glob@2.2.7, fast-glob@^2.2.6: merge2 "^1.2.3" micromatch "^3.1.10" -fast-glob@3.2.7, fast-glob@^3.0.3, fast-glob@^3.1.1, fast-glob@^3.2.2, fast-glob@^3.2.4, fast-glob@^3.2.5: +fast-glob@3.2.7, fast-glob@^3.0.3, fast-glob@^3.1.1, fast-glob@^3.2.2, fast-glob@^3.2.4: version "3.2.7" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.7.tgz#fd6cb7a2d7e9aa7a7846111e85a196d6b2f766a1" integrity sha512-rYGMRwip6lUMvYD3BTScMwT1HtAs2d71SMv66Vrxs0IekGZEjhM0pcMfjQPnknBt2zeCwQMEupiN02ZP4DiT1Q== @@ -13838,6 +13840,17 @@ fast-glob@3.2.7, fast-glob@^3.0.3, fast-glob@^3.1.1, fast-glob@^3.2.2, fast-glob merge2 "^1.3.0" micromatch "^4.0.4" +fast-glob@^3.2.7: + version "3.2.11" + resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.11.tgz#a1172ad95ceb8a16e20caa5c5e56480e5129c1d9" + integrity sha512-xrO3+1bxSo3ZVHAnqzyuewYT6aMFHRAd4Kcs92MAonjwQZLsK9d0SF1IyQ3k5PoirxTW0Oe/RqFgMQ6TcNE5Ew== + dependencies: + "@nodelib/fs.stat" "^2.0.2" + "@nodelib/fs.walk" "^1.2.3" + glob-parent "^5.1.2" + merge2 "^1.3.0" + micromatch "^4.0.4" + fast-json-parse@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/fast-json-parse/-/fast-json-parse-1.0.3.tgz#43e5c61ee4efa9265633046b770fb682a7577c4d" @@ -27673,13 +27686,13 @@ ts-loader@^7.0.5: micromatch "^4.0.0" semver "^6.0.0" -ts-morph@^11.0.0: - version "11.0.3" - resolved "https://registry.yarnpkg.com/ts-morph/-/ts-morph-11.0.3.tgz#01a92b3c2b5a48ccdf318ec90864229b8061d056" - integrity sha512-ymuPkndv9rzqTLiHWMkVrFXWcN4nBiBGhRP/kTC9F5amAAl7BNLfyrsTzMD1o9A0zishKoF1KQT/0yyFhJnPgA== +ts-morph@^13.0.2: + version "13.0.2" + resolved "https://registry.yarnpkg.com/ts-morph/-/ts-morph-13.0.2.tgz#55546023493ef82389d9e4f28848a556c784bac4" + integrity sha512-SjeeHaRf/mFsNeR3KTJnx39JyEOzT4e+DX28gQx5zjzEOuFs2eGrqeN2PLKs/+AibSxPmzV7RD8nJVKmFJqtLA== dependencies: - "@ts-morph/common" "~0.10.1" - code-block-writer "^10.1.1" + "@ts-morph/common" "~0.12.2" + code-block-writer "^11.0.0" ts-node@^10.2.1: version "10.2.1" @@ -27726,6 +27739,11 @@ tsd@^0.13.1: read-pkg-up "^7.0.0" update-notifier "^4.1.0" +tslib@2.3.1, tslib@^2.3.0, tslib@~2.3.1: + version "2.3.1" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" + integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== + tslib@^1, tslib@^1.0.0, tslib@^1.10.0, tslib@^1.8.1, tslib@^1.9.0, tslib@^1.9.3: version "1.13.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.13.0.tgz#c881e13cc7015894ed914862d276436fa9a47043" @@ -27736,11 +27754,6 @@ tslib@^2.0.0, tslib@^2.0.1, tslib@^2.2.0: resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.2.0.tgz#fb2c475977e35e241311ede2693cee1ec6698f5c" integrity sha512-gS9GVHRU+RGn5KQM2rllAlR3dU6m7AcpJKdtH8gFvQiC4Otgk98XnmMU+nZenHt/+VhnBPWwgrJsyrdcw6i23w== -tslib@^2.3.0, tslib@~2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" - integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== - tslib@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.1.0.tgz#da60860f1c2ecaa5703ab7d39bc05b6bf988b97a"