diff --git a/oas_docs/output/kibana.yaml b/oas_docs/output/kibana.yaml index 2efadba213d82..915d0e5208f23 100644 --- a/oas_docs/output/kibana.yaml +++ b/oas_docs/output/kibana.yaml @@ -23086,7 +23086,7 @@ paths: - $ref: '#/components/parameters/SLOs_space_id' - $ref: '#/components/parameters/SLOs_slo_id' responses: - '204': + '200': content: application/json; Elastic-Api-Version=2023-10-31: schema: @@ -23130,7 +23130,7 @@ paths: - $ref: '#/components/parameters/SLOs_space_id' - $ref: '#/components/parameters/SLOs_slo_id' responses: - '200': + '204': description: Successful request '400': content: diff --git a/x-pack/plugins/observability_solution/observability/server/errors/errors.ts b/x-pack/plugins/observability_solution/observability/server/errors/errors.ts deleted file mode 100644 index eaec36e66d08b..0000000000000 --- a/x-pack/plugins/observability_solution/observability/server/errors/errors.ts +++ /dev/null @@ -1,26 +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. - */ - -/* eslint-disable max-classes-per-file */ - -export class ObservabilityError extends Error { - constructor(message?: string) { - super(message); - this.name = this.constructor.name; - } -} - -export class SLONotFound extends ObservabilityError {} -export class SLOIdConflict extends ObservabilityError {} - -export class InvalidQueryError extends ObservabilityError {} -export class InternalQueryError extends ObservabilityError {} -export class NotSupportedError extends ObservabilityError {} -export class IllegalArgumentError extends ObservabilityError {} -export class InvalidTransformError extends ObservabilityError {} - -export class SecurityException extends ObservabilityError {} diff --git a/x-pack/plugins/observability_solution/observability/server/errors/handler.ts b/x-pack/plugins/observability_solution/observability/server/errors/handler.ts deleted file mode 100644 index c10f1d98c083e..0000000000000 --- a/x-pack/plugins/observability_solution/observability/server/errors/handler.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ObservabilityError, SecurityException, SLOIdConflict, SLONotFound } from './errors'; - -export function getHTTPResponseCode(error: ObservabilityError): number { - if (error instanceof SLONotFound) { - return 404; - } - - if (error instanceof SLOIdConflict) { - return 409; - } - - if (error instanceof SecurityException) { - return 403; - } - - return 400; -} diff --git a/x-pack/plugins/observability_solution/observability/server/errors/index.ts b/x-pack/plugins/observability_solution/observability/server/errors/index.ts deleted file mode 100644 index e466d5b8ae4a1..0000000000000 --- a/x-pack/plugins/observability_solution/observability/server/errors/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export * from './errors'; -export * from './handler'; diff --git a/x-pack/plugins/observability_solution/observability/server/routes/register_routes.ts b/x-pack/plugins/observability_solution/observability/server/routes/register_routes.ts index b885050eb64c7..5599039a5ce67 100644 --- a/x-pack/plugins/observability_solution/observability/server/routes/register_routes.ts +++ b/x-pack/plugins/observability_solution/observability/server/routes/register_routes.ts @@ -8,20 +8,19 @@ import { errors } from '@elastic/elasticsearch'; import Boom from '@hapi/boom'; import { RulesClientApi } from '@kbn/alerting-plugin/server/types'; import { CoreSetup, KibanaRequest, Logger, RouteRegistrar } from '@kbn/core/server'; +import { DataViewsServerPluginStart } from '@kbn/data-views-plugin/server'; import { RuleDataPluginService } from '@kbn/rule-registry-plugin/server'; import { IoTsParamsObject, decodeRequestParams, - stripNullishRequestParameters, parseEndpoint, passThroughValidationObject, + stripNullishRequestParameters, } from '@kbn/server-route-repository'; import { SpacesPluginStart } from '@kbn/spaces-plugin/server'; import axios from 'axios'; import * as t from 'io-ts'; -import { DataViewsServerPluginStart } from '@kbn/data-views-plugin/server'; import { ObservabilityConfig } from '..'; -import { getHTTPResponseCode, ObservabilityError } from '../errors'; import { AlertDetailsContextualInsightsService } from '../services'; import { ObservabilityRequestHandlerContext } from '../types'; import { AbstractObservabilityServerRouteRepository } from './types'; @@ -88,16 +87,6 @@ export function registerRoutes({ config, repository, core, logger, dependencies return response.ok({ body: data }); } catch (error) { - if (error instanceof ObservabilityError) { - logger.error(error.message); - return response.customError({ - statusCode: getHTTPResponseCode(error), - body: { - message: error.message, - }, - }); - } - if (axios.isAxiosError(error)) { logger.error(error); return response.customError({ diff --git a/x-pack/plugins/observability_solution/observability_logs_explorer/public/types.ts b/x-pack/plugins/observability_solution/observability_logs_explorer/public/types.ts index b1bbfb1b504a1..7106395d47b27 100644 --- a/x-pack/plugins/observability_solution/observability_logs_explorer/public/types.ts +++ b/x-pack/plugins/observability_solution/observability_logs_explorer/public/types.ts @@ -25,7 +25,7 @@ import { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/publi import { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; import { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public'; import { LensPublicStart } from '@kbn/lens-plugin/public'; -import { SloPublicStart } from '@kbn/slo-plugin/public'; +import { SLOPublicStart } from '@kbn/slo-plugin/public'; import { LogsDataAccessPluginStart } from '@kbn/logs-data-access-plugin/public'; import { ObservabilityLogsExplorerLocators, @@ -53,7 +53,7 @@ export interface ObservabilityLogsExplorerStartDeps { logsDataAccess: LogsDataAccessPluginStart; observabilityAIAssistant?: ObservabilityAIAssistantPublicStart; observabilityShared: ObservabilitySharedPluginStart; - slo: SloPublicStart; + slo: SLOPublicStart; serverless?: ServerlessPluginStart; triggersActionsUi?: TriggersAndActionsUIPublicPluginStart; unifiedSearch?: UnifiedSearchPublicPluginStart; diff --git a/x-pack/plugins/observability_solution/slo/common/config.ts b/x-pack/plugins/observability_solution/slo/common/config.ts index 973fc562d743b..86fa7b74c2a1f 100644 --- a/x-pack/plugins/observability_solution/slo/common/config.ts +++ b/x-pack/plugins/observability_solution/slo/common/config.ts @@ -25,5 +25,5 @@ export const config = { experimental: true, }, }; -export type SloConfig = TypeOf; -export type ExperimentalFeatures = SloConfig['experimental']; +export type SLOConfig = TypeOf; +export type ExperimentalFeatures = SLOConfig['experimental']; diff --git a/x-pack/plugins/observability_solution/slo/docs/openapi/slo/bundled.json b/x-pack/plugins/observability_solution/slo/docs/openapi/slo/bundled.json index b8d3e28ce210a..b4d66229dc495 100644 --- a/x-pack/plugins/observability_solution/slo/docs/openapi/slo/bundled.json +++ b/x-pack/plugins/observability_solution/slo/docs/openapi/slo/bundled.json @@ -559,7 +559,7 @@ } ], "responses": { - "200": { + "204": { "description": "Successful request" }, "400": { @@ -625,7 +625,7 @@ } ], "responses": { - "204": { + "200": { "description": "Successful request", "content": { "application/json": { diff --git a/x-pack/plugins/observability_solution/slo/docs/openapi/slo/bundled.yaml b/x-pack/plugins/observability_solution/slo/docs/openapi/slo/bundled.yaml index dc57f3e4ea4f6..fde29b3602be0 100644 --- a/x-pack/plugins/observability_solution/slo/docs/openapi/slo/bundled.yaml +++ b/x-pack/plugins/observability_solution/slo/docs/openapi/slo/bundled.yaml @@ -341,7 +341,7 @@ paths: - $ref: '#/components/parameters/space_id' - $ref: '#/components/parameters/slo_id' responses: - '200': + '204': description: Successful request '400': description: Bad request @@ -380,7 +380,7 @@ paths: - $ref: '#/components/parameters/space_id' - $ref: '#/components/parameters/slo_id' responses: - '204': + '200': description: Successful request content: application/json: diff --git a/x-pack/plugins/observability_solution/slo/docs/openapi/slo/paths/s@{spaceid}@api@slos@{sloid}@_reset.yaml b/x-pack/plugins/observability_solution/slo/docs/openapi/slo/paths/s@{spaceid}@api@slos@{sloid}@_reset.yaml index e805c1117f5c1..53d9e03e463e6 100644 --- a/x-pack/plugins/observability_solution/slo/docs/openapi/slo/paths/s@{spaceid}@api@slos@{sloid}@_reset.yaml +++ b/x-pack/plugins/observability_solution/slo/docs/openapi/slo/paths/s@{spaceid}@api@slos@{sloid}@_reset.yaml @@ -11,7 +11,7 @@ post: - $ref: ../components/parameters/space_id.yaml - $ref: ../components/parameters/slo_id.yaml responses: - '204': + '200': description: Successful request content: application/json: diff --git a/x-pack/plugins/observability_solution/slo/docs/openapi/slo/paths/s@{spaceid}@api@slos@{sloid}@disable.yaml b/x-pack/plugins/observability_solution/slo/docs/openapi/slo/paths/s@{spaceid}@api@slos@{sloid}@disable.yaml index 704e2f8d24359..0a5194a550aa9 100644 --- a/x-pack/plugins/observability_solution/slo/docs/openapi/slo/paths/s@{spaceid}@api@slos@{sloid}@disable.yaml +++ b/x-pack/plugins/observability_solution/slo/docs/openapi/slo/paths/s@{spaceid}@api@slos@{sloid}@disable.yaml @@ -11,7 +11,7 @@ post: - $ref: ../components/parameters/space_id.yaml - $ref: ../components/parameters/slo_id.yaml responses: - '200': + '204': description: Successful request '400': description: Bad request diff --git a/x-pack/plugins/observability_solution/slo/kibana.jsonc b/x-pack/plugins/observability_solution/slo/kibana.jsonc index dfa28b44f769e..79302b58f8269 100644 --- a/x-pack/plugins/observability_solution/slo/kibana.jsonc +++ b/x-pack/plugins/observability_solution/slo/kibana.jsonc @@ -39,14 +39,14 @@ "presentationUtil", "features", "licensing", - "usageCollection" + "usageCollection", ], "optionalPlugins": [ "cloud", - "spaces", "serverless", "discover", - "observabilityAIAssistant" + "observabilityAIAssistant", + "spaces", ], "requiredBundles": [ "controls", diff --git a/x-pack/plugins/observability_solution/slo/public/application.tsx b/x-pack/plugins/observability_solution/slo/public/application.tsx index b6291b5286148..79160de114cd5 100644 --- a/x-pack/plugins/observability_solution/slo/public/application.tsx +++ b/x-pack/plugins/observability_solution/slo/public/application.tsx @@ -25,26 +25,20 @@ import { ExperimentalFeatures } from '../common/config'; import { PluginContext } from './context/plugin_context'; import { usePluginContext } from './hooks/use_plugin_context'; import { getRoutes } from './routes/routes'; -import { SloPublicPluginsStart } from './types'; +import { SLORepositoryClient, SLOPublicPluginsStart } from './types'; -function App() { - const { isServerless } = usePluginContext(); - - const routes = getRoutes(isServerless); - - return ( - <> - - {Object.keys(routes).map((path) => { - const { handler, exact } = routes[path]; - const Wrapper = () => { - return handler(); - }; - return ; - })} - - - ); +interface Props { + core: CoreStart; + plugins: SLOPublicPluginsStart; + appMountParameters: AppMountParameters; + observabilityRuleTypeRegistry: ObservabilityRuleTypeRegistry; + ObservabilityPageTemplate: React.ComponentType; + usageCollection: UsageCollectionSetup; + isDev?: boolean; + kibanaVersion: string; + isServerless?: boolean; + experimentalFeatures: ExperimentalFeatures; + sloClient: SLORepositoryClient; } export const renderApp = ({ @@ -58,18 +52,8 @@ export const renderApp = ({ isServerless, observabilityRuleTypeRegistry, experimentalFeatures, -}: { - core: CoreStart; - plugins: SloPublicPluginsStart; - appMountParameters: AppMountParameters; - observabilityRuleTypeRegistry: ObservabilityRuleTypeRegistry; - ObservabilityPageTemplate: React.ComponentType; - usageCollection: UsageCollectionSetup; - isDev?: boolean; - kibanaVersion: string; - isServerless?: boolean; - experimentalFeatures: ExperimentalFeatures; -}) => { + sloClient, +}: Props) => { const { element, history, theme$ } = appMountParameters; const isDarkMode = core.theme.getTheme().darkMode; @@ -128,6 +112,7 @@ export const renderApp = ({ ObservabilityPageTemplate, observabilityRuleTypeRegistry, experimentalFeatures, + sloClient, }} > @@ -160,3 +145,21 @@ export const renderApp = ({ ReactDOM.unmountComponentAtNode(element); }; }; + +function App() { + const { isServerless } = usePluginContext(); + + const routes = getRoutes(isServerless); + + return ( + + {Object.keys(routes).map((path) => { + const { handler, exact } = routes[path]; + const Wrapper = () => { + return handler(); + }; + return ; + })} + + ); +} diff --git a/x-pack/plugins/observability_solution/slo/public/components/good_bad_events_chart/good_bad_events_chart.tsx b/x-pack/plugins/observability_solution/slo/public/components/good_bad_events_chart/good_bad_events_chart.tsx index ba3a201402e4f..31245a06b56d0 100644 --- a/x-pack/plugins/observability_solution/slo/public/components/good_bad_events_chart/good_bad_events_chart.tsx +++ b/x-pack/plugins/observability_solution/slo/public/components/good_bad_events_chart/good_bad_events_chart.tsx @@ -24,7 +24,7 @@ import React, { useRef } from 'react'; import { useAnnotations } from '@kbn/observability-plugin/public'; import { TimeBounds } from '../../pages/slo_details/types'; import { getBrushTimeBounds } from '../../utils/slo/duration'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { openInDiscover } from '../../utils/slo/get_discover_link'; export interface Props { diff --git a/x-pack/plugins/observability_solution/slo/public/components/header_menu/header_menu.tsx b/x-pack/plugins/observability_solution/slo/public/components/header_menu/header_menu.tsx index 1269dfb73afdb..bc01ed55acbdf 100644 --- a/x-pack/plugins/observability_solution/slo/public/components/header_menu/header_menu.tsx +++ b/x-pack/plugins/observability_solution/slo/public/components/header_menu/header_menu.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; import { EuiFlexGroup, EuiFlexItem, EuiHeaderLink, EuiHeaderLinks } from '@elastic/eui'; import { HeaderMenuPortal } from '@kbn/observability-shared-plugin/public'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { usePluginContext } from '../../hooks/use_plugin_context'; import { SLOS_BASE_PATH, SLO_SETTINGS_PATH } from '../../../common/locators/paths'; diff --git a/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/alert_details_app_section.tsx b/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/alert_details_app_section.tsx index 44ab29e77e1bd..49c9da82e9511 100644 --- a/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/alert_details_app_section.tsx +++ b/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/alert_details_app_section.tsx @@ -9,7 +9,7 @@ import React, { useEffect } from 'react'; import { EuiFlexGroup, EuiLink } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { AlertDetailsAppSectionProps } from '@kbn/observability-plugin/public'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { useFetchSloDetails } from '../../../../hooks/use_fetch_slo_details'; import { CustomAlertDetailsPanel } from './components/custom_panels/custom_panels'; import { ErrorRatePanel } from './components/error_rate/error_rate_panel'; diff --git a/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/components/custom_panels/custom_kql/log_rate_analysis_panel.tsx b/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/components/custom_panels/custom_kql/log_rate_analysis_panel.tsx index e94b8d5baed55..4a43fb85be824 100644 --- a/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/components/custom_panels/custom_kql/log_rate_analysis_panel.tsx +++ b/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/components/custom_panels/custom_kql/log_rate_analysis_panel.tsx @@ -27,7 +27,7 @@ import type { WindowSchema } from '../../../../../../../typings'; import { TimeRange } from '../../../../../error_rate_chart/use_lens_definition'; import { BurnRateAlert, BurnRateRule } from '../../../types'; import { getActionGroupFromReason } from '../../../utils/alert'; -import { useKibana } from '../../../../../../../utils/kibana_react'; +import { useKibana } from '../../../../../../../hooks/use_kibana'; import { getESQueryForLogRateAnalysis } from './helpers/log_rate_analysis_query'; function getDataTimeRange( timeRange: { gte: string; lte?: string }, diff --git a/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/components/error_rate/error_rate_panel.tsx b/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/components/error_rate/error_rate_panel.tsx index 560f3f463bb46..1c371ea1abd30 100644 --- a/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/components/error_rate/error_rate_panel.tsx +++ b/x-pack/plugins/observability_solution/slo/public/components/slo/burn_rate/alert_details/components/error_rate/error_rate_panel.tsx @@ -23,7 +23,7 @@ import { FormattedMessage } from '@kbn/i18n-react'; import { ALERT_EVALUATION_VALUE, ALERT_TIME_RANGE } from '@kbn/rule-data-utils'; import { GetSLOResponse } from '@kbn/slo-schema'; import React from 'react'; -import { useKibana } from '../../../../../../utils/kibana_react'; +import { useKibana } from '../../../../../../hooks/use_kibana'; import { ErrorRateChart } from '../../../../error_rate_chart'; import { TimeRange } from '../../../../error_rate_chart/use_lens_definition'; import { BurnRateAlert } from '../../types'; diff --git a/x-pack/plugins/observability_solution/slo/public/components/slo/error_rate_chart/error_rate_chart.tsx b/x-pack/plugins/observability_solution/slo/public/components/slo/error_rate_chart/error_rate_chart.tsx index 261359e1b8873..fec552354102e 100644 --- a/x-pack/plugins/observability_solution/slo/public/components/slo/error_rate_chart/error_rate_chart.tsx +++ b/x-pack/plugins/observability_solution/slo/public/components/slo/error_rate_chart/error_rate_chart.tsx @@ -11,7 +11,7 @@ import moment from 'moment'; import React from 'react'; import { SloTabId } from '../../../pages/slo_details/components/slo_details'; import { TimeBounds } from '../../../pages/slo_details/types'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { getDelayInSecondsFromSLO } from '../../../utils/slo/get_delay_in_seconds_from_slo'; import { AlertAnnotation, TimeRange, useLensDefinition } from './use_lens_definition'; diff --git a/x-pack/plugins/observability_solution/slo/public/components/slo/slo_outdated_callout/index.tsx b/x-pack/plugins/observability_solution/slo/public/components/slo/slo_outdated_callout/index.tsx index 8495c43d677b3..e6b235898fa74 100644 --- a/x-pack/plugins/observability_solution/slo/public/components/slo/slo_outdated_callout/index.tsx +++ b/x-pack/plugins/observability_solution/slo/public/components/slo/slo_outdated_callout/index.tsx @@ -8,7 +8,7 @@ import { EuiButton, EuiCallOut, EuiSpacer } from '@elastic/eui'; import React from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { useFetchSloDefinitions } from '../../../hooks/use_fetch_slo_definitions'; import { paths } from '../../../../common/locators/paths'; diff --git a/x-pack/plugins/observability_solution/slo/public/components/slo/slo_status_badge/slo_active_alerts_badge.tsx b/x-pack/plugins/observability_solution/slo/public/components/slo/slo_status_badge/slo_active_alerts_badge.tsx index 3c01e57faa398..bfa15ce490ab4 100644 --- a/x-pack/plugins/observability_solution/slo/public/components/slo/slo_status_badge/slo_active_alerts_badge.tsx +++ b/x-pack/plugins/observability_solution/slo/public/components/slo/slo_status_badge/slo_active_alerts_badge.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import React, { MouseEvent } from 'react'; import { SLOWithSummaryResponse } from '@kbn/slo-schema'; import { observabilityPaths } from '@kbn/observability-plugin/common'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; export interface Props { viewMode?: 'compact' | 'default'; diff --git a/x-pack/plugins/observability_solution/slo/public/constants.ts b/x-pack/plugins/observability_solution/slo/public/constants.ts index 07b79e5505736..ecd07f6209943 100644 --- a/x-pack/plugins/observability_solution/slo/public/constants.ts +++ b/x-pack/plugins/observability_solution/slo/public/constants.ts @@ -5,4 +5,3 @@ * 2.0. */ export const SLO_LONG_REFETCH_INTERVAL = 60 * 1000; // 1 minute -export const SLO_SHORT_REFETCH_INTERVAL = 5 * 1000; // 5 seconds diff --git a/x-pack/plugins/observability_solution/slo/public/context/plugin_context.tsx b/x-pack/plugins/observability_solution/slo/public/context/plugin_context.tsx index b61ccb8085a12..c0818cdea116e 100644 --- a/x-pack/plugins/observability_solution/slo/public/context/plugin_context.tsx +++ b/x-pack/plugins/observability_solution/slo/public/context/plugin_context.tsx @@ -10,6 +10,7 @@ import type { AppMountParameters } from '@kbn/core/public'; import type { LazyObservabilityPageTemplateProps } from '@kbn/observability-shared-plugin/public'; import type { ObservabilityRuleTypeRegistry } from '@kbn/observability-plugin/public'; import { ExperimentalFeatures } from '../../common/config'; +import type { SLORepositoryClient } from '../types'; export interface PluginContextValue { isDev?: boolean; @@ -18,6 +19,7 @@ export interface PluginContextValue { observabilityRuleTypeRegistry: ObservabilityRuleTypeRegistry; ObservabilityPageTemplate: React.ComponentType; experimentalFeatures?: ExperimentalFeatures; + sloClient: SLORepositoryClient; } export const PluginContext = createContext(null); diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/alerts/slo_alerts_embeddable_factory.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/alerts/slo_alerts_embeddable_factory.tsx index 24c29a20f1e6f..c3a505463e885 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/alerts/slo_alerts_embeddable_factory.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/alerts/slo_alerts_embeddable_factory.tsx @@ -5,27 +5,28 @@ * 2.0. */ -import { i18n } from '@kbn/i18n'; -import React, { useEffect } from 'react'; -import { Router } from '@kbn/shared-ux-router'; -import { BehaviorSubject, Subject } from 'rxjs'; +import type { CoreStart } from '@kbn/core-lifecycle-browser'; import { ReactEmbeddableFactory } from '@kbn/embeddable-plugin/public'; +import { i18n } from '@kbn/i18n'; +import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; +import { Storage } from '@kbn/kibana-utils-plugin/public'; import { + FetchContext, + fetch$, initializeTitles, useBatchedPublishingSubjects, - fetch$, - FetchContext, useFetchContext, } from '@kbn/presentation-publishing'; -import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; +import { Router } from '@kbn/shared-ux-router'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { createBrowserHistory } from 'history'; -import { Storage } from '@kbn/kibana-utils-plugin/public'; -import type { StartServicesAccessor } from '@kbn/core-lifecycle-browser'; +import React, { useEffect } from 'react'; +import { BehaviorSubject, Subject } from 'rxjs'; +import { PluginContext } from '../../../context/plugin_context'; +import { SLOPublicPluginsStart, SLORepositoryClient } from '../../../types'; import { SLO_ALERTS_EMBEDDABLE_ID } from './constants'; -import { SloAlertsEmbeddableState, SloAlertsApi } from './types'; -import { SloPublicPluginsStart, SloPublicStart } from '../../../types'; import { SloAlertsWrapper } from './slo_alerts_wrapper'; +import { SloAlertsApi, SloAlertsEmbeddableState } from './types'; const history = createBrowserHistory(); const queryClient = new QueryClient(); @@ -34,10 +35,17 @@ export const getAlertsPanelTitle = () => defaultMessage: 'SLO Alerts', }); -export function getAlertsEmbeddableFactory( - getStartServices: StartServicesAccessor, - kibanaVersion: string -) { +export function getAlertsEmbeddableFactory({ + coreStart, + pluginsStart, + sloClient, + kibanaVersion, +}: { + coreStart: CoreStart; + pluginsStart: SLOPublicPluginsStart; + sloClient: SLORepositoryClient; + kibanaVersion: string; +}) { const factory: ReactEmbeddableFactory< SloAlertsEmbeddableState, SloAlertsEmbeddableState, @@ -48,15 +56,15 @@ export function getAlertsEmbeddableFactory( return state.rawState as SloAlertsEmbeddableState; }, buildEmbeddable: async (state, buildApi, uuid, parentApi) => { - const [coreStart, pluginStart] = await getStartServices(); - const deps = { ...coreStart, ...pluginStart }; + const deps = { ...coreStart, ...pluginsStart }; async function onEdit() { try { const { openSloConfiguration } = await import('./slo_alerts_open_configuration'); const result = await openSloConfiguration( coreStart, - pluginStart, + pluginsStart, + sloClient, api.getSloAlertsConfig() ); api.updateSloAlertsConfig(result); @@ -143,18 +151,28 @@ export function getAlertsEmbeddableFactory( kibanaVersion, }} > - - - - - + + + + + + + ); diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/alerts/slo_alerts_open_configuration.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/alerts/slo_alerts_open_configuration.tsx index 655ad9e3d35ab..c4a8c3886e14f 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/alerts/slo_alerts_open_configuration.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/alerts/slo_alerts_open_configuration.tsx @@ -4,17 +4,21 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import React from 'react'; import type { CoreStart } from '@kbn/core/public'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { toMountPoint } from '@kbn/react-kibana-mount'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; -import { SloPublicPluginsStart } from '../../..'; +import { toMountPoint } from '@kbn/react-kibana-mount'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import React from 'react'; +import { SLOPublicPluginsStart } from '../../..'; +import { PluginContext } from '../../../context/plugin_context'; +import { SLORepositoryClient } from '../../../types'; import { SloConfiguration } from './slo_configuration'; import type { EmbeddableSloProps } from './types'; + export async function openSloConfiguration( coreStart: CoreStart, - pluginStart: SloPublicPluginsStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient, initialState?: EmbeddableSloProps ): Promise { const { overlays } = coreStart; @@ -26,22 +30,31 @@ export async function openSloConfiguration( - - { - flyoutSession.close(); - resolve(update); - }} - onCancel={() => { - flyoutSession.close(); - reject(); - }} - /> - + + + { + flyoutSession.close(); + resolve(update); + }} + onCancel={() => { + flyoutSession.close(); + reject(); + }} + /> + + , coreStart ) diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/burn_rate/burn_rate_react_embeddable_factory.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/burn_rate/burn_rate_react_embeddable_factory.tsx index d0370877b511e..5cceab9fa10d8 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/burn_rate/burn_rate_react_embeddable_factory.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/burn_rate/burn_rate_react_embeddable_factory.tsx @@ -4,31 +4,40 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { i18n } from '@kbn/i18n'; -import React, { useEffect } from 'react'; -import { Router } from '@kbn/shared-ux-router'; -import { createBrowserHistory } from 'history'; import { ReactEmbeddableFactory } from '@kbn/embeddable-plugin/public'; +import { i18n } from '@kbn/i18n'; +import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { + fetch$, initializeTitles, useBatchedPublishingSubjects, - fetch$, } from '@kbn/presentation-publishing'; -import { BehaviorSubject, Subject } from 'rxjs'; -import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; +import { Router } from '@kbn/shared-ux-router'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { SLO_BURN_RATE_EMBEDDABLE_ID } from './constants'; -import { SloBurnRateEmbeddableState, SloEmbeddableDeps, BurnRateApi } from './types'; +import { createBrowserHistory } from 'history'; +import React, { useEffect } from 'react'; +import { BehaviorSubject, Subject } from 'rxjs'; +import { CoreStart } from '@kbn/core-lifecycle-browser'; import { BurnRate } from './burn_rate'; +import { SLO_BURN_RATE_EMBEDDABLE_ID } from './constants'; +import { BurnRateApi, SloBurnRateEmbeddableState } from './types'; +import type { SLOPublicPluginsStart, SLORepositoryClient } from '../../../types'; +import { PluginContext } from '../../../context/plugin_context'; -export const getTitle = () => +const getTitle = () => i18n.translate('xpack.slo.burnRateEmbeddable.title', { defaultMessage: 'SLO Burn Rate', }); -const queryClient = new QueryClient(); - -export const getBurnRateEmbeddableFactory = (deps: SloEmbeddableDeps) => { +export const getBurnRateEmbeddableFactory = ({ + coreStart, + pluginsStart, + sloClient, +}: { + coreStart: CoreStart; + pluginsStart: SLOPublicPluginsStart; + sloClient: SLORepositoryClient; +}) => { const factory: ReactEmbeddableFactory< SloBurnRateEmbeddableState, SloBurnRateEmbeddableState, @@ -39,6 +48,7 @@ export const getBurnRateEmbeddableFactory = (deps: SloEmbeddableDeps) => { return state.rawState as SloBurnRateEmbeddableState; }, buildEmbeddable: async (state, buildApi, uuid, parentApi) => { + const deps = { ...coreStart, ...pluginsStart }; const { titlesApi, titleComparators, serializeTitles } = initializeTitles(state); const defaultTitle$ = new BehaviorSubject(getTitle()); const sloId$ = new BehaviorSubject(state.sloId); @@ -84,18 +94,26 @@ export const getBurnRateEmbeddableFactory = (deps: SloEmbeddableDeps) => { duration$ ); - const I18nContext = deps.i18n.Context; - useEffect(() => { return () => { fetchSubscription.unsubscribe(); }; }, []); + const queryClient = new QueryClient(); + return ( - - - + + + { reloadSubject={reload$} /> - - - + + + ); }, }; diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/burn_rate/open_configuration.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/burn_rate/open_configuration.tsx index e8a7777b29a62..8a881b417bb64 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/burn_rate/open_configuration.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/burn_rate/open_configuration.tsx @@ -10,13 +10,16 @@ import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { toMountPoint } from '@kbn/react-kibana-mount'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import React from 'react'; -import { SloPublicPluginsStart } from '../../..'; +import { SLOPublicPluginsStart } from '../../..'; +import { PluginContext } from '../../../context/plugin_context'; +import { SLORepositoryClient } from '../../../types'; import { Configuration } from './configuration'; import type { EmbeddableProps, SloBurnRateEmbeddableState } from './types'; export async function openConfiguration( coreStart: CoreStart, - pluginStart: SloPublicPluginsStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient, initialState?: SloBurnRateEmbeddableState ): Promise { const { overlays } = coreStart; @@ -28,21 +31,30 @@ export async function openConfiguration( - - { - flyoutSession.close(); - resolve(update); - }} - onCancel={() => { - flyoutSession.close(); - reject(); - }} - /> - + + + { + flyoutSession.close(); + resolve(update); + }} + onCancel={() => { + flyoutSession.close(); + reject(); + }} + /> + + , coreStart ) diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/common/slo_embeddable_context.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/common/slo_embeddable_context.tsx deleted file mode 100644 index acb0897b07e71..0000000000000 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/common/slo_embeddable_context.tsx +++ /dev/null @@ -1,43 +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 React from 'react'; -import { Router } from '@kbn/shared-ux-router'; -import { createBrowserHistory } from 'history'; -import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common'; -import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { PluginContext } from '../../../context/plugin_context'; -import { SloEmbeddableDeps } from '../overview/types'; - -const queryClient = new QueryClient(); - -export interface SloEmbeddableContextProps { - deps: SloEmbeddableDeps; - children: React.ReactNode; -} - -export function SloEmbeddableContext({ deps, children }: SloEmbeddableContextProps) { - const { observabilityRuleTypeRegistry } = deps.observability; - const { navigation } = deps.observabilityShared; - - return ( - - - - - {children} - - - - - ); -} diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/common/slo_overview_details.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/common/slo_overview_details.tsx index 5bfc07f3562bd..3cb5b18aab4a5 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/common/slo_overview_details.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/common/slo_overview_details.tsx @@ -4,7 +4,6 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { i18n } from '@kbn/i18n'; import { EuiButton, @@ -14,22 +13,23 @@ import { EuiFlyoutBody, EuiFlyoutFooter, EuiFlyoutHeader, - EuiTitle, - EuiTabs, - EuiTab, EuiSpacer, + EuiTab, + EuiTabs, + EuiTitle, } from '@elastic/eui'; -import React, { useState } from 'react'; +import { i18n } from '@kbn/i18n'; import { SLOWithSummaryResponse } from '@kbn/slo-schema'; -import { useKibana } from '../../../utils/kibana_react'; -import { useSloDetailsTabs } from '../../../pages/slo_details/hooks/use_slo_details_tabs'; +import React, { useState } from 'react'; import { HeaderTitle } from '../../../pages/slo_details/components/header_title'; -import { getSloFormattedSummary } from '../../../pages/slos/hooks/use_slo_summary'; import { OVERVIEW_TAB_ID, SloDetails, SloTabId, } from '../../../pages/slo_details/components/slo_details'; +import { useSloDetailsTabs } from '../../../pages/slo_details/hooks/use_slo_details_tabs'; +import { getSloFormattedSummary } from '../../../pages/slos/hooks/use_slo_summary'; +import { useKibana } from '../../../hooks/use_kibana'; export function SloOverviewDetails({ slo, diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/error_budget/error_budget_open_configuration.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/error_budget/error_budget_open_configuration.tsx index 6798b7b9c46a6..79e1e1eafe2a9 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/error_budget/error_budget_open_configuration.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/error_budget/error_budget_open_configuration.tsx @@ -4,17 +4,21 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import React from 'react'; import type { CoreStart } from '@kbn/core/public'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { toMountPoint } from '@kbn/react-kibana-mount'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; -import { SloPublicPluginsStart } from '../../..'; +import { toMountPoint } from '@kbn/react-kibana-mount'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import React from 'react'; +import { SLOPublicPluginsStart } from '../../..'; +import { PluginContext } from '../../../context/plugin_context'; import { SloConfiguration } from './slo_configuration'; -import type { SloErrorBudgetEmbeddableState, EmbeddableSloProps } from './types'; +import type { EmbeddableSloProps, SloErrorBudgetEmbeddableState } from './types'; +import { SLORepositoryClient } from '../../../types'; + export async function openSloConfiguration( coreStart: CoreStart, - pluginStart: SloPublicPluginsStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient, initialState?: SloErrorBudgetEmbeddableState ): Promise { const { overlays } = coreStart; @@ -26,21 +30,30 @@ export async function openSloConfiguration( - - { - flyoutSession.close(); - resolve(update); - }} - onCancel={() => { - flyoutSession.close(); - reject(); - }} - /> - + + + { + flyoutSession.close(); + resolve(update); + }} + onCancel={() => { + flyoutSession.close(); + reject(); + }} + /> + + , coreStart ) diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/error_budget/error_budget_react_embeddable_factory.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/error_budget/error_budget_react_embeddable_factory.tsx index 6d01995fb8191..b76152124825d 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/error_budget/error_budget_react_embeddable_factory.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/error_budget/error_budget_react_embeddable_factory.tsx @@ -4,30 +4,40 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { i18n } from '@kbn/i18n'; -import React, { useEffect } from 'react'; -import { Router } from '@kbn/shared-ux-router'; -import { createBrowserHistory } from 'history'; +import { CoreStart } from '@kbn/core-lifecycle-browser'; import { ReactEmbeddableFactory } from '@kbn/embeddable-plugin/public'; +import { i18n } from '@kbn/i18n'; +import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { + fetch$, initializeTitles, useBatchedPublishingSubjects, - fetch$, } from '@kbn/presentation-publishing'; -import { BehaviorSubject, Subject } from 'rxjs'; -import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; +import { Router } from '@kbn/shared-ux-router'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { createBrowserHistory } from 'history'; +import React, { useEffect } from 'react'; +import { BehaviorSubject, Subject } from 'rxjs'; +import { PluginContext } from '../../../context/plugin_context'; +import { SLOPublicPluginsStart, SLORepositoryClient } from '../../../types'; import { SLO_ERROR_BUDGET_ID } from './constants'; -import { SloErrorBudgetEmbeddableState, SloEmbeddableDeps, ErrorBudgetApi } from './types'; import { SloErrorBudget } from './error_budget_burn_down'; +import { ErrorBudgetApi, SloErrorBudgetEmbeddableState } from './types'; -export const getErrorBudgetPanelTitle = () => +const getErrorBudgetPanelTitle = () => i18n.translate('xpack.slo.errorBudgetEmbeddable.title', { defaultMessage: 'SLO Error Budget burn down', }); -const queryClient = new QueryClient(); -export const getErrorBudgetEmbeddableFactory = (deps: SloEmbeddableDeps) => { +export const getErrorBudgetEmbeddableFactory = ({ + coreStart, + pluginsStart, + sloClient, +}: { + coreStart: CoreStart; + pluginsStart: SLOPublicPluginsStart; + sloClient: SLORepositoryClient; +}) => { const factory: ReactEmbeddableFactory< SloErrorBudgetEmbeddableState, SloErrorBudgetEmbeddableState, @@ -38,6 +48,7 @@ export const getErrorBudgetEmbeddableFactory = (deps: SloEmbeddableDeps) => { return state.rawState as SloErrorBudgetEmbeddableState; }, buildEmbeddable: async (state, buildApi, uuid, parentApi) => { + const deps = { ...coreStart, ...pluginsStart }; const { titlesApi, titleComparators, serializeTitles } = initializeTitles(state); const defaultTitle$ = new BehaviorSubject(getErrorBudgetPanelTitle()); const sloId$ = new BehaviorSubject(state.sloId); @@ -76,18 +87,26 @@ export const getErrorBudgetEmbeddableFactory = (deps: SloEmbeddableDeps) => { Component: () => { const [sloId, sloInstanceId] = useBatchedPublishingSubjects(sloId$, sloInstanceId$); - const I18nContext = deps.i18n.Context; - useEffect(() => { return () => { fetchSubscription.unsubscribe(); }; }, []); + const queryClient = new QueryClient(); + return ( - - - + + + { reloadSubject={reload$} /> - - - + + + ); }, }; diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/group_view/slo_group_filters.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/group_view/slo_group_filters.tsx index 2f32d360853bb..d9995adfc412c 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/group_view/slo_group_filters.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/group_view/slo_group_filters.tsx @@ -15,8 +15,8 @@ import { SLO_SUMMARY_DESTINATION_INDEX_NAME } from '../../../../../common/consta import { useCreateDataView } from '../../../../hooks/use_create_data_view'; import { useFetchSloGroups } from '../../../../hooks/use_fetch_slo_groups'; import { SLI_OPTIONS } from '../../../../pages/slo_edit/constants'; -import { useGetSettings } from '../../../../pages/slo_settings/use_get_settings'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useGetSettings } from '../../../../pages/slo_settings/hooks/use_get_settings'; +import { useKibana } from '../../../../hooks/use_kibana'; import type { GroupBy, GroupFilters } from '../types'; import './slo_group_filters.scss'; diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_embeddable_factory.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_embeddable_factory.tsx index 7704bc5326310..e74ba591e7166 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_embeddable_factory.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_embeddable_factory.tsx @@ -5,33 +5,45 @@ * 2.0. */ -import { i18n } from '@kbn/i18n'; -import React, { useEffect } from 'react'; -import styled from 'styled-components'; -import { EuiFlexItem, EuiFlexGroup } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import type { CoreStart } from '@kbn/core-lifecycle-browser'; import { ReactEmbeddableFactory } from '@kbn/embeddable-plugin/public'; +import { i18n } from '@kbn/i18n'; +import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common'; +import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { + fetch$, initializeTitles, useBatchedPublishingSubjects, - fetch$, } from '@kbn/presentation-publishing'; +import { Router } from '@kbn/shared-ux-router'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { createBrowserHistory } from 'history'; +import React, { useEffect } from 'react'; import { BehaviorSubject, Subject } from 'rxjs'; -import type { StartServicesAccessor } from '@kbn/core-lifecycle-browser'; +import styled from 'styled-components'; +import { PluginContext } from '../../../context/plugin_context'; +import type { SLOPublicPluginsStart, SLORepositoryClient } from '../../../types'; import { SLO_OVERVIEW_EMBEDDABLE_ID } from './constants'; -import { SloCardChartList } from './slo_overview_grid'; -import { SloOverview } from './slo_overview'; import { GroupSloView } from './group_view/group_view'; -import { SloOverviewEmbeddableState, SloOverviewApi, GroupSloCustomInput } from './types'; -import { SloPublicPluginsStart, SloPublicStart } from '../../../types'; -import { SloEmbeddableContext } from '../common/slo_embeddable_context'; +import { SloOverview } from './slo_overview'; +import { SloCardChartList } from './slo_overview_grid'; +import { GroupSloCustomInput, SloOverviewApi, SloOverviewEmbeddableState } from './types'; -export const getOverviewPanelTitle = () => +const getOverviewPanelTitle = () => i18n.translate('xpack.slo.sloEmbeddable.displayName', { defaultMessage: 'SLO Overview', }); -export const getOverviewEmbeddableFactory = ( - getStartServices: StartServicesAccessor -) => { + +export const getOverviewEmbeddableFactory = ({ + coreStart, + pluginsStart, + sloClient, +}: { + coreStart: CoreStart; + pluginsStart: SLOPublicPluginsStart; + sloClient: SLORepositoryClient; +}) => { const factory: ReactEmbeddableFactory< SloOverviewEmbeddableState, SloOverviewEmbeddableState, @@ -42,15 +54,15 @@ export const getOverviewEmbeddableFactory = ( return state.rawState as SloOverviewEmbeddableState; }, buildEmbeddable: async (state, buildApi, uuid, parentApi) => { - const [coreStart, pluginStart] = await getStartServices(); - const deps = { ...coreStart, ...pluginStart }; + const deps = { ...coreStart, ...pluginsStart }; async function onEdit() { try { const { openSloConfiguration } = await import('./slo_overview_open_configuration'); const result = await openSloConfiguration( coreStart, - pluginStart, + pluginsStart, + sloClient, api.getSloGroupOverviewConfig() ); api.updateSloGroupOverviewConfig(result as GroupSloCustomInput); @@ -184,10 +196,33 @@ export const getOverviewEmbeddableFactory = ( ); } }; + + const queryClient = new QueryClient(); + return ( - - {showAllGroupByInstances ? : renderOverview()} - + + + + + + {showAllGroupByInstances ? ( + + ) : ( + renderOverview() + )} + + + + + ); }, }; diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_overview_grid.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_overview_grid.tsx index f452f77cb1da3..88e10faeae1a1 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_overview_grid.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_overview_grid.tsx @@ -18,7 +18,7 @@ import { import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; import { EuiFlexGroup, EuiFlexItem, EuiIcon, EuiLoadingSpinner } from '@elastic/eui'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { SloOverviewDetails } from '../common/slo_overview_details'; import { useFetchSloList } from '../../../hooks/use_fetch_slo_list'; import { formatHistoricalData } from '../../../utils/slo/chart_data_formatter'; diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_overview_open_configuration.tsx b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_overview_open_configuration.tsx index 7d10a0ca76bfb..de4f248aad0bf 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_overview_open_configuration.tsx +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/slo_overview_open_configuration.tsx @@ -11,15 +11,21 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { toMountPoint } from '@kbn/react-kibana-mount'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import type { GroupSloCustomInput, SingleSloCustomInput } from './types'; -import { SloPublicPluginsStart } from '../../..'; +import { SLOPublicPluginsStart } from '../../..'; import { SloConfiguration } from './slo_configuration'; +import { SLORepositoryClient } from '../../../types'; +import { PluginContext } from '../../../context/plugin_context'; + export async function openSloConfiguration( coreStart: CoreStart, - pluginStart: SloPublicPluginsStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient, initialState?: GroupSloCustomInput ): Promise { const { overlays } = coreStart; + const queryClient = new QueryClient(); + return new Promise(async (resolve, reject) => { try { const flyoutSession = overlays.openFlyout( @@ -27,22 +33,31 @@ export async function openSloConfiguration( - - { - flyoutSession.close(); - resolve(update); - }} - onCancel={() => { - flyoutSession.close(); - reject(); - }} - /> - + + + { + flyoutSession.close(); + resolve(update); + }} + onCancel={() => { + flyoutSession.close(); + reject(); + }} + /> + + , coreStart ) diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/types.ts b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/types.ts index c64faff1f110d..3c2866077aaa6 100644 --- a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/types.ts +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/overview/types.ts @@ -13,15 +13,6 @@ import { import type { EmbeddableApiContext } from '@kbn/presentation-publishing'; import { DefaultEmbeddableApi } from '@kbn/embeddable-plugin/public'; import { Filter } from '@kbn/es-query'; -import { - type CoreStart, - IUiSettingsClient, - ApplicationStart, - NotificationsStart, -} from '@kbn/core/public'; -import { ObservabilityPublicStart } from '@kbn/observability-plugin/public'; -import type { UiActionsStart } from '@kbn/ui-actions-plugin/public'; -import { ObservabilitySharedPluginStart } from '@kbn/observability-shared-plugin/public'; export type OverviewMode = 'single' | 'groups'; export type GroupBy = 'slo.tags' | 'status' | 'slo.indicator.type'; @@ -72,18 +63,6 @@ export const apiHasSloGroupOverviewConfig = ( ); }; -export interface SloEmbeddableDeps { - uiSettings: IUiSettingsClient; - http: CoreStart['http']; - i18n: CoreStart['i18n']; - theme: CoreStart['theme']; - application: ApplicationStart; - notifications: NotificationsStart; - observability: ObservabilityPublicStart; - observabilityShared: ObservabilitySharedPluginStart; - uiActions: UiActionsStart; -} - export type SloOverviewEmbeddableActionContext = EmbeddableApiContext & { embeddable: SloOverviewApi; }; diff --git a/x-pack/plugins/observability_solution/slo/public/embeddable/slo/types.ts b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/types.ts new file mode 100644 index 0000000000000..08397cd7e6817 --- /dev/null +++ b/x-pack/plugins/observability_solution/slo/public/embeddable/slo/types.ts @@ -0,0 +1,30 @@ +/* + * 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 { + ApplicationStart, + CoreStart, + IUiSettingsClient, + NotificationsStart, +} from '@kbn/core/public'; +import { ObservabilityPublicStart } from '@kbn/observability-plugin/public'; +import { ObservabilitySharedPluginStart } from '@kbn/observability-shared-plugin/public'; +import { UiActionsStart } from '@kbn/ui-actions-plugin/public'; +import type { SLORepositoryClient } from '../../types'; + +export interface SLOEmbeddableDeps { + uiSettings: IUiSettingsClient; + http: CoreStart['http']; + i18n: CoreStart['i18n']; + theme: CoreStart['theme']; + application: ApplicationStart; + notifications: NotificationsStart; + observability: ObservabilityPublicStart; + observabilityShared: ObservabilitySharedPluginStart; + uiActions: UiActionsStart; + sloClient: SLORepositoryClient; +} diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_alerts_url.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_alerts_url.ts index fa97a22204372..65c71a6b58973 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_alerts_url.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_alerts_url.ts @@ -7,7 +7,7 @@ import { observabilityPaths } from '@kbn/observability-plugin/common'; import rison from '@kbn/rison'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; export const useAlertsUrl = () => { const { basePath } = useKibana().services.http; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_capabilities.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_capabilities.ts index bc1856681b930..52db1245b5608 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_capabilities.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_capabilities.ts @@ -5,7 +5,7 @@ * 2.0. */ import { sloFeatureId } from '@kbn/observability-plugin/common'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; export function useCapabilities() { const { diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_clone_slo.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_clone_slo.ts index dc7901e81b528..fbb4145b6bec9 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_clone_slo.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_clone_slo.ts @@ -9,7 +9,7 @@ import { encode } from '@kbn/rison'; import { SLOWithSummaryResponse } from '@kbn/slo-schema'; import { useCallback } from 'react'; import { paths } from '../../common/locators/paths'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { createRemoteSloCloneUrl } from '../utils/slo/remote_slo_urls'; import { useSpace } from './use_space'; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_create_burn_rate_rule.tsx b/x-pack/plugins/observability_solution/slo/public/hooks/use_create_burn_rate_rule.tsx index 906e844c14806..3fa2b7f8ffd81 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_create_burn_rate_rule.tsx +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_create_burn_rate_rule.tsx @@ -16,7 +16,7 @@ import type { } from '@kbn/alerting-plugin/common/routes/rule/apis/create'; import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner } from '@elastic/eui'; import { toMountPoint } from '@kbn/react-kibana-mount'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; export function useCreateRule() { const { diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_create_data_view.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_create_data_view.ts index 781145885df5f..d630ce24c4751 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_create_data_view.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_create_data_view.ts @@ -6,7 +6,7 @@ */ import { useFetcher } from '@kbn/observability-shared-plugin/public'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; interface UseCreateDataViewProps { indexPatternString?: string; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_create_slo.tsx b/x-pack/plugins/observability_solution/slo/public/hooks/use_create_slo.tsx index e5b6d2c114a84..2059c9b273592 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_create_slo.tsx +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_create_slo.tsx @@ -15,9 +15,10 @@ import { toMountPoint } from '@kbn/react-kibana-mount'; import { FormattedMessage } from '@kbn/i18n-react'; import { i18n } from '@kbn/i18n'; import { RedirectAppLinks } from '@kbn/shared-ux-link-redirect-app'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { paths } from '../../common/locators/paths'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; type ServerError = IHttpFetchError; @@ -29,6 +30,7 @@ export function useCreateSlo() { http, notifications: { toasts }, } = useKibana().services; + const { sloClient } = usePluginContext(); const services = useKibana().services; const queryClient = useQueryClient(); @@ -40,8 +42,7 @@ export function useCreateSlo() { >( ['createSlo'], ({ slo }) => { - const body = JSON.stringify(slo); - return http.post(`/api/observability/slos`, { body }); + return sloClient.fetch(`POST /api/observability/slos 2023-10-31`, { params: { body: slo } }); }, { onSuccess: (data, { slo }) => { diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_delete_slo.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_delete_slo.ts index a8d2758e4a9c2..237c5f909ae8a 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_delete_slo.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_delete_slo.ts @@ -8,23 +8,26 @@ import { IHttpFetchError, ResponseErrorBody } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; type ServerError = IHttpFetchError; export function useDeleteSlo() { const { - http, notifications: { toasts }, } = useKibana().services; + const { sloClient } = usePluginContext(); const queryClient = useQueryClient(); - return useMutation( + return useMutation( ['deleteSlo'], ({ id }) => { try { - return http.delete(`/api/observability/slos/${id}`); + return sloClient.fetch(`DELETE /api/observability/slos/{id} 2023-10-31`, { + params: { path: { id } }, + }); } catch (error) { return Promise.reject(`Something went wrong: ${String(error)}`); } diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_delete_slo_instance.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_delete_slo_instance.ts index 66f0012659446..9b84e6f565ead 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_delete_slo_instance.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_delete_slo_instance.ts @@ -7,34 +7,37 @@ import { IHttpFetchError, ResponseErrorBody } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; -import { SLOWithSummaryResponse } from '@kbn/slo-schema'; +import { ALL_VALUE, SLOWithSummaryResponse } from '@kbn/slo-schema'; import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; type ServerError = IHttpFetchError; export function useDeleteSloInstance() { const { - http, notifications: { toasts }, } = useKibana().services; + const { sloClient } = usePluginContext(); const queryClient = useQueryClient(); - return useMutation( + return useMutation( ['deleteSloInstance'], ({ slo, excludeRollup }) => { try { - return http.post(`/api/observability/slos/_delete_instances`, { - body: JSON.stringify({ - list: [ - { - sloId: slo.id, - instanceId: slo.instanceId, - excludeRollup, - }, - ], - }), + return sloClient.fetch(`POST /api/observability/slos/_delete_instances 2023-10-31`, { + params: { + body: { + list: [ + { + sloId: slo.id, + instanceId: slo.instanceId ?? ALL_VALUE, + excludeRollup, + }, + ], + }, + }, }); } catch (error) { return Promise.reject(`Something went wrong: ${String(error)}`); diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_active_alerts.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_active_alerts.ts index 6ad34d8c4dc86..8fa7d3ec88e91 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_active_alerts.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_active_alerts.ts @@ -9,7 +9,7 @@ import { useQuery } from '@tanstack/react-query'; import { BASE_RAC_ALERTS_API_PATH } from '@kbn/rule-registry-plugin/common'; import { AlertConsumers } from '@kbn/rule-registry-plugin/common/technical_rule_data_field_names'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { sloKeys } from './query_key_factory'; import { ActiveAlerts } from './active_alerts'; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_apm_indices.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_apm_indices.ts index e21df7b56a964..436ba45fad273 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_apm_indices.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_apm_indices.ts @@ -7,7 +7,7 @@ import { useQuery } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; type ApmIndex = string; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_apm_suggestions.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_apm_suggestions.ts index c6484076b1d72..ea8ae831a26cf 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_apm_suggestions.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_apm_suggestions.ts @@ -7,7 +7,7 @@ import { useQuery } from '@tanstack/react-query'; import moment from 'moment'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; export type Suggestion = string; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_global_diagnosis.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_global_diagnosis.ts index df8ea83ed2aaa..d943322cf1322 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_global_diagnosis.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_global_diagnosis.ts @@ -9,9 +9,10 @@ import type { SecurityHasPrivilegesResponse } from '@elastic/elasticsearch/lib/a import { i18n } from '@kbn/i18n'; import type { PublicLicenseJSON } from '@kbn/licensing-plugin/public'; import { useQuery } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { convertErrorForUseInToast } from './helpers/convert_error_for_use_in_toast'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; interface SloGlobalDiagnosisResponse { licenseAndFeatures: PublicLicenseJSON; @@ -25,23 +26,17 @@ export interface UseFetchSloGlobalDiagnoseResponse { export function useFetchSloGlobalDiagnosis(): UseFetchSloGlobalDiagnoseResponse { const { - http, notifications: { toasts }, } = useKibana().services; + const { sloClient } = usePluginContext(); const { isLoading, data } = useQuery({ queryKey: sloKeys.globalDiagnosis(), queryFn: async ({ signal }) => { try { - const response = await http.get( - '/internal/observability/slos/_diagnosis', - { - query: {}, - signal, - } - ); - - return response; + return await sloClient.fetch('GET /internal/observability/slos/_diagnosis', { + signal, + }); } catch (error) { throw convertErrorForUseInToast(error); } diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_group_by_cardinality.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_group_by_cardinality.ts index 6be95e67c0d89..beab209f7c692 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_group_by_cardinality.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_group_by_cardinality.ts @@ -10,7 +10,7 @@ import { ALL_VALUE, QuerySchema } from '@kbn/slo-schema'; import { useQuery } from '@tanstack/react-query'; import { lastValueFrom } from 'rxjs'; import { getElasticsearchQueryOrThrow } from '../../common/parse_kuery'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; export interface UseFetchGroupByCardinalityResponse { isLoading: boolean; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_historical_summary.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_historical_summary.ts index fc77e0ba40c7a..b8b0bc7ca9c4e 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_historical_summary.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_historical_summary.ts @@ -5,11 +5,11 @@ * 2.0. */ -import { useQuery } from '@tanstack/react-query'; import { ALL_VALUE, FetchHistoricalSummaryResponse, SLOWithSummaryResponse } from '@kbn/slo-schema'; -import { useKibana } from '../utils/kibana_react'; -import { sloKeys } from './query_key_factory'; +import { useQuery } from '@tanstack/react-query'; import { SLO_LONG_REFETCH_INTERVAL } from '../constants'; +import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; export interface UseFetchHistoricalSummaryResponse { data: FetchHistoricalSummaryResponse | undefined; @@ -34,7 +34,7 @@ export function useFetchHistoricalSummary({ shouldRefetch, range, }: Params): UseFetchHistoricalSummaryResponse { - const { http } = useKibana().services; + const { sloClient } = usePluginContext(); const list = sloList.map((slo) => ({ sloId: slo.id, @@ -57,15 +57,10 @@ export function useFetchHistoricalSummary({ queryKey: sloKeys.historicalSummary(list), queryFn: async ({ signal }) => { try { - const response = await http.post( - '/internal/observability/slos/_historical_summary', - { - body: JSON.stringify({ list }), - signal, - } - ); - - return response; + return await sloClient.fetch('POST /internal/observability/slos/_historical_summary', { + params: { body: { list } }, + signal, + }); } catch (error) { // ignore error } diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_rules_for_slo.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_rules_for_slo.ts index 51a8337e4dd82..841bc9bec0a47 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_rules_for_slo.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_rules_for_slo.ts @@ -9,7 +9,7 @@ import type { Rule, AsApiContract } from '@kbn/triggers-actions-ui-plugin/public import { transformRule } from '@kbn/triggers-actions-ui-plugin/public'; import { useQuery } from '@tanstack/react-query'; import { BurnRateRuleParams } from '../typings'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { sloKeys } from './query_key_factory'; interface Params { diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_burn_rates.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_burn_rates.ts index 3da6e09072dfd..01404a6261a49 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_burn_rates.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_burn_rates.ts @@ -12,8 +12,8 @@ import { useQuery, } from '@tanstack/react-query'; import { SLO_LONG_REFETCH_INTERVAL } from '../constants'; -import { useKibana } from '../utils/kibana_react'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; export interface UseFetchSloBurnRatesResponse { isLoading: boolean; @@ -34,19 +34,24 @@ export function useFetchSloBurnRates({ windows, shouldRefetch, }: UseFetchSloBurnRatesParams): UseFetchSloBurnRatesResponse { - const { http } = useKibana().services; + const { sloClient } = usePluginContext(); const { isLoading, data, refetch } = useQuery({ queryKey: sloKeys.burnRates(slo.id, slo.instanceId, windows), queryFn: async ({ signal }) => { try { - const response = await http.post( - `/internal/observability/slos/${slo.id}/_burn_rates`, + const response = await sloClient.fetch( + 'POST /internal/observability/slos/{id}/_burn_rates', { - body: JSON.stringify({ - windows, - instanceId: slo.instanceId ?? ALL_VALUE, - remoteName: slo.remote?.remoteName, - }), + params: { + path: { + id: slo.id, + }, + body: { + windows, + instanceId: slo.instanceId ?? ALL_VALUE, + remoteName: slo.remote?.remoteName, + }, + }, signal, } ); diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_definitions.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_definitions.ts index 8aae512faab44..085cb777a32ec 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_definitions.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_definitions.ts @@ -7,8 +7,8 @@ import { FindSLODefinitionsResponse } from '@kbn/slo-schema'; import { useQuery } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; export interface UseFetchSloDefinitionsResponse { data: FindSLODefinitionsResponse | undefined; @@ -31,19 +31,19 @@ export function useFetchSloDefinitions({ page = 1, perPage = 100, }: Params): UseFetchSloDefinitionsResponse { - const { http } = useKibana().services; + const { sloClient } = usePluginContext(); const search = name.endsWith('*') ? name : `${name}*`; const { isLoading, isError, isSuccess, data, refetch } = useQuery({ queryKey: sloKeys.definitions(search, page, perPage, includeOutdatedOnly), queryFn: async ({ signal }) => { try { - const response = await http.get( - '/api/observability/slos/_definitions', - { query: { search, includeOutdatedOnly, page, perPage }, signal } - ); - - return response; + return await sloClient.fetch('GET /api/observability/slos/_definitions 2023-10-31', { + params: { + query: { search, includeOutdatedOnly, page: String(page), perPage: String(perPage) }, + }, + signal, + }); } catch (error) { throw new Error(`Something went wrong. Error: ${error}`); } diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_details.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_details.ts index 589701be319ae..b32c0c6dc5976 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_details.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_details.ts @@ -12,9 +12,9 @@ import { RefetchQueryFilters, useQuery, } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; import { SLO_LONG_REFETCH_INTERVAL } from '../constants'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; export interface UseFetchSloDetailsResponse { isInitialLoading: boolean; @@ -39,17 +39,20 @@ export function useFetchSloDetails({ remoteName?: string; shouldRefetch?: boolean; }): UseFetchSloDetailsResponse { - const { http } = useKibana().services; + const { sloClient } = usePluginContext(); const { isInitialLoading, isLoading, isError, isSuccess, isRefetching, data, refetch } = useQuery( { queryKey: sloKeys.detail(sloId!, instanceId, remoteName), queryFn: async ({ signal }) => { try { - const response = await http.get(`/api/observability/slos/${sloId}`, { - query: { - ...(!!instanceId && instanceId !== ALL_VALUE && { instanceId }), - ...(remoteName && { remoteName }), + const response = await sloClient.fetch('GET /api/observability/slos/{id} 2023-10-31', { + params: { + path: { id: sloId! }, + query: { + ...(!!instanceId && instanceId !== ALL_VALUE && { instanceId }), + ...(remoteName && { remoteName }), + }, }, signal, }); diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_groups.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_groups.ts index f7cdfbed28f3f..4b409a2c56562 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_groups.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_groups.ts @@ -4,25 +4,26 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ +import { Filter, buildQueryFromFilters } from '@kbn/es-query'; +import { i18n } from '@kbn/i18n'; +import { FindSLOGroupsResponse } from '@kbn/slo-schema'; import { - useQuery, - RefetchOptions, QueryObserverResult, + RefetchOptions, RefetchQueryFilters, + useQuery, } from '@tanstack/react-query'; -import { i18n } from '@kbn/i18n'; -import { buildQueryFromFilters, Filter } from '@kbn/es-query'; import { useMemo } from 'react'; -import { FindSLOGroupsResponse } from '@kbn/slo-schema'; -import { useKibana } from '../utils/kibana_react'; -import { useCreateDataView } from './use_create_data_view'; -import { sloKeys } from './query_key_factory'; import { DEFAULT_SLO_GROUPS_PAGE_SIZE, SLO_SUMMARY_DESTINATION_INDEX_PATTERN, } from '../../common/constants'; -import { SearchState } from '../pages/slos/hooks/use_url_search_state'; import { GroupByField } from '../pages/slos/components/slo_list_group_by'; +import { SearchState } from '../pages/slos/hooks/use_url_search_state'; +import { useKibana } from './use_kibana'; +import { sloKeys } from './query_key_factory'; +import { useCreateDataView } from './use_create_data_view'; +import { usePluginContext } from './use_plugin_context'; interface SLOGroupsParams { page?: number; @@ -58,8 +59,8 @@ export function useFetchSloGroups({ filters: filterDSL = [], lastRefresh, }: SLOGroupsParams = {}): UseFetchSloGroupsResponse { + const { sloClient } = usePluginContext(); const { - http, notifications: { toasts }, } = useKibana().services; @@ -97,20 +98,19 @@ export function useFetchSloGroups({ lastRefresh, }), queryFn: async ({ signal }) => { - const response = await http.get( - '/internal/observability/slos/_groups', - { + const response = await sloClient.fetch('GET /internal/observability/slos/_groups', { + params: { query: { - ...(page && { page }), - ...(perPage && { perPage }), + ...(page && { page: String(page) }), + ...(perPage && { perPage: String(perPage) }), ...(groupBy && { groupBy }), ...(groupsFilter && { groupsFilter }), ...(kqlQuery && { kqlQuery }), ...(filters && { filters }), }, - signal, - } - ); + }, + signal, + }); return response; }, cacheTime: 0, diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_health.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_health.ts index 4d8439331d042..3dc0024082f1c 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_health.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_health.ts @@ -7,8 +7,8 @@ import { ALL_VALUE, FetchSLOHealthResponse, SLOWithSummaryResponse } from '@kbn/slo-schema'; import { useQuery } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; export interface UseFetchSloHealth { data: FetchSLOHealthResponse | undefined; @@ -21,7 +21,7 @@ export interface Params { } export function useFetchSloHealth({ list }: Params): UseFetchSloHealth { - const { http } = useKibana().services; + const { sloClient } = usePluginContext(); const payload = list.map((slo) => ({ sloId: slo.id, sloInstanceId: slo.instanceId ?? ALL_VALUE, @@ -31,15 +31,10 @@ export function useFetchSloHealth({ list }: Params): UseFetchSloHealth { queryKey: sloKeys.health(payload), queryFn: async ({ signal }) => { try { - const response = await http.post( - '/internal/observability/slos/_health', - { - body: JSON.stringify({ list: payload }), - signal, - } - ); - - return response; + return await sloClient.fetch('POST /internal/observability/slos/_health', { + params: { body: { list: payload } }, + signal, + }); } catch (error) { // ignore error } diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_inspect.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_inspect.ts index 51308b23b3300..df360801ed6fd 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_inspect.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_inspect.ts @@ -5,39 +5,21 @@ * 2.0. */ -import { TransformPutTransformRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import type { CreateSLOInput, SLODefinitionResponse } from '@kbn/slo-schema'; +import type { CreateSLOInput } from '@kbn/slo-schema'; import { useQuery } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; - -interface SLOInspectResponse { - slo: SLODefinitionResponse; - rollUpPipeline: Record; - summaryPipeline: Record; - rollUpTransform: TransformPutTransformRequest; - summaryTransform: TransformPutTransformRequest; - temporaryDoc: Record; - rollUpTransformCompositeQuery: string; - summaryTransformCompositeQuery: string; -} +import { usePluginContext } from './use_plugin_context'; export function useFetchSloInspect(slo: CreateSLOInput, shouldInspect: boolean) { - const { http } = useKibana().services; + const { sloClient } = usePluginContext(); const { isLoading, isError, isSuccess, data } = useQuery({ queryKey: ['slo', 'inspect'], queryFn: async ({ signal }) => { try { - const body = JSON.stringify(slo); - const response = await http.post( - '/internal/observability/slos/_inspect', - { - body, - signal, - } - ); - - return response; + return await sloClient.fetch('POST /internal/observability/slos/_inspect', { + params: { body: slo }, + signal, + }); } catch (error) { // ignore error } diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_list.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_list.ts index 0e2bb39dab878..aba2fe66dcb03 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_list.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slo_list.ts @@ -14,17 +14,17 @@ import { DEFAULT_SLO_PAGE_SIZE, SLO_SUMMARY_DESTINATION_INDEX_PATTERN, } from '../../common/constants'; -import { SearchState } from '../pages/slos/hooks/use_url_search_state'; -import { useKibana } from '../utils/kibana_react'; -import { useCreateDataView } from './use_create_data_view'; - +import { SearchState, SortDirection, SortField } from '../pages/slos/hooks/use_url_search_state'; +import { useKibana } from './use_kibana'; import { sloKeys } from './query_key_factory'; +import { useCreateDataView } from './use_create_data_view'; +import { usePluginContext } from './use_plugin_context'; export interface SLOListParams { kqlQuery?: string; page?: number; - sortBy?: string; - sortDirection?: 'asc' | 'desc'; + sortBy?: SortField; + sortDirection?: SortDirection; perPage?: number; filters?: Filter[]; lastRefresh?: number; @@ -55,9 +55,10 @@ export function useFetchSloList({ disabled = false, }: SLOListParams = {}): UseFetchSloListResponse { const { - http, notifications: { toasts }, } = useKibana().services; + const { sloClient } = usePluginContext(); + const queryClient = useQueryClient(); const { dataView } = useCreateDataView({ @@ -95,15 +96,17 @@ export function useFetchSloList({ lastRefresh, }), queryFn: async ({ signal }) => { - return await http.get(`/api/observability/slos`, { - query: { - ...(kqlQuery && { kqlQuery }), - ...(sortBy && { sortBy }), - ...(sortDirection && { sortDirection }), - ...(page !== undefined && { page }), - ...(perPage !== undefined && { perPage }), - ...(filters && { filters }), - hideStale: true, + return await sloClient.fetch('GET /api/observability/slos 2023-10-31', { + params: { + query: { + ...(kqlQuery && { kqlQuery }), + ...(sortBy && { sortBy }), + ...(sortDirection && { sortDirection }), + ...(page !== undefined && { page: String(page) }), + ...(perPage !== undefined && { perPage: String(perPage) }), + ...(filters && { filters }), + hideStale: true, + }, }, signal, }); diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slos_with_burn_rate_rules.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slos_with_burn_rate_rules.ts index 34cfa36bfcab8..ce1efab910723 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slos_with_burn_rate_rules.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_slos_with_burn_rate_rules.ts @@ -14,7 +14,7 @@ import { import type { Rule } from '@kbn/triggers-actions-ui-plugin/public'; import { BASE_ALERTING_API_PATH } from '@kbn/alerting-plugin/common'; import { HttpSetup } from '@kbn/core/public'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { sloKeys } from './query_key_factory'; import { WindowSchema } from '../typings'; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_synthetics_suggestions.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_synthetics_suggestions.ts index f985b1f53ca94..f97bf64f5c8da 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_synthetics_suggestions.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_fetch_synthetics_suggestions.ts @@ -7,7 +7,7 @@ import { useQuery } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; export interface Suggestion { label: string; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_get_preview_data.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_get_preview_data.ts index f8e65fea9edff..5b4dc32ca4f28 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_get_preview_data.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_get_preview_data.ts @@ -7,8 +7,8 @@ import { GetPreviewDataResponse, Indicator, Objective } from '@kbn/slo-schema'; import { useQuery } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; export interface UseGetPreviewData { data: GetPreviewDataResponse | undefined; @@ -18,6 +18,20 @@ export interface UseGetPreviewData { isError: boolean; } +interface Props { + isValid: boolean; + groupBy?: string | string[]; + instanceId?: string; + remoteName?: string; + groupings?: Record; + objective?: Objective; + indicator: Indicator; + range: { + from: Date; + to: Date; + }; +} + export function useGetPreviewData({ isValid, range, @@ -27,36 +41,29 @@ export function useGetPreviewData({ groupings, instanceId, remoteName, -}: { - isValid: boolean; - groupBy?: string | string[]; - instanceId?: string; - remoteName?: string; - groupings?: Record; - objective?: Objective; - indicator: Indicator; - range: { from: Date; to: Date }; -}): UseGetPreviewData { - const { http } = useKibana().services; +}: Props): UseGetPreviewData { + const { sloClient } = usePluginContext(); const { isInitialLoading, isLoading, isError, isSuccess, data } = useQuery({ queryKey: sloKeys.preview(indicator, range, groupings), queryFn: async ({ signal }) => { - const response = await http.post( - '/internal/observability/slos/_preview', - { - body: JSON.stringify({ + const response = await sloClient.fetch('POST /internal/observability/slos/_preview', { + params: { + body: { indicator, - range, + range: { + from: range.from.toISOString(), + to: range.to.toISOString(), + }, groupBy, instanceId, groupings, remoteName, ...(objective ? { objective } : null), - }), - signal, - } - ); + }, + }, + signal, + }); return Array.isArray(response) ? response : []; }, diff --git a/x-pack/plugins/observability_solution/slo/public/utils/kibana_react.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_kibana.ts similarity index 80% rename from x-pack/plugins/observability_solution/slo/public/utils/kibana_react.ts rename to x-pack/plugins/observability_solution/slo/public/hooks/use_kibana.ts index 20ec03497b0af..5880a52a11ee6 100644 --- a/x-pack/plugins/observability_solution/slo/public/utils/kibana_react.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_kibana.ts @@ -8,14 +8,15 @@ import { CoreStart } from '@kbn/core/public'; import { useKibana } from '@kbn/kibana-react-plugin/public'; import { Storage } from '@kbn/kibana-utils-plugin/public'; -import { SloPublicPluginsStart } from '../types'; +import { SLOPublicPluginsStart } from '../types'; -export type StartServices = CoreStart & - SloPublicPluginsStart & +type StartServices = CoreStart & + SLOPublicPluginsStart & AdditionalServices & { storage: Storage; kibanaVersion: string; }; + const useTypedKibana = () => useKibana>(); diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_license.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_license.ts index 823c9e4135bf7..763e0bb1b0228 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_license.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_license.ts @@ -9,7 +9,7 @@ import { useCallback } from 'react'; import { Observable } from 'rxjs'; import useObservable from 'react-use/lib/useObservable'; import type { ILicense, LicenseType } from '@kbn/licensing-plugin/public'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; interface UseLicenseReturnValue { getLicense: () => ILicense | null; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_permissions.test.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_permissions.test.ts index c9646c070dbbb..7d70e5f6460ff 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_permissions.test.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_permissions.test.ts @@ -5,11 +5,11 @@ * 2.0. */ import { sloFeatureId } from '@kbn/observability-shared-plugin/common'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { useFetchSloGlobalDiagnosis } from './use_fetch_global_diagnosis'; import { usePermissions } from './use_permissions'; -jest.mock('../utils/kibana_react'); +jest.mock('./use_kibana'); jest.mock('./use_fetch_global_diagnosis'); const useKibanaMock = useKibana as jest.Mock; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_permissions.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_permissions.ts index 6e380fbe1a33e..efd6c6cab94c9 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_permissions.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_permissions.ts @@ -5,7 +5,7 @@ * 2.0. */ import { sloFeatureId } from '@kbn/observability-plugin/common'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; import { useFetchSloGlobalDiagnosis } from './use_fetch_global_diagnosis'; export function usePermissions() { diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_reset_slo.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_reset_slo.ts index 18d09d5859145..fdca20517102e 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_reset_slo.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_reset_slo.ts @@ -7,23 +7,27 @@ import { IHttpFetchError, ResponseErrorBody } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; +import { ResetSLOResponse } from '@kbn/slo-schema'; +import { useKibana } from './use_kibana'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; type ServerError = IHttpFetchError; export function useResetSlo() { const { - http, notifications: { toasts }, } = useKibana().services; const queryClient = useQueryClient(); + const { sloClient } = usePluginContext(); - return useMutation( + return useMutation( ['resetSlo'], ({ id, name }) => { try { - return http.post(`/api/observability/slos/${id}/_reset`); + return sloClient.fetch('POST /api/observability/slos/{id}/_reset 2023-10-31', { + params: { path: { id } }, + }); } catch (error) { return Promise.reject( i18n.translate('xpack.slo.slo.reset.errorMessage', { diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_space.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_space.ts index c52056f006de2..8e348c1772398 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_space.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_space.ts @@ -6,7 +6,7 @@ */ import { useState, useEffect } from 'react'; -import { useKibana } from '../utils/kibana_react'; +import { useKibana } from './use_kibana'; export function useSpace() { const { spaces } = useKibana().services; diff --git a/x-pack/plugins/observability_solution/slo/public/hooks/use_update_slo.ts b/x-pack/plugins/observability_solution/slo/public/hooks/use_update_slo.ts index 21e9aa57c142d..2050b9cc101a7 100644 --- a/x-pack/plugins/observability_solution/slo/public/hooks/use_update_slo.ts +++ b/x-pack/plugins/observability_solution/slo/public/hooks/use_update_slo.ts @@ -10,9 +10,10 @@ import { i18n } from '@kbn/i18n'; import { encode } from '@kbn/rison'; import type { FindSLOResponse, UpdateSLOInput, UpdateSLOResponse } from '@kbn/slo-schema'; import { QueryKey, useMutation, useQueryClient } from '@tanstack/react-query'; -import { useKibana } from '../utils/kibana_react'; import { paths } from '../../common/locators/paths'; +import { useKibana } from './use_kibana'; import { sloKeys } from './query_key_factory'; +import { usePluginContext } from './use_plugin_context'; type ServerError = IHttpFetchError; @@ -23,6 +24,7 @@ export function useUpdateSlo() { notifications: { toasts }, } = useKibana().services; const queryClient = useQueryClient(); + const { sloClient } = usePluginContext(); return useMutation< UpdateSLOResponse, @@ -32,8 +34,9 @@ export function useUpdateSlo() { >( ['updateSlo'], ({ sloId, slo }) => { - const body = JSON.stringify(slo); - return http.put(`/api/observability/slos/${sloId}`, { body }); + return sloClient.fetch('PUT /api/observability/slos/{id} 2023-10-31', { + params: { path: { id: sloId }, body: slo }, + }); }, { onSuccess: (_data, { slo: { name } }) => { diff --git a/x-pack/plugins/observability_solution/slo/public/index.ts b/x-pack/plugins/observability_solution/slo/public/index.ts index e57edb2205208..7d01e9c418fb5 100644 --- a/x-pack/plugins/observability_solution/slo/public/index.ts +++ b/x-pack/plugins/observability_solution/slo/public/index.ts @@ -5,20 +5,26 @@ * 2.0. */ import { PluginInitializer, PluginInitializerContext } from '@kbn/core/public'; -import { SloPlugin } from './plugin'; +import { SLOPlugin } from './plugin'; import type { - SloPublicSetup, - SloPublicStart, - SloPublicPluginsSetup, - SloPublicPluginsStart, + SLOPublicSetup, + SLOPublicStart, + SLOPublicPluginsSetup, + SLOPublicPluginsStart, } from './types'; export const plugin: PluginInitializer< - SloPublicSetup, - SloPublicStart, - SloPublicPluginsSetup, - SloPublicPluginsStart + SLOPublicSetup, + SLOPublicStart, + SLOPublicPluginsSetup, + SLOPublicPluginsStart > = (initializerContext: PluginInitializerContext) => { - return new SloPlugin(initializerContext); + return new SLOPlugin(initializerContext); }; -export type { SloPublicPluginsSetup, SloPublicPluginsStart, SloPublicStart } from './types'; + +export type { + SLOPublicPluginsSetup, + SLOPublicPluginsStart, + SLOPublicStart, + SLOPublicSetup, +} from './types'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_chart.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_chart.tsx index 8b15c809ab1d0..4f6b5a159c62a 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_chart.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_chart.tsx @@ -12,7 +12,7 @@ import numeral from '@elastic/numeral'; import { SLOWithSummaryResponse } from '@kbn/slo-schema'; import { TimeBounds } from '../types'; import { SloTabId } from './slo_details'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { toDuration, toMinutes } from '../../../utils/slo/duration'; import { ChartData } from '../../../typings/slo'; import { WideChart } from './wide_chart'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_chart_panel.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_chart_panel.tsx index b8ffb2f30a79e..72c6cf30c9de6 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_chart_panel.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_chart_panel.tsx @@ -16,7 +16,7 @@ import React, { useState, useCallback } from 'react'; import { SaveModalDashboardProps } from '@kbn/presentation-util-plugin/public'; import { TimeBounds } from '../types'; import { SloTabId } from './slo_details'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { ChartData } from '../../../typings/slo'; import { ErrorBudgetChart } from './error_budget_chart'; import { ErrorBudgetHeader } from './error_budget_header'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_header.test.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_header.test.tsx index 65a4033314972..533fd6b499a7a 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_header.test.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_header.test.tsx @@ -7,12 +7,12 @@ import React from 'react'; import { screen } from '@testing-library/react'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { render } from '../../../utils/test_helper'; import { buildSlo } from '../../../data/slo/slo'; import { ErrorBudgetHeader } from './error_budget_header'; -jest.mock('../../../utils/kibana_react'); +jest.mock('../../../hooks/use_kibana'); const useKibanaMock = useKibana as jest.Mock; describe('In Observability Context', () => { diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_header.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_header.tsx index 4a484d9df013f..11d1b1e600b0d 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_header.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/error_budget_header.tsx @@ -10,7 +10,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiText, EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { rollingTimeWindowTypeSchema, SLOWithSummaryResponse } from '@kbn/slo-schema'; import { SloTabId } from './slo_details'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { toDurationAdverbLabel, toDurationLabel } from '../../../utils/slo/labels'; import { ErrorBudgetActions } from './error_budget_actions'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/events_area_chart.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/events_area_chart.tsx index 01496c6471d89..364e775eaf0e4 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/events_area_chart.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/events_area_chart.tsx @@ -16,7 +16,7 @@ import { useActiveCursor } from '@kbn/charts-plugin/public'; import moment from 'moment'; import { getBrushTimeBounds } from '../../../utils/slo/duration'; import { TimeBounds } from '../types'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; export function EventsAreaChart({ slo, diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/events_chart_panel.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/events_chart_panel.tsx index 4b393e307deb3..3ea9cb30627ad 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/events_chart_panel.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/events_chart_panel.tsx @@ -25,7 +25,7 @@ import { EventsAreaChart } from './events_area_chart'; import { TimeBounds } from '../types'; import { SloTabId } from './slo_details'; import { useGetPreviewData } from '../../../hooks/use_get_preview_data'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { GoodBadEventsChart } from '../../../components/good_bad_events_chart/good_bad_events_chart'; import { getDiscoverLink } from '../../../utils/slo/get_discover_link'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/header_control.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/header_control.tsx index fb1e524e3e170..e4ccb4f0cbf26 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/header_control.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/header_control.tsx @@ -24,7 +24,7 @@ import { useCloneSlo } from '../../../hooks/use_clone_slo'; import { useFetchRulesForSlo } from '../../../hooks/use_fetch_rules_for_slo'; import { usePermissions } from '../../../hooks/use_permissions'; import { useResetSlo } from '../../../hooks/use_reset_slo'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { convertSliApmParamsToApmAppDeeplinkUrl } from '../../../utils/slo/convert_sli_apm_params_to_apm_app_deeplink_url'; import { isApmIndicatorType } from '../../../utils/slo/indicator'; import { EditBurnRateRuleFlyout } from '../../slos/components/common/edit_burn_rate_rule_flyout'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/history/slo_details_history.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/history/slo_details_history.tsx index 7ecf4d4672775..45177fa0d73fe 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/history/slo_details_history.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/history/slo_details_history.tsx @@ -16,7 +16,7 @@ import DateMath from '@kbn/datemath'; import { SLOWithSummaryResponse } from '@kbn/slo-schema'; import React, { useMemo, useState } from 'react'; import { BurnRates } from '../../../../components/slo/burn_rate/burn_rates'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { useBurnRateOptions } from '../../hooks/use_burn_rate_options'; import { TimeBounds } from '../../types'; import { EventsChartPanel } from '../events_chart_panel'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/apm_indicator_overview.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/apm_indicator_overview.tsx index 6520c061d6d07..be1cc2b15fd8a 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/apm_indicator_overview.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/apm_indicator_overview.tsx @@ -14,7 +14,7 @@ import { SLOWithSummaryResponse, } from '@kbn/slo-schema'; import React from 'react'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { convertSliApmParamsToApmAppDeeplinkUrl } from '../../../../utils/slo/convert_sli_apm_params_to_apm_app_deeplink_url'; import { OverviewItem } from './overview_item'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/display_query.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/display_query.tsx index 0d6674cc4036c..db85ad817f464 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/display_query.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/display_query.tsx @@ -10,7 +10,7 @@ import { QuerySchema } from '@kbn/slo-schema'; import { EuiCodeBlock, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; import { FilterItem } from '@kbn/unified-search-plugin/public'; import { injectI18n } from '@kbn/i18n-react'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { useCreateDataView } from '../../../../hooks/use_create_data_view'; const FilterItemI18n = injectI18n(FilterItem); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/overview.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/overview.tsx index c974c91b00a69..34f3b0132dc8a 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/overview.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/overview.tsx @@ -17,7 +17,7 @@ import { import React from 'react'; import { TagsList } from '@kbn/observability-shared-plugin/public'; import { DisplayQuery } from './display_query'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { BUDGETING_METHOD_OCCURRENCES, BUDGETING_METHOD_TIMESLICES, diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/synthetics_indicator_overview.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/synthetics_indicator_overview.tsx index a475428a6005b..6083d988a8b98 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/synthetics_indicator_overview.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/overview/synthetics_indicator_overview.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { syntheticsAvailabilityIndicatorSchema, SLOWithSummaryResponse } from '@kbn/slo-schema'; import React from 'react'; import { syntheticsMonitorDetailLocatorID } from '@kbn/observability-plugin/common'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { OverviewItem } from './overview_item'; interface Props { diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/sli_chart_panel.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/sli_chart_panel.tsx index 9a7c814630aae..0225c380737a4 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/sli_chart_panel.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/sli_chart_panel.tsx @@ -12,7 +12,7 @@ import { rollingTimeWindowTypeSchema, SLOWithSummaryResponse } from '@kbn/slo-sc import React from 'react'; import { TimeBounds } from '../types'; import { SloTabId } from './slo_details'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { ChartData } from '../../../typings/slo'; import { toDurationAdverbLabel, toDurationLabel } from '../../../utils/slo/labels'; import { WideChart } from './wide_chart'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/slo_detail_alerts.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/slo_detail_alerts.tsx index 7e002d1cac7d1..3aa94c00b6441 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/slo_detail_alerts.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/slo_detail_alerts.tsx @@ -10,7 +10,7 @@ import { AlertConsumers } from '@kbn/rule-data-utils'; import { ALL_VALUE, SLOWithSummaryResponse } from '@kbn/slo-schema'; import { SLO_ALERTS_TABLE_ID } from '@kbn/observability-shared-plugin/common'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; export interface Props { slo: SLOWithSummaryResponse; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/slo_health_callout.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/slo_health_callout.tsx index 0b9e312910319..ab34e2428786c 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/slo_health_callout.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/slo_health_callout.tsx @@ -19,7 +19,7 @@ import { SLOWithSummaryResponse } from '@kbn/slo-schema'; import React from 'react'; import { getSLOSummaryTransformId, getSLOTransformId } from '../../../../common/constants'; import { useFetchSloHealth } from '../../../hooks/use_fetch_slo_health'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; export function SloHealthCallout({ slo }: { slo: SLOWithSummaryResponse }) { const { http } = useKibana().services; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/wide_chart.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/wide_chart.tsx index faff275ffbeac..b1354205990af 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/wide_chart.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/components/wide_chart.tsx @@ -26,7 +26,7 @@ import { useAnnotations } from '@kbn/observability-plugin/public'; import { SLOWithSummaryResponse } from '@kbn/slo-schema'; import { getBrushTimeBounds } from '../../../utils/slo/duration'; import { TimeBounds } from '../types'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { ChartData } from '../../../typings'; type ChartType = 'area' | 'line'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/hooks/use_slo_actions.ts b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/hooks/use_slo_actions.ts index 44a6b8979ecd6..8e7be877ca02e 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/hooks/use_slo_actions.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/hooks/use_slo_actions.ts @@ -12,7 +12,7 @@ import path from 'path'; import { paths } from '../../../../common/locators/paths'; import { useSpace } from '../../../hooks/use_space'; import { BurnRateRuleParams } from '../../../typings'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { createRemoteSloDeleteUrl, createRemoteSloEditUrl, diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/hooks/use_slo_details_tabs.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/hooks/use_slo_details_tabs.tsx index 8eb954d4b5771..83acc81a68716 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/hooks/use_slo_details_tabs.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/hooks/use_slo_details_tabs.tsx @@ -10,7 +10,7 @@ import { EuiNotificationBadge, EuiToolTip } from '@elastic/eui'; import React from 'react'; import { ALL_VALUE, SLOWithSummaryResponse } from '@kbn/slo-schema'; import { paths } from '../../../../common/locators/paths'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { useFetchActiveAlerts } from '../../../hooks/use_fetch_active_alerts'; import { ALERTS_TAB_ID, diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/slo_details.test.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/slo_details.test.tsx index eb678b8ca7418..a363fdccb16f8 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/slo_details.test.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/slo_details.test.tsx @@ -30,7 +30,7 @@ import { useFetchHistoricalSummary } from '../../hooks/use_fetch_historical_summ import { useFetchSloDetails } from '../../hooks/use_fetch_slo_details'; import { useLicense } from '../../hooks/use_license'; import { usePermissions } from '../../hooks/use_permissions'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { render } from '../../utils/test_helper'; import { SloDetailsPage } from './slo_details'; import { usePerformanceContext } from '@kbn/ebt-tools'; @@ -41,7 +41,7 @@ jest.mock('react-router-dom', () => ({ })); jest.mock('@kbn/observability-shared-plugin/public'); -jest.mock('../../utils/kibana_react'); +jest.mock('../../hooks/use_kibana'); jest.mock('../../hooks/use_license'); jest.mock('../../hooks/use_permissions'); jest.mock('../../hooks/use_fetch_active_alerts'); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/slo_details.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/slo_details.tsx index 9a32c150e1b8c..38f65bb341070 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_details/slo_details.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_details/slo_details.tsx @@ -24,7 +24,7 @@ import { useFetchSloDetails } from '../../hooks/use_fetch_slo_details'; import { useLicense } from '../../hooks/use_license'; import { usePermissions } from '../../hooks/use_permissions'; import { usePluginContext } from '../../hooks/use_plugin_context'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import PageNotFound from '../404'; import { HeaderControl } from './components/header_control'; import { HeaderTitle } from './components/header_title'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/data_preview_chart.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/data_preview_chart.tsx index e797c4d5d3b3d..60d464b1f0503 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/data_preview_chart.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/data_preview_chart.tsx @@ -37,7 +37,7 @@ import { max, min } from 'lodash'; import moment from 'moment'; import React, { useState } from 'react'; import { useFormContext } from 'react-hook-form'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { GoodBadEventsChart } from '../../../../components/good_bad_events_chart/good_bad_events_chart'; import { useDebouncedGetPreviewData } from '../../hooks/use_preview'; import { useSectionFormValidation } from '../../hooks/use_section_form_validation'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/documents_table.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/documents_table.tsx index ed250da853f9e..546b443aa23c7 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/documents_table.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/documents_table.tsx @@ -16,7 +16,7 @@ import { EuiResizableContainer, EuiProgress, EuiCallOut, EuiSpacer } from '@elas import { buildFilter, FILTERS, TimeRange } from '@kbn/es-query'; import { FieldPath, useFormContext } from 'react-hook-form'; import { Serializable } from '@kbn/utility-types'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { CreateSLOForm } from '../../types'; import { QuerySearchBar } from './query_search_bar'; import { SearchBarProps } from './query_builder'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/query_search_bar.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/query_search_bar.tsx index 394d8c303e953..e7e61adfc1cc5 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/query_search_bar.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/query_search_bar.tsx @@ -13,7 +13,7 @@ import React, { memo } from 'react'; import styled from 'styled-components'; import { observabilityAppId } from '@kbn/observability-shared-plugin/common'; import { SearchBarProps } from './query_builder'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { CreateSLOForm } from '../../types'; import { OptionalText } from './optional_text'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/slo_inspect/req_code_viewer.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/slo_inspect/req_code_viewer.tsx index f160dc0aa33c0..451997319a03d 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/slo_inspect/req_code_viewer.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/slo_inspect/req_code_viewer.tsx @@ -13,7 +13,7 @@ import { XJsonLang } from '@kbn/monaco'; import React, { ReactNode, useCallback } from 'react'; import { CodeEditor } from '@kbn/code-editor'; import { compressToEncodedURIComponent } from 'lz-string'; -import { useKibana } from '../../../../../utils/kibana_react'; +import { useKibana } from '../../../../../hooks/use_kibana'; interface RequestCodeViewerProps { value: string; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/slo_inspect/slo_inspect.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/slo_inspect/slo_inspect.tsx index 18d0d966c1ac0..1b4a49bc81894 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/slo_inspect/slo_inspect.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/slo_inspect/slo_inspect.tsx @@ -27,7 +27,7 @@ import { GetSLOResponse } from '@kbn/slo-schema'; import React, { useState } from 'react'; import { useFormContext } from 'react-hook-form'; import { enableInspectEsQueries } from '@kbn/observability-plugin/common'; -import { useKibana } from '../../../../../utils/kibana_react'; +import { useKibana } from '../../../../../hooks/use_kibana'; import { useFetchSloInspect } from '../../../../../hooks/use_fetch_slo_inspect'; import { usePluginContext } from '../../../../../hooks/use_plugin_context'; import { transformCreateSLOFormToCreateSLOInput } from '../../../helpers/process_slo_form_values'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/use_field_sidebar.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/use_field_sidebar.tsx index 71d6ab00a77af..37467eb33c272 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/use_field_sidebar.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/common/use_field_sidebar.tsx @@ -8,7 +8,7 @@ import React, { useMemo, SetStateAction } from 'react'; import { UnifiedFieldListSidebarContainer } from '@kbn/unified-field-list'; import { DataView } from '@kbn/data-views-plugin/common'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; export const useFieldSidebar = ({ dataView, diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/custom_common/index_selection.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/custom_common/index_selection.tsx index 7332c94103c7e..146d11be84ac8 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/custom_common/index_selection.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/custom_common/index_selection.tsx @@ -12,8 +12,8 @@ import React, { useEffect } from 'react'; import { Controller, useFormContext } from 'react-hook-form'; import { DataViewPicker } from '@kbn/unified-search-plugin/public'; import { getDataViewPattern, useAdhocDataViews } from './use_adhoc_data_views'; -import { SloPublicPluginsStart } from '../../../..'; -import { useKibana } from '../../../../utils/kibana_react'; +import { SLOPublicPluginsStart } from '../../../..'; +import { useKibana } from '../../../../hooks/use_kibana'; import { CreateSLOForm } from '../../types'; const BTN_MAX_WIDTH = 515; @@ -26,7 +26,7 @@ export function IndexSelection({ selectedDataView }: { selectedDataView?: DataVi const { control, getFieldState, setValue, watch } = useFormContext(); const { dataViews: dataViewsService, dataViewFieldEditor } = useKibana().services; - const { dataViewEditor } = useKibana().services; + const { dataViewEditor } = useKibana().services; const currentIndexPattern = watch(INDEX_FIELD); const currentDataViewId = watch(DATA_VIEW_FIELD); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/custom_common/use_adhoc_data_views.ts b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/custom_common/use_adhoc_data_views.ts index 6c8288df6b9d9..67792b056408d 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/custom_common/use_adhoc_data_views.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/custom_common/use_adhoc_data_views.ts @@ -8,7 +8,7 @@ import { useEffect, useState } from 'react'; import { DataView, DataViewListItem } from '@kbn/data-views-plugin/common'; import { useFetchDataViews } from '@kbn/observability-plugin/public'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; export const getDataViewPattern = ({ byId, diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/slo_edit_form_footer.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/slo_edit_form_footer.tsx index 29150231046d1..ab0c7ff235fbf 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/slo_edit_form_footer.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/slo_edit_form_footer.tsx @@ -12,7 +12,7 @@ import React, { useCallback, useMemo } from 'react'; import { useFormContext } from 'react-hook-form'; import { InPortal } from 'react-reverse-portal'; import { useCreateRule } from '../../../hooks/use_create_burn_rate_rule'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { sloEditFormFooterPortal } from '../shared_flyout/slo_add_form_flyout'; import { paths } from '../../../../common/locators/paths'; import { useCreateSlo } from '../../../hooks/use_create_slo'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/timeslice_metric/timeslice_metric_indicator.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/timeslice_metric/timeslice_metric_indicator.tsx index 548f0bd0ab3e5..86eede0ba65e2 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/timeslice_metric/timeslice_metric_indicator.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/components/timeslice_metric/timeslice_metric_indicator.tsx @@ -19,7 +19,7 @@ import { FormattedMessage } from '@kbn/i18n-react'; import React from 'react'; import { useFormContext } from 'react-hook-form'; import { IndexAndTimestampField } from '../custom_common/index_and_timestamp_field'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { GroupByField } from '../common/group_by_field'; import { CreateSLOForm } from '../../types'; import { DataPreviewChart } from '../common/data_preview_chart'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/hooks/use_fetch_suggestions.ts b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/hooks/use_fetch_suggestions.ts index ff9ebffa72f56..4cfe886b17b69 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/hooks/use_fetch_suggestions.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/hooks/use_fetch_suggestions.ts @@ -6,22 +6,18 @@ */ import { useQuery } from '@tanstack/react-query'; -import { GetSLOSuggestionsResponse } from '@kbn/slo-schema'; -import { useKibana } from '../../../utils/kibana_react'; +import { usePluginContext } from '../../../hooks/use_plugin_context'; export function useFetchSLOSuggestions() { - const { http } = useKibana().services; + const { sloClient } = usePluginContext(); const { isLoading, isError, isSuccess, data } = useQuery({ queryKey: ['fetchSLOSuggestions'], queryFn: async ({ signal }) => { try { - return await http.get( - '/internal/observability/slos/suggestions', - { - signal, - } - ); + return await sloClient.fetch('GET /internal/observability/slos/suggestions', { + signal, + }); } catch (error) { // ignore error } diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/slo_add_form_flyout.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/slo_add_form_flyout.tsx index c3b51a0058fed..98c76b190aa1a 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/slo_add_form_flyout.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/slo_add_form_flyout.tsx @@ -4,19 +4,20 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { FormattedMessage } from '@kbn/i18n-react'; -import React from 'react'; -import { EuiTitle, EuiFlyoutHeader, EuiFlyout, EuiFlyoutBody, EuiFlyoutFooter } from '@elastic/eui'; +import { EuiFlyout, EuiFlyoutBody, EuiFlyoutFooter, EuiFlyoutHeader, EuiTitle } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n-react'; import { RecursivePartial } from '@kbn/utility-types'; import { merge } from 'lodash'; -import { createHtmlPortalNode, OutPortal } from 'react-reverse-portal'; -import { CreateSLOForm } from '../types'; +import React from 'react'; +import { OutPortal, createHtmlPortalNode } from 'react-reverse-portal'; import { SloEditForm } from '../components/slo_edit_form'; +import { CreateSLOForm } from '../types'; export const sloEditFormFooterPortal = createHtmlPortalNode(); -function SloAddFormFlyout({ +// eslint-disable-next-line import/no-default-export +export default function SloAddFormFlyout({ onClose, initialValues, }: { @@ -69,6 +70,3 @@ function SloAddFormFlyout({ ); } - -// eslint-disable-next-line import/no-default-export -export default SloAddFormFlyout; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/slo_form.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/slo_form.tsx deleted file mode 100644 index 8c105e6159797..0000000000000 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/slo_form.tsx +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { lazy } from 'react'; -import React, { Suspense } from 'react'; -import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, EuiLoadingSpinnerProps } from '@elastic/eui'; - -function CenterJustifiedSpinner({ size }: { size: EuiLoadingSpinnerProps['size'] }) { - return ( - - - - - - ); -} - -function suspendedComponentWithProps( - ComponentToSuspend: React.ComponentType, - size?: EuiLoadingSpinnerProps['size'] -) { - return (props: T) => ( - }> - {/* @ts-expect-error upgrade typescript v4.9.5 */} - - - ); -} - -export const SloAddFormFlyout = suspendedComponentWithProps( - lazy(() => import('./slo_add_form_flyout')) -); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/slo_edit.test.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/slo_edit.test.tsx index f5acb4e964f08..abc60d6a00352 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/slo_edit.test.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/slo_edit.test.tsx @@ -25,7 +25,7 @@ import { useFetchSloDetails } from '../../hooks/use_fetch_slo_details'; import { usePermissions } from '../../hooks/use_permissions'; import { useCreateRule } from '../../hooks/use_create_burn_rate_rule'; import { useUpdateSlo } from '../../hooks/use_update_slo'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { kibanaStartMock } from '../../utils/kibana_react.mock'; import { render } from '../../utils/test_helper'; import { SLO_EDIT_FORM_DEFAULT_VALUES } from './constants'; @@ -49,7 +49,7 @@ jest.mock('../../hooks/use_create_burn_rate_rule'); const mockUseKibanaReturnValue = kibanaStartMock.startContract(); -jest.mock('../../utils/kibana_react', () => ({ +jest.mock('../../hooks/use_kibana', () => ({ useKibana: jest.fn(() => mockUseKibanaReturnValue), })); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/slo_edit.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/slo_edit.tsx index 7dcce93c0d003..b014bdb1d6dec 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/slo_edit.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/slo_edit.tsx @@ -15,7 +15,7 @@ import { useFetchSloDetails } from '../../hooks/use_fetch_slo_details'; import { useLicense } from '../../hooks/use_license'; import { usePermissions } from '../../hooks/use_permissions'; import { usePluginContext } from '../../hooks/use_plugin_context'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { SloEditForm } from './components/slo_edit_form'; export function SloEditPage() { diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_outdated_definitions/index.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_outdated_definitions/index.tsx index 5a35061b464e5..edd26e579b2a1 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_outdated_definitions/index.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_outdated_definitions/index.tsx @@ -15,7 +15,7 @@ import { useFetchSloDefinitions } from '../../hooks/use_fetch_slo_definitions'; import { useLicense } from '../../hooks/use_license'; import { usePermissions } from '../../hooks/use_permissions'; import { usePluginContext } from '../../hooks/use_plugin_context'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { SloListEmpty } from '../slos/components/slo_list_empty'; import { OutdatedSlo } from './outdated_slo'; import { OutdatedSloSearchBar } from './outdated_slo_search_bar'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/use_get_settings.ts b/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/hooks/use_get_settings.ts similarity index 75% rename from x-pack/plugins/observability_solution/slo/public/pages/slo_settings/use_get_settings.ts rename to x-pack/plugins/observability_solution/slo/public/pages/slo_settings/hooks/use_get_settings.ts index 88d38bc7f936d..eb8d9642790cd 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/use_get_settings.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/hooks/use_get_settings.ts @@ -7,16 +7,16 @@ import { GetSLOSettingsResponse } from '@kbn/slo-schema'; import { useQuery } from '@tanstack/react-query'; -import { DEFAULT_STALE_SLO_THRESHOLD_HOURS } from '../../../common/constants'; -import { useKibana } from '../../utils/kibana_react'; +import { DEFAULT_STALE_SLO_THRESHOLD_HOURS } from '../../../../common/constants'; +import { usePluginContext } from '../../../hooks/use_plugin_context'; export const useGetSettings = () => { - const { http } = useKibana().services; + const { sloClient } = usePluginContext(); const { isLoading, data } = useQuery({ queryKey: ['getSloSettings'], queryFn: async ({ signal }) => { try { - return http.get('/internal/slo/settings', { signal }); + return await sloClient.fetch('GET /internal/slo/settings', { signal }); } catch (error) { return defaultSettings; } diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/use_put_slo_settings.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/hooks/use_put_slo_settings.tsx similarity index 81% rename from x-pack/plugins/observability_solution/slo/public/pages/slo_settings/use_put_slo_settings.tsx rename to x-pack/plugins/observability_solution/slo/public/pages/slo_settings/hooks/use_put_slo_settings.tsx index 48c9a54eea295..e62204d0abb6d 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/use_put_slo_settings.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/hooks/use_put_slo_settings.tsx @@ -9,8 +9,9 @@ import { IHttpFetchError, ResponseErrorBody } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; import { PutSLOSettingsParams, PutSLOSettingsResponse } from '@kbn/slo-schema'; import { useMutation } from '@tanstack/react-query'; -import { paths } from '../../../common/locators/paths'; -import { useKibana } from '../../utils/kibana_react'; +import { paths } from '../../../../common/locators/paths'; +import { usePluginContext } from '../../../hooks/use_plugin_context'; +import { useKibana } from '../../../hooks/use_kibana'; type ServerError = IHttpFetchError; @@ -20,12 +21,14 @@ export function usePutSloSettings() { http, notifications: { toasts }, } = useKibana().services; + const { sloClient } = usePluginContext(); return useMutation( ['putSloSettings'], ({ settings }) => { - const body = JSON.stringify(settings); - return http.put(`/internal/slo/settings`, { body }); + return sloClient.fetch(`PUT /internal/slo/settings`, { + params: { body: settings }, + }); }, { onSuccess: (data, { settings }) => { diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/settings_form.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/settings_form.tsx index 895ca2c0f8e2b..c6910bf53810d 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/settings_form.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/settings_form.tsx @@ -7,25 +7,25 @@ import { i18n } from '@kbn/i18n'; import { - EuiForm, - EuiFormRow, - EuiSwitch, - EuiDescribedFormGroup, + EuiButton, + EuiButtonEmpty, EuiComboBox, + EuiDescribedFormGroup, + EuiFieldNumber, EuiFlexGroup, EuiFlexItem, - EuiButtonEmpty, - EuiButton, + EuiForm, + EuiFormRow, EuiSpacer, - EuiFieldNumber, + EuiSwitch, } from '@elastic/eui'; -import React, { useEffect, useState } from 'react'; -import { useFetcher } from '@kbn/observability-shared-plugin/public'; import { useKibana } from '@kbn/kibana-react-plugin/public'; +import { useFetcher } from '@kbn/observability-shared-plugin/public'; import { isEqual } from 'lodash'; +import React, { useEffect, useState } from 'react'; import { DEFAULT_STALE_SLO_THRESHOLD_HOURS } from '../../../common/constants'; -import { useGetSettings } from './use_get_settings'; -import { usePutSloSettings } from './use_put_slo_settings'; +import { useGetSettings } from './hooks/use_get_settings'; +import { usePutSloSettings } from './hooks/use_put_slo_settings'; export function SettingsForm() { const [useAllRemoteClusters, setUseAllRemoteClusters] = useState(false); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/slo_settings.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/slo_settings.tsx index ca41c7561fb46..5c3ae879058ce 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/slo_settings.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slo_settings/slo_settings.tsx @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { useBreadcrumbs } from '@kbn/observability-shared-plugin/public'; import { SettingsForm } from './settings_form'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { usePluginContext } from '../../hooks/use_plugin_context'; import { paths } from '../../../common/locators/paths'; import { HeaderMenu } from '../../components/header_menu/header_menu'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/badges/slo_indicator_type_badge.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/badges/slo_indicator_type_badge.tsx index a721499e9ef01..e8368f96a6d34 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/badges/slo_indicator_type_badge.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/badges/slo_indicator_type_badge.tsx @@ -17,7 +17,7 @@ import { euiLightVars } from '@kbn/ui-theme'; import React, { MouseEvent } from 'react'; import { useRouteMatch } from 'react-router-dom'; import { SLOS_PATH } from '../../../../../common/locators/paths'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { convertSliApmParamsToApmAppDeeplinkUrl } from '../../../../utils/slo/convert_sli_apm_params_to_apm_app_deeplink_url'; import { toIndicatorTypeLabel } from '../../../../utils/slo/labels'; import { useUrlSearchState } from '../../hooks/use_url_search_state'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/card_view/slo_card_item.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/card_view/slo_card_item.tsx index fe274cdabd6a7..7800337be79ae 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/card_view/slo_card_item.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/card_view/slo_card_item.tsx @@ -22,7 +22,7 @@ import { SloDeleteModal } from '../../../../components/slo/delete_confirmation_m import { SloResetConfirmationModal } from '../../../../components/slo/reset_confirmation_modal/slo_reset_confirmation_modal'; import { useResetSlo } from '../../../../hooks/use_reset_slo'; import { BurnRateRuleParams } from '../../../../typings'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { formatHistoricalData } from '../../../../utils/slo/chart_data_formatter'; import { useSloListActions } from '../../hooks/use_slo_list_actions'; import { useSloFormattedSummary } from '../../hooks/use_slo_summary'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/burn_rate_rule_flyout.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/burn_rate_rule_flyout.tsx index 609e4d02cd19a..f8e6890483404 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/burn_rate_rule_flyout.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/burn_rate_rule_flyout.tsx @@ -11,7 +11,7 @@ import { useQueryClient } from '@tanstack/react-query'; import { SLO_BURN_RATE_RULE_TYPE_ID } from '@kbn/rule-data-utils'; import { sloFeatureId } from '@kbn/observability-plugin/common'; import { useGetFilteredRuleTypes } from '../../../../hooks/use_get_filtered_rule_types'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { paths } from '../../../../../common/locators/paths'; import { sloKeys } from '../../../../hooks/query_key_factory'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/create_slo_btn.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/create_slo_btn.tsx index 7add8debe165b..843ae5f268f49 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/create_slo_btn.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/create_slo_btn.tsx @@ -8,7 +8,7 @@ import { EuiButton } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { paths } from '../../../../../common/locators/paths'; import { usePermissions } from '../../../../hooks/use_permissions'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/edit_burn_rate_rule_flyout.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/edit_burn_rate_rule_flyout.tsx index 1a8577e4a83fe..89701b0922f87 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/edit_burn_rate_rule_flyout.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/common/edit_burn_rate_rule_flyout.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { Rule } from '@kbn/triggers-actions-ui-plugin/public'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { BurnRateRuleParams } from '../../../../typings'; export function EditBurnRateRuleFlyout({ diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/compact_view/slo_list_compact_view.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/compact_view/slo_list_compact_view.tsx index 0d556c0546e1f..03fbb0174f303 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/compact_view/slo_list_compact_view.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/compact_view/slo_list_compact_view.tsx @@ -36,7 +36,7 @@ import { useGetFilteredRuleTypes } from '../../../../hooks/use_get_filtered_rule import { usePermissions } from '../../../../hooks/use_permissions'; import { useResetSlo } from '../../../../hooks/use_reset_slo'; import { useSpace } from '../../../../hooks/use_space'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { formatHistoricalData } from '../../../../utils/slo/chart_data_formatter'; import { createRemoteSloDeleteUrl, diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/grouped_slos/group_list_view.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/grouped_slos/group_list_view.tsx index 8342c9aa5976b..a433b57073e3b 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/grouped_slos/group_list_view.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/grouped_slos/group_list_view.tsx @@ -26,7 +26,7 @@ import { GroupSummary } from '@kbn/slo-schema'; import React, { memo, useState } from 'react'; import { paths } from '../../../../../common/locators/paths'; import { useFetchSloList } from '../../../../hooks/use_fetch_slo_list'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { useSloFormattedSLIValue } from '../../hooks/use_slo_summary'; import type { SortDirection, SortField } from '../../hooks/use_url_search_state'; import { SlosView } from '../slos_view'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/health_callout/health_callout.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/health_callout/health_callout.tsx index ce956b00a8170..c4befdfe6b92f 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/health_callout/health_callout.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/health_callout/health_callout.tsx @@ -20,7 +20,7 @@ import { SLOWithSummaryResponse } from '@kbn/slo-schema'; import React, { useState } from 'react'; import { getSLOSummaryTransformId, getSLOTransformId } from '../../../../../common/constants'; import { useFetchSloHealth } from '../../../../hooks/use_fetch_slo_health'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; const CALLOUT_SESSION_STORAGE_KEY = 'slo_health_callout_hidden'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_item_actions.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_item_actions.tsx index 1332a78c1e484..1a99f8ff354d9 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_item_actions.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_item_actions.tsx @@ -22,7 +22,7 @@ import styled from 'styled-components'; import { usePermissions } from '../../../hooks/use_permissions'; import { useCloneSlo } from '../../../hooks/use_clone_slo'; import { BurnRateRuleParams } from '../../../typings'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { useSloActions } from '../../slo_details/hooks/use_slo_actions'; interface Props { diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list.tsx index 0fad1e96975ea..f0fec063ad23e 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list.tsx @@ -13,7 +13,7 @@ import dedent from 'dedent'; import { groupBy as _groupBy, mapValues } from 'lodash'; import React, { useEffect } from 'react'; import { useFetchSloList } from '../../../hooks/use_fetch_slo_list'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { useUrlSearchState } from '../hooks/use_url_search_state'; import { GroupView } from './grouped_slos/group_view'; import { ToggleSLOView } from './toggle_slo_view'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list_group_by.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list_group_by.tsx index d7175553fd178..7223f91d49519 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list_group_by.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list_group_by.tsx @@ -8,7 +8,7 @@ import { EuiPanel, EuiSelectableOption, EuiText } from '@elastic/eui'; import { EuiSelectableOptionCheckedType } from '@elastic/eui/src/components/selectable/selectable_option'; import { i18n } from '@kbn/i18n'; import React, { useState } from 'react'; -import { useGetSettings } from '../../slo_settings/use_get_settings'; +import { useGetSettings } from '../../slo_settings/hooks/use_get_settings'; import type { SearchState } from '../hooks/use_url_search_state'; import type { Option } from './slo_context_menu'; import { ContextMenuItem, SLOContextMenu } from './slo_context_menu'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list_search_bar.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list_search_bar.tsx index 69cc895121d01..16c635a2da20c 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list_search_bar.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_list_search_bar.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { observabilityAppId } from '@kbn/observability-plugin/public'; import React, { useEffect } from 'react'; import styled from 'styled-components'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { useSloCrudLoading } from '../hooks/use_crud_loading'; import { useSloSummaryDataView } from '../hooks/use_summary_dataview'; import { useUrlSearchState } from '../hooks/use_url_search_state'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_sparkline.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_sparkline.tsx index d00152e425dfd..1315e2b6c829a 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_sparkline.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slo_sparkline.tsx @@ -20,7 +20,7 @@ import React from 'react'; import { EuiLoadingChart, useEuiTheme } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; interface Data { key: number; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slos_overview/slo_overview_alerts.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slos_overview/slo_overview_alerts.tsx index 808c9096a3793..9fba8b59bef4a 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slos_overview/slo_overview_alerts.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slos_overview/slo_overview_alerts.tsx @@ -11,7 +11,7 @@ import React from 'react'; import { GetOverviewResponse } from '@kbn/slo-schema/src/rest_specs/routes/get_overview'; import { rulesLocatorID, RulesParams } from '@kbn/observability-plugin/public'; import { useAlertsUrl } from '../../../../hooks/use_alerts_url'; -import { useKibana } from '../../../../utils/kibana_react'; +import { useKibana } from '../../../../hooks/use_kibana'; import { OverViewItem } from './overview_item'; export function SLOOverviewAlerts({ diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slos_overview/slos_overview.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slos_overview/slos_overview.tsx index ab551637a6f25..42c0d199db788 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slos_overview/slos_overview.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/components/slos_overview/slos_overview.tsx @@ -17,7 +17,7 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; import { DEFAULT_STALE_SLO_THRESHOLD_HOURS } from '../../../../../common/constants'; import { SLOOverviewAlerts } from './slo_overview_alerts'; -import { useGetSettings } from '../../../slo_settings/use_get_settings'; +import { useGetSettings } from '../../../slo_settings/hooks/use_get_settings'; import { useFetchSLOsOverview } from '../../hooks/use_fetch_slos_overview'; import { useUrlSearchState } from '../../hooks/use_url_search_state'; import { OverViewItem } from './overview_item'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_fetch_slos_overview.ts b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_fetch_slos_overview.ts index 783c23d49a42b..1e9246d97f795 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_fetch_slos_overview.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_fetch_slos_overview.ts @@ -4,15 +4,16 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { useQuery } from '@tanstack/react-query'; -import { i18n } from '@kbn/i18n'; import { buildQueryFromFilters, Filter } from '@kbn/es-query'; -import { useMemo } from 'react'; +import { i18n } from '@kbn/i18n'; import { GetOverviewResponse } from '@kbn/slo-schema/src/rest_specs/routes/get_overview'; -import { sloKeys } from '../../../hooks/query_key_factory'; +import { useQuery } from '@tanstack/react-query'; +import { useMemo } from 'react'; import { SLO_SUMMARY_DESTINATION_INDEX_PATTERN } from '../../../../common/constants'; +import { sloKeys } from '../../../hooks/query_key_factory'; import { useCreateDataView } from '../../../hooks/use_create_data_view'; -import { useKibana } from '../../../utils/kibana_react'; +import { usePluginContext } from '../../../hooks/use_plugin_context'; +import { useKibana } from '../../../hooks/use_kibana'; import { SearchState } from './use_url_search_state'; interface SLOsOverviewParams { @@ -38,8 +39,8 @@ export function useFetchSLOsOverview({ filters: filterDSL = [], lastRefresh, }: SLOsOverviewParams = {}): UseFetchSloGroupsResponse { + const { sloClient } = usePluginContext(); const { - http, notifications: { toasts }, } = useKibana().services; @@ -73,10 +74,12 @@ export function useFetchSLOsOverview({ lastRefresh, }), queryFn: async ({ signal }) => { - return await http.get('/internal/observability/slos/overview', { - query: { - ...(kqlQuery && { kqlQuery }), - ...(filters && { filters }), + return await sloClient.fetch('GET /internal/observability/slos/overview', { + params: { + query: { + ...(kqlQuery && { kqlQuery }), + ...(filters && { filters }), + }, }, signal, }); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_slo_list_actions.ts b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_slo_list_actions.ts index 2d7d8b7d9a97f..d339c1e66bf00 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_slo_list_actions.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_slo_list_actions.ts @@ -8,7 +8,7 @@ import { SaveModalDashboardProps } from '@kbn/presentation-util-plugin/public'; import { SLOWithSummaryResponse } from '@kbn/slo-schema'; import { useCallback } from 'react'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { SLO_OVERVIEW_EMBEDDABLE_ID } from '../../../embeddable/slo/overview/constants'; export function useSloListActions({ diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_slo_summary.ts b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_slo_summary.ts index d2811774e59aa..0ad95a4408ab8 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_slo_summary.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_slo_summary.ts @@ -9,7 +9,7 @@ import numeral from '@elastic/numeral'; import { ALL_VALUE, SLOWithSummaryResponse } from '@kbn/slo-schema'; import { IBasePath } from '@kbn/core-http-browser'; import { IUiSettingsClient } from '@kbn/core-ui-settings-browser'; -import { useKibana } from '../../../utils/kibana_react'; +import { useKibana } from '../../../hooks/use_kibana'; import { paths } from '../../../../common/locators/paths'; import { NOT_AVAILABLE_LABEL } from '../../../../common/i18n'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_summary_dataview.ts b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_summary_dataview.ts index 3d502cfe85ec7..ab5664ee49b43 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_summary_dataview.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_summary_dataview.ts @@ -9,8 +9,8 @@ import { useFetcher } from '@kbn/observability-shared-plugin/public'; import { useEffect, useState } from 'react'; import { getListOfSloSummaryIndices } from '../../../../common/summary_indices'; import { useCreateDataView } from '../../../hooks/use_create_data_view'; -import { useKibana } from '../../../utils/kibana_react'; -import { useGetSettings } from '../../slo_settings/use_get_settings'; +import { useKibana } from '../../../hooks/use_kibana'; +import { useGetSettings } from '../../slo_settings/hooks/use_get_settings'; export const useSloSummaryDataView = () => { const { http } = useKibana().services; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_url_search_state.ts b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_url_search_state.ts index 59284ee617919..5da3b4596ed71 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_url_search_state.ts +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/hooks/use_url_search_state.ts @@ -5,11 +5,11 @@ * 2.0. */ +import type { Filter } from '@kbn/es-query'; import { createKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public'; import deepmerge from 'deepmerge'; -import { useHistory } from 'react-router-dom'; -import { Filter } from '@kbn/es-query'; import { useCallback, useEffect, useRef, useState } from 'react'; +import { useHistory } from 'react-router-dom'; import { DEFAULT_SLO_PAGE_SIZE } from '../../../../common/constants'; import type { GroupByField } from '../components/slo_list_group_by'; import type { SLOView } from '../components/toggle_slo_view'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/slos.test.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/slos.test.tsx index 905e6088ef74b..3a9c21c2ffa0e 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/slos.test.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/slos.test.tsx @@ -25,9 +25,9 @@ import { useFetchHistoricalSummary } from '../../hooks/use_fetch_historical_summ import { useFetchSloList } from '../../hooks/use_fetch_slo_list'; import { useLicense } from '../../hooks/use_license'; import { usePermissions } from '../../hooks/use_permissions'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { render } from '../../utils/test_helper'; -import { useGetSettings } from '../slo_settings/use_get_settings'; +import { useGetSettings } from '../slo_settings/hooks/use_get_settings'; import { SlosPage } from './slos'; jest.mock('react-router-dom', () => ({ @@ -36,11 +36,11 @@ jest.mock('react-router-dom', () => ({ })); jest.mock('@kbn/observability-shared-plugin/public'); -jest.mock('../../utils/kibana_react'); +jest.mock('../../hooks/use_kibana'); jest.mock('../../hooks/use_license'); jest.mock('../../hooks/use_fetch_slo_list'); jest.mock('../../hooks/use_create_slo'); -jest.mock('../slo_settings/use_get_settings'); +jest.mock('../slo_settings/hooks/use_get_settings'); jest.mock('../../hooks/use_delete_slo'); jest.mock('../../hooks/use_delete_slo_instance'); jest.mock('../../hooks/use_fetch_historical_summary'); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos/slos.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos/slos.tsx index ba23f7af34c3d..ebc0dbb39c192 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos/slos.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos/slos.tsx @@ -17,7 +17,7 @@ import { useFetchSloList } from '../../hooks/use_fetch_slo_list'; import { useLicense } from '../../hooks/use_license'; import { usePermissions } from '../../hooks/use_permissions'; import { usePluginContext } from '../../hooks/use_plugin_context'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { CreateSloBtn } from './components/common/create_slo_btn'; import { FeedbackButton } from './components/common/feedback_button'; import { SloList } from './components/slo_list'; diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos_welcome/slos_welcome.test.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos_welcome/slos_welcome.test.tsx index 07676d1cbe4a3..369a1fbeed932 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos_welcome/slos_welcome.test.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos_welcome/slos_welcome.test.tsx @@ -14,7 +14,7 @@ import { emptySloList, sloList } from '../../data/slo/slo'; import { usePermissions } from '../../hooks/use_permissions'; import { useFetchSloList } from '../../hooks/use_fetch_slo_list'; import { useLicense } from '../../hooks/use_license'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import { render } from '../../utils/test_helper'; import { SlosWelcomePage } from './slos_welcome'; import { HeaderMenuPortal } from '@kbn/observability-shared-plugin/public'; @@ -25,7 +25,7 @@ jest.mock('react-router-dom', () => ({ })); jest.mock('@kbn/observability-shared-plugin/public'); -jest.mock('../../utils/kibana_react'); +jest.mock('../../hooks/use_kibana'); jest.mock('../../hooks/use_license'); jest.mock('../../hooks/use_fetch_slo_list'); jest.mock('../../hooks/use_permissions'); diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slos_welcome/slos_welcome.tsx b/x-pack/plugins/observability_solution/slo/public/pages/slos_welcome/slos_welcome.tsx index fc03009beb72e..ccb273aad913e 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slos_welcome/slos_welcome.tsx +++ b/x-pack/plugins/observability_solution/slo/public/pages/slos_welcome/slos_welcome.tsx @@ -25,7 +25,7 @@ import { useFetchSloList } from '../../hooks/use_fetch_slo_list'; import { useLicense } from '../../hooks/use_license'; import { usePermissions } from '../../hooks/use_permissions'; import { usePluginContext } from '../../hooks/use_plugin_context'; -import { useKibana } from '../../utils/kibana_react'; +import { useKibana } from '../../hooks/use_kibana'; import illustration from './assets/illustration.svg'; export function SlosWelcomePage() { diff --git a/x-pack/plugins/observability_solution/slo/public/plugin.ts b/x-pack/plugins/observability_solution/slo/public/plugin.ts index a21a7716fc984..8711ca80ac9ce 100644 --- a/x-pack/plugins/observability_solution/slo/public/plugin.ts +++ b/x-pack/plugins/observability_solution/slo/public/plugin.ts @@ -14,10 +14,13 @@ import { Plugin, PluginInitializerContext, } from '@kbn/core/public'; +import { DefaultClientOptions, createRepositoryClient } from '@kbn/server-route-repository-client'; +import { lazy } from 'react'; import { BehaviorSubject, firstValueFrom } from 'rxjs'; import { PLUGIN_NAME, sloAppId } from '../common'; -import { ExperimentalFeatures, SloConfig } from '../common/config'; +import { ExperimentalFeatures, SLOConfig } from '../common/config'; import { SLOS_BASE_PATH } from '../common/locators/paths'; +import type { SLORouteRepository } from '../server/routes/get_slo_server_route_repository'; import { SLO_ALERTS_EMBEDDABLE_ID } from './embeddable/slo/alerts/constants'; import { SLO_BURN_RATE_EMBEDDABLE_ID } from './embeddable/slo/burn_rate/constants'; import { SLO_ERROR_BUDGET_ID } from './embeddable/slo/error_budget/constants'; @@ -26,37 +29,41 @@ import { SloOverviewEmbeddableState } from './embeddable/slo/overview/types'; import { SloDetailsLocatorDefinition } from './locators/slo_details'; import { SloEditLocatorDefinition } from './locators/slo_edit'; import { SloListLocatorDefinition } from './locators/slo_list'; -import { getCreateSLOFlyoutLazy } from './pages/slo_edit/shared_flyout/get_create_slo_flyout'; import { registerBurnRateRuleType } from './rules/register_burn_rate_rule_type'; -import type { SloPublicSetup, SloPublicStart } from './types'; -import { SloPublicPluginsSetup, SloPublicPluginsStart } from './types'; - -export class SloPlugin - implements Plugin +import type { + SLOPublicPluginsSetup, + SLOPublicPluginsStart, + SLOPublicSetup, + SLOPublicStart, +} from './types'; +import { getLazyWithContextProviders } from './utils/get_lazy_with_context_providers'; + +export class SLOPlugin + implements Plugin { private readonly appUpdater$ = new BehaviorSubject(() => ({})); private experimentalFeatures: ExperimentalFeatures = { ruleFormV2: { enabled: false } }; - constructor(private readonly initContext: PluginInitializerContext) { + constructor(private readonly initContext: PluginInitializerContext) { this.experimentalFeatures = this.initContext.config.get().experimental ?? this.experimentalFeatures; } public setup( - coreSetup: CoreSetup, - pluginsSetup: SloPublicPluginsSetup + core: CoreSetup, + plugins: SLOPublicPluginsSetup ) { const kibanaVersion = this.initContext.env.packageInfo.version; - const sloDetailsLocator = pluginsSetup.share.url.locators.create( - new SloDetailsLocatorDefinition() - ); - const sloEditLocator = pluginsSetup.share.url.locators.create(new SloEditLocatorDefinition()); - const sloListLocator = pluginsSetup.share.url.locators.create(new SloListLocatorDefinition()); + const sloClient = createRepositoryClient(core); + + const sloDetailsLocator = plugins.share.url.locators.create(new SloDetailsLocatorDefinition()); + const sloEditLocator = plugins.share.url.locators.create(new SloEditLocatorDefinition()); + const sloListLocator = plugins.share.url.locators.create(new SloListLocatorDefinition()); const mount = async (params: AppMountParameters) => { const { renderApp } = await import('./application'); - const [coreStart, pluginsStart] = await coreSetup.getStartServices(); + const [coreStart, pluginsStart] = await core.getStartServices(); const { observabilityRuleTypeRegistry } = pluginsStart.observability; return renderApp({ @@ -65,11 +72,12 @@ export class SloPlugin isDev: this.initContext.env.mode.dev, observabilityRuleTypeRegistry, kibanaVersion, - usageCollection: pluginsSetup.usageCollection, + usageCollection: plugins.usageCollection, ObservabilityPageTemplate: pluginsStart.observabilityShared.navigation.PageTemplate, plugins: pluginsStart, isServerless: !!pluginsStart.serverless, experimentalFeatures: this.experimentalFeatures, + sloClient, }); }; const appUpdater$ = this.appUpdater$; @@ -85,17 +93,36 @@ export class SloPlugin keywords: ['observability', 'monitor', 'slos'], }; // Register an application into the side navigation menu - coreSetup.application.register(app); + core.application.register(app); - registerBurnRateRuleType(pluginsSetup.observability.observabilityRuleTypeRegistry); + const registerRules = async () => { + const [coreStart, pluginsStart] = await core.getStartServices(); + const lazyWithContextProviders = getLazyWithContextProviders({ + core: coreStart, + isDev: this.initContext.env.mode.dev, + kibanaVersion, + observabilityRuleTypeRegistry: pluginsStart.observability.observabilityRuleTypeRegistry, + ObservabilityPageTemplate: pluginsStart.observabilityShared.navigation.PageTemplate, + plugins: pluginsStart, + isServerless: !!plugins.serverless, + experimentalFeatures: this.experimentalFeatures, + sloClient, + }); - const assertPlatinumLicense = async () => { - const licensing = pluginsSetup.licensing; + registerBurnRateRuleType( + plugins.observability.observabilityRuleTypeRegistry, + lazyWithContextProviders + ); + }; + registerRules(); + + const registerEmbeddables = async () => { + const licensing = plugins.licensing; const license = await firstValueFrom(licensing.license$); const hasPlatinumLicense = license.hasAtLeast('platinum'); if (hasPlatinumLicense) { - const [coreStart, pluginsStart] = await coreSetup.getStartServices(); + const [coreStart, pluginsStart] = await core.getStartServices(); pluginsStart.dashboard.registerDashboardPanelPlacementSetting( SLO_OVERVIEW_EMBEDDABLE_ID, @@ -106,66 +133,61 @@ export class SloPlugin return { width: 12, height: 8 }; } ); - - pluginsSetup.embeddable.registerReactEmbeddableFactory( - SLO_OVERVIEW_EMBEDDABLE_ID, - async () => { - const { getOverviewEmbeddableFactory } = await import( - './embeddable/slo/overview/slo_embeddable_factory' - ); - return getOverviewEmbeddableFactory(coreSetup.getStartServices); + pluginsStart.dashboard.registerDashboardPanelPlacementSetting( + SLO_BURN_RATE_EMBEDDABLE_ID, + () => { + return { width: 14, height: 7 }; } ); - pluginsSetup.embeddable.registerReactEmbeddableFactory( - SLO_ALERTS_EMBEDDABLE_ID, - async () => { - const { getAlertsEmbeddableFactory } = await import( - './embeddable/slo/alerts/slo_alerts_embeddable_factory' - ); + plugins.embeddable.registerReactEmbeddableFactory(SLO_OVERVIEW_EMBEDDABLE_ID, async () => { + const { getOverviewEmbeddableFactory } = await import( + './embeddable/slo/overview/slo_embeddable_factory' + ); + return getOverviewEmbeddableFactory({ coreStart, pluginsStart, sloClient }); + }); - return getAlertsEmbeddableFactory(coreSetup.getStartServices, kibanaVersion); - } - ); + plugins.embeddable.registerReactEmbeddableFactory(SLO_ALERTS_EMBEDDABLE_ID, async () => { + const { getAlertsEmbeddableFactory } = await import( + './embeddable/slo/alerts/slo_alerts_embeddable_factory' + ); - pluginsSetup.embeddable.registerReactEmbeddableFactory(SLO_ERROR_BUDGET_ID, async () => { - const deps = { ...coreStart, ...pluginsStart }; + return getAlertsEmbeddableFactory({ coreStart, pluginsStart, sloClient, kibanaVersion }); + }); + plugins.embeddable.registerReactEmbeddableFactory(SLO_ERROR_BUDGET_ID, async () => { const { getErrorBudgetEmbeddableFactory } = await import( './embeddable/slo/error_budget/error_budget_react_embeddable_factory' ); - return getErrorBudgetEmbeddableFactory(deps); + return getErrorBudgetEmbeddableFactory({ + coreStart, + pluginsStart, + sloClient, + }); }); - pluginsStart.dashboard.registerDashboardPanelPlacementSetting( - SLO_BURN_RATE_EMBEDDABLE_ID, - () => { - return { width: 14, height: 7 }; - } - ); - pluginsSetup.embeddable.registerReactEmbeddableFactory( - SLO_BURN_RATE_EMBEDDABLE_ID, - async () => { - const deps = { ...coreStart, ...pluginsStart }; - - const { getBurnRateEmbeddableFactory } = await import( - './embeddable/slo/burn_rate/burn_rate_react_embeddable_factory' - ); - return getBurnRateEmbeddableFactory(deps); - } - ); + plugins.embeddable.registerReactEmbeddableFactory(SLO_BURN_RATE_EMBEDDABLE_ID, async () => { + const { getBurnRateEmbeddableFactory } = await import( + './embeddable/slo/burn_rate/burn_rate_react_embeddable_factory' + ); + return getBurnRateEmbeddableFactory({ + coreStart, + pluginsStart, + sloClient, + }); + }); const registerAsyncSloUiActions = async () => { - if (pluginsSetup.uiActions) { + if (plugins.uiActions) { const { registerSloUiActions } = await import('./ui_actions'); - registerSloUiActions(coreSetup, pluginsSetup, pluginsStart); + registerSloUiActions(plugins.uiActions, coreStart, pluginsStart, sloClient); } }; registerAsyncSloUiActions(); } }; - assertPlatinumLicense(); + registerEmbeddables(); return { sloDetailsLocator, @@ -174,27 +196,34 @@ export class SloPlugin }; } - public start(coreStart: CoreStart, pluginsStart: SloPublicPluginsStart) { + public start(core: CoreStart, plugins: SLOPublicPluginsStart) { const kibanaVersion = this.initContext.env.packageInfo.version; + const sloClient = createRepositoryClient(core); - const getCreateSLOFlyout = getCreateSLOFlyoutLazy({ - core: coreStart, + const lazyWithContextProviders = getLazyWithContextProviders({ + core, isDev: this.initContext.env.mode.dev, kibanaVersion, - observabilityRuleTypeRegistry: pluginsStart.observability.observabilityRuleTypeRegistry, - ObservabilityPageTemplate: pluginsStart.observabilityShared.navigation.PageTemplate, - plugins: pluginsStart, - isServerless: !!pluginsStart.serverless, + observabilityRuleTypeRegistry: plugins.observability.observabilityRuleTypeRegistry, + ObservabilityPageTemplate: plugins.observabilityShared.navigation.PageTemplate, + plugins, + isServerless: !!plugins.serverless, experimentalFeatures: this.experimentalFeatures, + sloClient, }); - pluginsStart.discoverShared.features.registry.register({ + const createSLOFlyout = lazyWithContextProviders( + lazy(() => import('./pages/slo_edit/shared_flyout/slo_add_form_flyout')), + { spinnerSize: 'm' } + ); + + plugins.discoverShared.features.registry.register({ id: 'observability-create-slo', - createSLOFlyout: getCreateSLOFlyout, + createSLOFlyout, }); return { - getCreateSLOFlyout, + getCreateSLOFlyout: createSLOFlyout, }; } diff --git a/x-pack/plugins/observability_solution/slo/public/rules/register_burn_rate_rule_type.ts b/x-pack/plugins/observability_solution/slo/public/rules/register_burn_rate_rule_type.ts index f843809543620..5861e5ffd9032 100644 --- a/x-pack/plugins/observability_solution/slo/public/rules/register_burn_rate_rule_type.ts +++ b/x-pack/plugins/observability_solution/slo/public/rules/register_burn_rate_rule_type.ts @@ -5,13 +5,13 @@ * 2.0. */ -import { lazy } from 'react'; import { i18n } from '@kbn/i18n'; -import { ALERT_REASON } from '@kbn/rule-data-utils'; import { ObservabilityRuleTypeRegistry } from '@kbn/observability-plugin/public/rules/create_observability_rule_type_registry'; -import { SLO_BURN_RATE_RULE_TYPE_ID } from '@kbn/rule-data-utils'; +import { ALERT_REASON, SLO_BURN_RATE_RULE_TYPE_ID } from '@kbn/rule-data-utils'; +import { lazy } from 'react'; import { SLO_ID_FIELD, SLO_INSTANCE_ID_FIELD } from '../../common/field_names/slo'; import { validateBurnRateRule } from '../components/burn_rate_rule_editor/validation'; +import { LazyWithContextProviders } from '../utils/get_lazy_with_context_providers'; const sloBurnRateDefaultActionMessage = i18n.translate( 'xpack.slo.rules.burnRate.defaultActionMessage', @@ -47,7 +47,8 @@ const sloBurnRateDefaultRecoveryMessage = i18n.translate( ); export const registerBurnRateRuleType = ( - observabilityRuleTypeRegistry: ObservabilityRuleTypeRegistry + observabilityRuleTypeRegistry: ObservabilityRuleTypeRegistry, + lazyWithContextProviders: LazyWithContextProviders ) => { observabilityRuleTypeRegistry.register({ id: SLO_BURN_RATE_RULE_TYPE_ID, @@ -71,8 +72,8 @@ export const registerBurnRateRuleType = ( requiresAppContext: false, defaultActionMessage: sloBurnRateDefaultActionMessage, defaultRecoveryMessage: sloBurnRateDefaultRecoveryMessage, - alertDetailsAppSection: lazy( - () => import('../components/slo/burn_rate/alert_details/alert_details_app_section') + alertDetailsAppSection: lazyWithContextProviders( + lazy(() => import('../components/slo/burn_rate/alert_details/alert_details_app_section')) ), priority: 100, }); diff --git a/x-pack/plugins/observability_solution/slo/public/types.ts b/x-pack/plugins/observability_solution/slo/public/types.ts index ba60f40872fbf..3c5e7f0e17946 100644 --- a/x-pack/plugins/observability_solution/slo/public/types.ts +++ b/x-pack/plugins/observability_solution/slo/public/types.ts @@ -4,7 +4,27 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ + +import { AiopsPluginStart } from '@kbn/aiops-plugin/public/types'; +import { CasesPublicStart } from '@kbn/cases-plugin/public'; +import type { ChartsPluginStart } from '@kbn/charts-plugin/public'; +import type { CloudStart } from '@kbn/cloud-plugin/public'; +import { DashboardStart } from '@kbn/dashboard-plugin/public'; +import type { DataPublicPluginSetup, DataPublicPluginStart } from '@kbn/data-plugin/public'; +import { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public'; +import { DataViewFieldEditorStart } from '@kbn/data-view-field-editor-plugin/public'; +import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; +import type { DiscoverStart } from '@kbn/discover-plugin/public'; import type { DiscoverSharedPublicStart } from '@kbn/discover-shared-plugin/public'; +import type { EmbeddableSetup, EmbeddableStart } from '@kbn/embeddable-plugin/public'; +import { FieldFormatsStart } from '@kbn/field-formats-plugin/public'; +import type { LensPublicStart } from '@kbn/lens-plugin/public'; +import type { LicensingPluginSetup } from '@kbn/licensing-plugin/public'; +import { LicensingPluginStart } from '@kbn/licensing-plugin/public'; +import { + ObservabilityAIAssistantPublicSetup, + ObservabilityAIAssistantPublicStart, +} from '@kbn/observability-ai-assistant-plugin/public'; import { ObservabilityPublicSetup, ObservabilityPublicStart, @@ -13,86 +33,69 @@ import type { ObservabilitySharedPluginSetup, ObservabilitySharedPluginStart, } from '@kbn/observability-shared-plugin/public'; -import { AiopsPluginStart } from '@kbn/aiops-plugin/public/types'; -import type { ChartsPluginStart } from '@kbn/charts-plugin/public'; -import { DashboardStart } from '@kbn/dashboard-plugin/public'; -import type { EmbeddableStart } from '@kbn/embeddable-plugin/public'; -import type { EmbeddableSetup } from '@kbn/embeddable-plugin/public'; +import type { PresentationUtilPluginStart } from '@kbn/presentation-util-plugin/public'; +import { DefaultClientOptions, RouteRepositoryClient } from '@kbn/server-route-repository-client'; +import { ServerlessPluginSetup, ServerlessPluginStart } from '@kbn/serverless/public'; +import { SharePluginSetup, SharePluginStart } from '@kbn/share-plugin/public'; +import { SpacesPluginStart } from '@kbn/spaces-plugin/public'; import type { TriggersAndActionsUIPublicPluginSetup, TriggersAndActionsUIPublicPluginStart, } from '@kbn/triggers-actions-ui-plugin/public'; -import type { LicensingPluginSetup } from '@kbn/licensing-plugin/public'; -import { SharePluginSetup, SharePluginStart } from '@kbn/share-plugin/public'; -import { LicensingPluginStart } from '@kbn/licensing-plugin/public'; -import type { UiActionsStart, UiActionsSetup } from '@kbn/ui-actions-plugin/public'; -import type { PresentationUtilPluginStart } from '@kbn/presentation-util-plugin/public'; -import { ServerlessPluginSetup, ServerlessPluginStart } from '@kbn/serverless/public'; -import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; -import type { DataPublicPluginSetup, DataPublicPluginStart } from '@kbn/data-plugin/public'; -import type { CloudStart } from '@kbn/cloud-plugin/public'; +import type { UiActionsSetup, UiActionsStart } from '@kbn/ui-actions-plugin/public'; +import { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public'; import type { UsageCollectionSetup, UsageCollectionStart, } from '@kbn/usage-collection-plugin/public'; -import { - ObservabilityAIAssistantPublicSetup, - ObservabilityAIAssistantPublicStart, -} from '@kbn/observability-ai-assistant-plugin/public'; -import { SpacesPluginStart } from '@kbn/spaces-plugin/public'; -import type { LensPublicStart } from '@kbn/lens-plugin/public'; -import { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public'; -import { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public'; -import { CasesPublicStart } from '@kbn/cases-plugin/public'; -import type { DiscoverStart } from '@kbn/discover-plugin/public'; -import { DataViewFieldEditorStart } from '@kbn/data-view-field-editor-plugin/public'; +import type { SLORouteRepository } from '../server/routes/get_slo_server_route_repository'; +import { SLOPlugin } from './plugin'; -import { FieldFormatsStart } from '@kbn/field-formats-plugin/public'; -import { SloPlugin } from './plugin'; +export type SLORepositoryClient = RouteRepositoryClient; -export interface SloPublicPluginsSetup { +export interface SLOPublicPluginsSetup { data: DataPublicPluginSetup; + embeddable: EmbeddableSetup; + licensing: LicensingPluginSetup; observability: ObservabilityPublicSetup; + observabilityAIAssistant?: ObservabilityAIAssistantPublicSetup; observabilityShared: ObservabilitySharedPluginSetup; - triggersActionsUi: TriggersAndActionsUIPublicPluginSetup; - licensing: LicensingPluginSetup; + presentationUtil: PresentationUtilPluginStart; + serverless?: ServerlessPluginSetup; share: SharePluginSetup; - embeddable: EmbeddableSetup; + triggersActionsUi: TriggersAndActionsUIPublicPluginSetup; uiActions: UiActionsSetup; - serverless?: ServerlessPluginSetup; - presentationUtil: PresentationUtilPluginStart; - observabilityAIAssistant?: ObservabilityAIAssistantPublicSetup; usageCollection: UsageCollectionSetup; } -export interface SloPublicPluginsStart { +export interface SLOPublicPluginsStart { aiops: AiopsPluginStart; cases: CasesPublicStart; + charts: ChartsPluginStart; cloud?: CloudStart; dashboard: DashboardStart; + data: DataPublicPluginStart; dataViewEditor: DataViewEditorStart; + dataViewFieldEditor: DataViewFieldEditorStart; + dataViews: DataViewsPublicPluginStart; + discover?: DiscoverStart; discoverShared: DiscoverSharedPublicStart; + embeddable: EmbeddableStart; fieldFormats: FieldFormatsStart; + lens: LensPublicStart; + licensing: LicensingPluginStart; observability: ObservabilityPublicStart; + observabilityAIAssistant?: ObservabilityAIAssistantPublicStart; observabilityShared: ObservabilitySharedPluginStart; - triggersActionsUi: TriggersAndActionsUIPublicPluginStart; - spaces?: SpacesPluginStart; - share: SharePluginStart; - licensing: LicensingPluginStart; - embeddable: EmbeddableStart; - uiActions: UiActionsStart; presentationUtil: PresentationUtilPluginStart; serverless?: ServerlessPluginStart; - data: DataPublicPluginStart; - dataViews: DataViewsPublicPluginStart; - observabilityAIAssistant?: ObservabilityAIAssistantPublicStart; - lens: LensPublicStart; - charts: ChartsPluginStart; + share: SharePluginStart; + spaces?: SpacesPluginStart; + triggersActionsUi: TriggersAndActionsUIPublicPluginStart; + uiActions: UiActionsStart; unifiedSearch: UnifiedSearchPublicPluginStart; usageCollection: UsageCollectionStart; - discover?: DiscoverStart; - dataViewFieldEditor: DataViewFieldEditorStart; } -export type SloPublicSetup = ReturnType; -export type SloPublicStart = ReturnType; +export type SLOPublicSetup = ReturnType; +export type SLOPublicStart = ReturnType; diff --git a/x-pack/plugins/observability_solution/slo/public/ui_actions/create_alerts_panel_action.tsx b/x-pack/plugins/observability_solution/slo/public/ui_actions/create_alerts_panel_action.tsx index 68e985d7d5580..7fb4f021329ee 100644 --- a/x-pack/plugins/observability_solution/slo/public/ui_actions/create_alerts_panel_action.tsx +++ b/x-pack/plugins/observability_solution/slo/public/ui_actions/create_alerts_panel_action.tsx @@ -4,23 +4,26 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ +import type { CoreStart } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; -import type { CoreSetup } from '@kbn/core/public'; +import { COMMON_OBSERVABILITY_GROUPING } from '@kbn/observability-shared-plugin/common'; import { apiIsPresentationContainer } from '@kbn/presentation-containers'; +import { EmbeddableApiContext } from '@kbn/presentation-publishing'; import { IncompatibleActionError, type UiActionsActionDefinition, } from '@kbn/ui-actions-plugin/public'; -import { EmbeddableApiContext } from '@kbn/presentation-publishing'; -import { COMMON_OBSERVABILITY_GROUPING } from '@kbn/observability-shared-plugin/common'; +import { SLOPublicPluginsStart } from '..'; import { ADD_SLO_ALERTS_ACTION_ID, SLO_ALERTS_EMBEDDABLE_ID, } from '../embeddable/slo/alerts/constants'; -import { SloPublicPluginsStart, SloPublicStart } from '..'; +import { SLORepositoryClient } from '../types'; export function createAddAlertsPanelAction( - getStartServices: CoreSetup['getStartServices'] + coreStart: CoreStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient ): UiActionsActionDefinition { return { id: ADD_SLO_ALERTS_ACTION_ID, @@ -32,12 +35,12 @@ export function createAddAlertsPanelAction( }, execute: async ({ embeddable }) => { if (!apiIsPresentationContainer(embeddable)) throw new IncompatibleActionError(); - const [coreStart, deps] = await getStartServices(); + try { const { openSloConfiguration } = await import( '../embeddable/slo/alerts/slo_alerts_open_configuration' ); - const initialState = await openSloConfiguration(coreStart, deps); + const initialState = await openSloConfiguration(coreStart, pluginsStart, sloClient); embeddable.addNewPanel( { panelType: SLO_ALERTS_EMBEDDABLE_ID, diff --git a/x-pack/plugins/observability_solution/slo/public/ui_actions/create_burn_rate_panel_action.tsx b/x-pack/plugins/observability_solution/slo/public/ui_actions/create_burn_rate_panel_action.tsx index 02490cf1bf7f8..c55dd85aa7027 100644 --- a/x-pack/plugins/observability_solution/slo/public/ui_actions/create_burn_rate_panel_action.tsx +++ b/x-pack/plugins/observability_solution/slo/public/ui_actions/create_burn_rate_panel_action.tsx @@ -4,23 +4,26 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { CoreSetup } from '@kbn/core/public'; +import type { CoreStart } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; +import { COMMON_OBSERVABILITY_GROUPING } from '@kbn/observability-shared-plugin/common'; import { apiIsPresentationContainer } from '@kbn/presentation-containers'; import { EmbeddableApiContext } from '@kbn/presentation-publishing'; import { IncompatibleActionError, type UiActionsActionDefinition, } from '@kbn/ui-actions-plugin/public'; -import { COMMON_OBSERVABILITY_GROUPING } from '@kbn/observability-shared-plugin/common'; -import { SloPublicPluginsStart, SloPublicStart } from '..'; +import { SLOPublicPluginsStart } from '..'; import { ADD_BURN_RATE_ACTION_ID, SLO_BURN_RATE_EMBEDDABLE_ID, } from '../embeddable/slo/burn_rate/constants'; +import { SLORepositoryClient } from '../types'; export function createBurnRatePanelAction( - getStartServices: CoreSetup['getStartServices'] + coreStart: CoreStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient ): UiActionsActionDefinition { return { id: ADD_BURN_RATE_ACTION_ID, @@ -32,12 +35,12 @@ export function createBurnRatePanelAction( }, execute: async ({ embeddable }) => { if (!apiIsPresentationContainer(embeddable)) throw new IncompatibleActionError(); - const [coreStart, deps] = await getStartServices(); + try { const { openConfiguration } = await import( '../embeddable/slo/burn_rate/open_configuration' ); - const initialState = await openConfiguration(coreStart, deps); + const initialState = await openConfiguration(coreStart, pluginsStart, sloClient); embeddable.addNewPanel( { panelType: SLO_BURN_RATE_EMBEDDABLE_ID, diff --git a/x-pack/plugins/observability_solution/slo/public/ui_actions/create_error_budget_action.tsx b/x-pack/plugins/observability_solution/slo/public/ui_actions/create_error_budget_action.tsx index 9ba0b7a7a8677..6d1c46094b3a2 100644 --- a/x-pack/plugins/observability_solution/slo/public/ui_actions/create_error_budget_action.tsx +++ b/x-pack/plugins/observability_solution/slo/public/ui_actions/create_error_budget_action.tsx @@ -5,21 +5,25 @@ * 2.0. */ import { i18n } from '@kbn/i18n'; -import type { CoreSetup } from '@kbn/core/public'; +import { COMMON_OBSERVABILITY_GROUPING } from '@kbn/observability-shared-plugin/common'; import { apiIsPresentationContainer } from '@kbn/presentation-containers'; +import { EmbeddableApiContext } from '@kbn/presentation-publishing'; import { IncompatibleActionError, type UiActionsActionDefinition, } from '@kbn/ui-actions-plugin/public'; -import { EmbeddableApiContext } from '@kbn/presentation-publishing'; -import { COMMON_OBSERVABILITY_GROUPING } from '@kbn/observability-shared-plugin/common'; +import { CoreStart } from '@kbn/core/public'; +import { SLOPublicPluginsStart } from '..'; import { ADD_SLO_ERROR_BUDGET_ACTION_ID, SLO_ERROR_BUDGET_ID, } from '../embeddable/slo/error_budget/constants'; -import { SloPublicPluginsStart, SloPublicStart } from '..'; +import { SLORepositoryClient } from '../types'; + export function createAddErrorBudgetPanelAction( - getStartServices: CoreSetup['getStartServices'] + coreStart: CoreStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient ): UiActionsActionDefinition { return { id: ADD_SLO_ERROR_BUDGET_ACTION_ID, @@ -31,12 +35,11 @@ export function createAddErrorBudgetPanelAction( }, execute: async ({ embeddable }) => { if (!apiIsPresentationContainer(embeddable)) throw new IncompatibleActionError(); - const [coreStart, deps] = await getStartServices(); try { const { openSloConfiguration } = await import( '../embeddable/slo/error_budget/error_budget_open_configuration' ); - const initialState = await openSloConfiguration(coreStart, deps); + const initialState = await openSloConfiguration(coreStart, pluginsStart, sloClient); embeddable.addNewPanel( { panelType: SLO_ERROR_BUDGET_ID, diff --git a/x-pack/plugins/observability_solution/slo/public/ui_actions/create_overview_panel_action.tsx b/x-pack/plugins/observability_solution/slo/public/ui_actions/create_overview_panel_action.tsx index c4b6e5009382d..3cb1bf49d55e9 100644 --- a/x-pack/plugins/observability_solution/slo/public/ui_actions/create_overview_panel_action.tsx +++ b/x-pack/plugins/observability_solution/slo/public/ui_actions/create_overview_panel_action.tsx @@ -4,23 +4,26 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ +import type { CoreStart } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; -import type { CoreSetup } from '@kbn/core/public'; +import { COMMON_OBSERVABILITY_GROUPING } from '@kbn/observability-shared-plugin/common'; import { apiIsPresentationContainer } from '@kbn/presentation-containers'; +import { EmbeddableApiContext } from '@kbn/presentation-publishing'; import { IncompatibleActionError, type UiActionsActionDefinition, } from '@kbn/ui-actions-plugin/public'; -import { EmbeddableApiContext } from '@kbn/presentation-publishing'; -import { COMMON_OBSERVABILITY_GROUPING } from '@kbn/observability-shared-plugin/common'; +import { SLOPublicPluginsStart } from '..'; import { ADD_SLO_OVERVIEW_ACTION_ID, SLO_OVERVIEW_EMBEDDABLE_ID, } from '../embeddable/slo/overview/constants'; -import { SloPublicPluginsStart, SloPublicStart } from '..'; +import { SLORepositoryClient } from '../types'; export function createOverviewPanelAction( - getStartServices: CoreSetup['getStartServices'] + coreStart: CoreStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient ): UiActionsActionDefinition { return { id: ADD_SLO_OVERVIEW_ACTION_ID, @@ -32,12 +35,12 @@ export function createOverviewPanelAction( }, execute: async ({ embeddable }) => { if (!apiIsPresentationContainer(embeddable)) throw new IncompatibleActionError(); - const [coreStart, deps] = await getStartServices(); + try { const { openSloConfiguration } = await import( '../embeddable/slo/overview/slo_overview_open_configuration' ); - const initialState = await openSloConfiguration(coreStart, deps); + const initialState = await openSloConfiguration(coreStart, pluginsStart, sloClient); embeddable.addNewPanel( { panelType: SLO_OVERVIEW_EMBEDDABLE_ID, diff --git a/x-pack/plugins/observability_solution/slo/public/ui_actions/index.ts b/x-pack/plugins/observability_solution/slo/public/ui_actions/index.ts index 26411f02e753d..2e5e69bd02ee2 100644 --- a/x-pack/plugins/observability_solution/slo/public/ui_actions/index.ts +++ b/x-pack/plugins/observability_solution/slo/public/ui_actions/index.ts @@ -5,27 +5,33 @@ * 2.0. */ +import type { CoreStart } from '@kbn/core/public'; import { ADD_PANEL_TRIGGER } from '@kbn/ui-actions-plugin/public'; -import type { CoreSetup } from '@kbn/core/public'; -import { createOverviewPanelAction } from './create_overview_panel_action'; -import { createAddErrorBudgetPanelAction } from './create_error_budget_action'; +import { UiActionsPublicSetup } from '@kbn/ui-actions-plugin/public/plugin'; +import { SLOPublicPluginsStart } from '..'; +import { SLORepositoryClient } from '../types'; import { createAddAlertsPanelAction } from './create_alerts_panel_action'; -import { SloPublicPluginsStart, SloPublicStart, SloPublicPluginsSetup } from '..'; import { createBurnRatePanelAction } from './create_burn_rate_panel_action'; +import { createAddErrorBudgetPanelAction } from './create_error_budget_action'; +import { createOverviewPanelAction } from './create_overview_panel_action'; export function registerSloUiActions( - core: CoreSetup, - pluginsSetup: SloPublicPluginsSetup, - pluginsStart: SloPublicPluginsStart + uiActions: UiActionsPublicSetup, + coreStart: CoreStart, + pluginsStart: SLOPublicPluginsStart, + sloClient: SLORepositoryClient ) { - const { uiActions } = pluginsSetup; const { serverless, cloud } = pluginsStart; // Initialize actions - const addOverviewPanelAction = createOverviewPanelAction(core.getStartServices); - const addErrorBudgetPanelAction = createAddErrorBudgetPanelAction(core.getStartServices); - const addAlertsPanelAction = createAddAlertsPanelAction(core.getStartServices); - const addBurnRatePanelAction = createBurnRatePanelAction(core.getStartServices); + const addOverviewPanelAction = createOverviewPanelAction(coreStart, pluginsStart, sloClient); + const addErrorBudgetPanelAction = createAddErrorBudgetPanelAction( + coreStart, + pluginsStart, + sloClient + ); + const addAlertsPanelAction = createAddAlertsPanelAction(coreStart, pluginsStart, sloClient); + const addBurnRatePanelAction = createBurnRatePanelAction(coreStart, pluginsStart, sloClient); // Assign triggers // Only register these actions in stateful kibana, and the serverless observability project diff --git a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/get_create_slo_flyout.tsx b/x-pack/plugins/observability_solution/slo/public/utils/get_lazy_with_context_providers.tsx similarity index 50% rename from x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/get_create_slo_flyout.tsx rename to x-pack/plugins/observability_solution/slo/public/utils/get_lazy_with_context_providers.tsx index 88e326082c9d8..a43aa9e7bff59 100644 --- a/x-pack/plugins/observability_solution/slo/public/pages/slo_edit/shared_flyout/get_create_slo_flyout.tsx +++ b/x-pack/plugins/observability_solution/slo/public/utils/get_lazy_with_context_providers.tsx @@ -5,49 +5,52 @@ * 2.0. */ -import React from 'react'; -import { QueryClientProvider } from '@tanstack/react-query'; -import { QueryClient } from '@tanstack/react-query'; -import { Storage } from '@kbn/kibana-utils-plugin/public'; +import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, EuiLoadingSpinnerProps } from '@elastic/eui'; import { CoreStart } from '@kbn/core/public'; -import { LazyObservabilityPageTemplateProps } from '@kbn/observability-shared-plugin/public'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; -import { RecursivePartial } from '@kbn/utility-types'; +import { Storage } from '@kbn/kibana-utils-plugin/public'; import { ObservabilityRuleTypeRegistry } from '@kbn/observability-plugin/public'; -import { ExperimentalFeatures } from '../../../../common/config'; -import { CreateSLOForm } from '../types'; -import { PluginContext } from '../../../context/plugin_context'; -import { SloPublicPluginsStart } from '../../../types'; -import { SloAddFormFlyout } from './slo_form'; +import { LazyObservabilityPageTemplateProps } from '@kbn/observability-shared-plugin/public'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import React, { Suspense } from 'react'; +import { ExperimentalFeatures } from '../../common/config'; +import { PluginContext } from '../context/plugin_context'; +import { SLOPublicPluginsStart, SLORepositoryClient } from '../types'; -export const getCreateSLOFlyoutLazy = ({ - core, - plugins, - observabilityRuleTypeRegistry, - ObservabilityPageTemplate, - isDev, - kibanaVersion, - isServerless, - experimentalFeatures, -}: { +interface Props { core: CoreStart; - plugins: SloPublicPluginsStart; + plugins: SLOPublicPluginsStart; observabilityRuleTypeRegistry: ObservabilityRuleTypeRegistry; ObservabilityPageTemplate: React.ComponentType; isDev?: boolean; kibanaVersion: string; isServerless?: boolean; experimentalFeatures: ExperimentalFeatures; -}) => { - return ({ - onClose, - initialValues, - }: { - onClose: () => void; - initialValues?: RecursivePartial; - }) => { + sloClient: SLORepositoryClient; +} + +export type LazyWithContextProviders = ReturnType; + +interface Options { + spinnerSize?: EuiLoadingSpinnerProps['size']; +} + +export const getLazyWithContextProviders = + ({ + core, + plugins, + observabilityRuleTypeRegistry, + ObservabilityPageTemplate, + isDev, + kibanaVersion, + isServerless, + experimentalFeatures, + sloClient, + }: Props) => + (LazyComponent: React.LazyExoticComponent, options?: Options): React.FunctionComponent => { + const { spinnerSize = 'xl' } = options ?? {}; const queryClient = new QueryClient(); - return ( + return (props) => ( - + }> + + ); }; -}; + +function LoadingSpinner({ size }: { size: EuiLoadingSpinnerProps['size'] }) { + return ( + + + + + + ); +} diff --git a/x-pack/plugins/observability_solution/slo/public/utils/kibana_react.storybook_decorator.tsx b/x-pack/plugins/observability_solution/slo/public/utils/kibana_react.storybook_decorator.tsx index 8785772608b55..8b6e951f9c97c 100644 --- a/x-pack/plugins/observability_solution/slo/public/utils/kibana_react.storybook_decorator.tsx +++ b/x-pack/plugins/observability_solution/slo/public/utils/kibana_react.storybook_decorator.tsx @@ -4,17 +4,18 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import React, { ComponentType } from 'react'; -import { of } from 'rxjs'; -import { QueryClientProvider, QueryClient } from '@tanstack/react-query'; -import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { AppMountParameters } from '@kbn/core-application-browser'; -import { KibanaPageTemplate } from '@kbn/shared-ux-page-kibana-template'; import { CoreTheme } from '@kbn/core-theme-browser'; -import { MemoryRouter } from 'react-router-dom'; +import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { casesFeatureId, sloFeatureId } from '@kbn/observability-shared-plugin/common'; -import { createObservabilityRuleTypeRegistryMock } from '../rules/observability_rule_type_registry_mock'; +import { KibanaPageTemplate } from '@kbn/shared-ux-page-kibana-template'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import React, { ComponentType } from 'react'; +import { MemoryRouter } from 'react-router-dom'; +import { of } from 'rxjs'; import { PluginContext } from '../context/plugin_context'; +import { createObservabilityRuleTypeRegistryMock } from '../rules/observability_rule_type_registry_mock'; +import { SLORepositoryClient } from '../types'; export function KibanaReactStorybookDecorator(Story: ComponentType) { const queryClient = new QueryClient(); @@ -105,6 +106,7 @@ export function KibanaReactStorybookDecorator(Story: ComponentType) { appMountParameters, observabilityRuleTypeRegistry, ObservabilityPageTemplate: KibanaPageTemplate, + sloClient: {} as SLORepositoryClient, }} > diff --git a/x-pack/plugins/observability_solution/slo/public/utils/test_helper.tsx b/x-pack/plugins/observability_solution/slo/public/utils/test_helper.tsx index 014644d973b74..fd735d94c4a98 100644 --- a/x-pack/plugins/observability_solution/slo/public/utils/test_helper.tsx +++ b/x-pack/plugins/observability_solution/slo/public/utils/test_helper.tsx @@ -16,7 +16,9 @@ import { KibanaPageTemplate } from '@kbn/shared-ux-page-kibana-template'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { render as testLibRender } from '@testing-library/react'; import React from 'react'; +import { DefaultClientOptions, createRepositoryClient } from '@kbn/server-route-repository-client'; import { PluginContext } from '../context/plugin_context'; +import type { SLORouteRepository } from '../../server/routes/get_slo_server_route_repository'; const appMountParameters = { setHeaderActionMenu: () => {} } as unknown as AppMountParameters; const observabilityRuleTypeRegistry = createObservabilityRuleTypeRegistryMock(); @@ -39,6 +41,8 @@ const queryClient = new QueryClient({ }, }); +const sloClient = createRepositoryClient(core); + export const render = (component: React.ReactNode) => { return testLibRender( // @ts-ignore @@ -60,6 +64,7 @@ export const render = (component: React.ReactNode) => { appMountParameters, observabilityRuleTypeRegistry, ObservabilityPageTemplate: KibanaPageTemplate, + sloClient, }} > diff --git a/x-pack/plugins/observability_solution/slo/server/errors/errors.ts b/x-pack/plugins/observability_solution/slo/server/errors/errors.ts index eaec36e66d08b..66718f64519d6 100644 --- a/x-pack/plugins/observability_solution/slo/server/errors/errors.ts +++ b/x-pack/plugins/observability_solution/slo/server/errors/errors.ts @@ -7,20 +7,18 @@ /* eslint-disable max-classes-per-file */ -export class ObservabilityError extends Error { +export class SLOError extends Error { constructor(message?: string) { super(message); this.name = this.constructor.name; } } -export class SLONotFound extends ObservabilityError {} -export class SLOIdConflict extends ObservabilityError {} +export class SLONotFound extends SLOError {} +export class SLOIdConflict extends SLOError {} -export class InvalidQueryError extends ObservabilityError {} -export class InternalQueryError extends ObservabilityError {} -export class NotSupportedError extends ObservabilityError {} -export class IllegalArgumentError extends ObservabilityError {} -export class InvalidTransformError extends ObservabilityError {} +export class InternalQueryError extends SLOError {} +export class IllegalArgumentError extends SLOError {} +export class InvalidTransformError extends SLOError {} -export class SecurityException extends ObservabilityError {} +export class SecurityException extends SLOError {} diff --git a/x-pack/plugins/observability_solution/slo/server/errors/handler.ts b/x-pack/plugins/observability_solution/slo/server/errors/handler.ts index c10f1d98c083e..2aeebefe2a06c 100644 --- a/x-pack/plugins/observability_solution/slo/server/errors/handler.ts +++ b/x-pack/plugins/observability_solution/slo/server/errors/handler.ts @@ -5,20 +5,33 @@ * 2.0. */ -import { ObservabilityError, SecurityException, SLOIdConflict, SLONotFound } from './errors'; +import { Boom, badRequest, conflict, forbidden, notFound } from '@hapi/boom'; +import { SLOError, SecurityException, SLOIdConflict, SLONotFound } from './errors'; -export function getHTTPResponseCode(error: ObservabilityError): number { +function handleSLOError(error: SLOError): Boom { if (error instanceof SLONotFound) { - return 404; + return notFound(error.message); } if (error instanceof SLOIdConflict) { - return 409; + return conflict(error.message); } if (error instanceof SecurityException) { - return 403; + return forbidden(error.message); } - return 400; + return badRequest(error.message); +} + +export async function executeWithErrorHandler(fn: () => Promise): Promise { + try { + return await fn(); + } catch (error) { + if (error instanceof SLOError) { + throw handleSLOError(error); + } + + throw error; + } } diff --git a/x-pack/plugins/observability_solution/slo/server/index.ts b/x-pack/plugins/observability_solution/slo/server/index.ts index 5d6ccadb7f323..76806ac4d16cd 100644 --- a/x-pack/plugins/observability_solution/slo/server/index.ts +++ b/x-pack/plugins/observability_solution/slo/server/index.ts @@ -5,23 +5,20 @@ * 2.0. */ -import { PluginInitializerContext } from '@kbn/core/server'; -import { configSchema } from '../common/config'; +import { PluginConfigDescriptor, PluginInitializerContext } from '@kbn/core/server'; +import { SLOConfig, configSchema } from '../common/config'; // This exports static code and TypeScript types, // as well as, Kibana Platform `plugin()` initializer. -export async function plugin(initializerContext: PluginInitializerContext) { - const { SloPlugin } = await import('./plugin'); - return new SloPlugin(initializerContext); +export async function plugin(ctx: PluginInitializerContext) { + const { SLOPlugin } = await import('./plugin'); + return new SLOPlugin(ctx); } -export type { PluginSetup, PluginStart } from './plugin'; - -export const config = { +export const config: PluginConfigDescriptor = { schema: configSchema, exposeToBrowser: { experimental: true, }, }; -export type { SloConfig } from '../common/config'; diff --git a/x-pack/plugins/observability_solution/slo/server/plugin.ts b/x-pack/plugins/observability_solution/slo/server/plugin.ts index a2e4229b2b952..d7d002d26aa03 100644 --- a/x-pack/plugins/observability_solution/slo/server/plugin.ts +++ b/x-pack/plugins/observability_solution/slo/server/plugin.ts @@ -5,79 +5,58 @@ * 2.0. */ -import { i18n } from '@kbn/i18n'; import { - PluginInitializerContext, CoreSetup, CoreStart, DEFAULT_APP_CATEGORIES, - Plugin, Logger, + Plugin, + PluginInitializerContext, SavedObjectsClient, } from '@kbn/core/server'; -import { PluginSetupContract, PluginStartContract } from '@kbn/alerting-plugin/server'; -import { FeaturesPluginSetup } from '@kbn/features-plugin/server'; -import { - RuleRegistryPluginSetupContract, - RuleRegistryPluginStartContract, -} from '@kbn/rule-registry-plugin/server'; -import { - TaskManagerSetupContract, - TaskManagerStartContract, -} from '@kbn/task-manager-plugin/server'; -import { DataViewsServerPluginStart } from '@kbn/data-views-plugin/server'; -import { CloudSetup } from '@kbn/cloud-plugin/server'; -import { SharePluginSetup } from '@kbn/share-plugin/server'; -import { UsageCollectionSetup } from '@kbn/usage-collection-plugin/server'; -import { SpacesPluginSetup, SpacesPluginStart } from '@kbn/spaces-plugin/server'; -import { AlertsLocatorDefinition } from '@kbn/observability-plugin/common'; -import { SLO_BURN_RATE_RULE_TYPE_ID } from '@kbn/rule-data-utils'; -import { sloFeatureId } from '@kbn/observability-plugin/common'; import { KibanaFeatureScope } from '@kbn/features-plugin/common'; +import { i18n } from '@kbn/i18n'; +import { AlertsLocatorDefinition, sloFeatureId } from '@kbn/observability-plugin/common'; +import { SLO_BURN_RATE_RULE_TYPE_ID } from '@kbn/rule-data-utils'; +import { mapValues } from 'lodash'; import { registerSloUsageCollector } from './lib/collectors/register'; -import { SloOrphanSummaryCleanupTask } from './services/tasks/orphan_summary_cleanup_task'; -import { slo, SO_SLO_TYPE } from './saved_objects'; -import { DefaultResourceInstaller, DefaultSLOInstaller } from './services'; import { registerBurnRateRule } from './lib/rules/register_burn_rate_rule'; -import { SloConfig } from '.'; -import { registerRoutes } from './routes/register_routes'; import { getSloServerRouteRepository } from './routes/get_slo_server_route_repository'; -import { sloSettings, SO_SLO_SETTINGS_TYPE } from './saved_objects/slo_settings'; - -export type SloPluginSetup = ReturnType; - -export interface PluginSetup { - alerting: PluginSetupContract; - ruleRegistry: RuleRegistryPluginSetupContract; - share: SharePluginSetup; - features: FeaturesPluginSetup; - taskManager: TaskManagerSetupContract; - spaces?: SpacesPluginSetup; - cloud?: CloudSetup; - usageCollection: UsageCollectionSetup; -} - -export interface PluginStart { - alerting: PluginStartContract; - taskManager: TaskManagerStartContract; - spaces?: SpacesPluginStart; - ruleRegistry: RuleRegistryPluginStartContract; - dataViews: DataViewsServerPluginStart; -} +import { registerServerRoutes } from './routes/register_routes'; +import { SLORoutesDependencies } from './routes/types'; +import { SO_SLO_TYPE, slo } from './saved_objects'; +import { SO_SLO_SETTINGS_TYPE, sloSettings } from './saved_objects/slo_settings'; +import { DefaultResourceInstaller, DefaultSLOInstaller } from './services'; +import { SloOrphanSummaryCleanupTask } from './services/tasks/orphan_summary_cleanup_task'; +import type { + SLOConfig, + SLOPluginSetupDependencies, + SLOPluginStartDependencies, + SLOServerSetup, + SLOServerStart, +} from './types'; const sloRuleTypes = [SLO_BURN_RATE_RULE_TYPE_ID]; -export class SloPlugin implements Plugin { +export class SLOPlugin + implements + Plugin +{ private readonly logger: Logger; + private readonly config: SLOConfig; + private readonly isServerless: boolean; private sloOrphanCleanupTask?: SloOrphanSummaryCleanupTask; constructor(private readonly initContext: PluginInitializerContext) { - this.initContext = initContext; - this.logger = initContext.logger.get(); + this.logger = this.initContext.logger.get(); + this.config = this.initContext.config.get(); + this.isServerless = this.initContext.env.packageInfo.buildFlavor === 'serverless'; } - public setup(core: CoreSetup, plugins: PluginSetup) { - const config = this.initContext.config.get(); + public setup( + core: CoreSetup, + plugins: SLOPluginSetupDependencies + ): SLOServerSetup { const alertsLocator = plugins.share.url.locators.create(new AlertsLocatorDefinition()); const savedObjectTypes = [SO_SLO_TYPE, SO_SLO_SETTINGS_TYPE]; @@ -144,36 +123,24 @@ export class SloPlugin implements Plugin { registerSloUsageCollector(plugins.usageCollection); - registerRoutes({ + const routeHandlerPlugins = mapValues(plugins, (value, key) => { + return { + setup: value, + start: () => + core.getStartServices().then(([, pluginStart]) => { + return pluginStart[key as keyof SLOPluginStartDependencies]; + }), + }; + }) as SLORoutesDependencies['plugins']; + + registerServerRoutes({ core, - config, dependencies: { - pluginsSetup: { - ...plugins, - core, - }, - getDataViewsStart: async () => { - const [, pluginStart] = await core.getStartServices(); - return pluginStart.dataViews; - }, - getSpacesStart: async () => { - const [, pluginStart] = await core.getStartServices(); - return pluginStart.spaces; - }, - ruleDataService, - getRulesClientWithRequest: async (request) => { - const [, pluginStart] = await core.getStartServices(); - return pluginStart.alerting.getRulesClientWithRequest(request); - }, - getRacClientWithRequest: async (request) => { - const [, pluginStart] = await core.getStartServices(); - return pluginStart.ruleRegistry.getRacClientWithRequest(request); - }, + corePlugins: core, + plugins: routeHandlerPlugins, }, logger: this.logger, - repository: getSloServerRouteRepository({ - isServerless: this.initContext.env.packageInfo.buildFlavor === 'serverless', - }), + repository: getSloServerRouteRepository({ isServerless: this.isServerless }), }); core @@ -191,18 +158,20 @@ export class SloPlugin implements Plugin { this.sloOrphanCleanupTask = new SloOrphanSummaryCleanupTask( plugins.taskManager, this.logger, - config + this.config ); + + return {}; } - public start(core: CoreStart, plugins: PluginStart) { + public start(core: CoreStart, plugins: SLOPluginStartDependencies): SLOServerStart { const internalSoClient = new SavedObjectsClient(core.savedObjects.createInternalRepository()); const internalEsClient = core.elasticsearch.client.asInternalUser; this.sloOrphanCleanupTask ?.start(plugins.taskManager, internalSoClient, internalEsClient) .catch(() => {}); - } - public stop() {} + return {}; + } } diff --git a/x-pack/plugins/observability_solution/slo/server/routes/create_slo_server_route.ts b/x-pack/plugins/observability_solution/slo/server/routes/create_slo_server_route.ts index 762b5b369f6e6..6d1b762f1dca5 100644 --- a/x-pack/plugins/observability_solution/slo/server/routes/create_slo_server_route.ts +++ b/x-pack/plugins/observability_solution/slo/server/routes/create_slo_server_route.ts @@ -5,9 +5,6 @@ * 2.0. */ import { createServerRouteFactory } from '@kbn/server-route-repository'; -import { SloRouteCreateOptions, SloRouteHandlerResources } from './types'; +import { SLORouteHandlerResources } from './types'; -export const createSloServerRoute = createServerRouteFactory< - SloRouteHandlerResources, - SloRouteCreateOptions ->(); +export const createSloServerRoute = createServerRouteFactory(); diff --git a/x-pack/plugins/observability_solution/slo/server/routes/get_slo_server_route_repository.ts b/x-pack/plugins/observability_solution/slo/server/routes/get_slo_server_route_repository.ts index b04b6209054a9..f4205c98363d8 100644 --- a/x-pack/plugins/observability_solution/slo/server/routes/get_slo_server_route_repository.ts +++ b/x-pack/plugins/observability_solution/slo/server/routes/get_slo_server_route_repository.ts @@ -8,9 +8,7 @@ import { getSloRouteRepository } from './slo/route'; export function getSloServerRouteRepository({ isServerless }: { isServerless?: boolean } = {}) { - return { - ...getSloRouteRepository(isServerless), - }; + return getSloRouteRepository(isServerless); } -export type SloServerRouteRepository = ReturnType; +export type SLORouteRepository = ReturnType; diff --git a/x-pack/plugins/observability_solution/slo/server/routes/register_routes.ts b/x-pack/plugins/observability_solution/slo/server/routes/register_routes.ts index 6a7d2d08bdd1b..fd0b18c210041 100644 --- a/x-pack/plugins/observability_solution/slo/server/routes/register_routes.ts +++ b/x-pack/plugins/observability_solution/slo/server/routes/register_routes.ts @@ -4,136 +4,23 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { errors } from '@elastic/elasticsearch'; -import Boom from '@hapi/boom'; -import { RulesClientApi } from '@kbn/alerting-plugin/server/types'; -import { CoreSetup, KibanaRequest, Logger, RouteRegistrar } from '@kbn/core/server'; -import { - AlertsClient, - RuleDataPluginService, - RuleRegistryPluginSetupContract, -} from '@kbn/rule-registry-plugin/server'; -import { - IoTsParamsObject, - decodeRequestParams, - stripNullishRequestParameters, - parseEndpoint, - passThroughValidationObject, -} from '@kbn/server-route-repository'; -import { SpacesPluginStart } from '@kbn/spaces-plugin/server'; -import axios from 'axios'; -import * as t from 'io-ts'; -import { DataViewsServerPluginStart } from '@kbn/data-views-plugin/server'; -import { SloConfig } from '..'; -import { getHTTPResponseCode, ObservabilityError } from '../errors'; -import { SloRequestHandlerContext } from '../types'; -import { AbstractSloServerRouteRepository } from './types'; +import { CoreSetup, Logger } from '@kbn/core/server'; +import { ServerRoute, registerRoutes } from '@kbn/server-route-repository'; +import { ServerRouteCreateOptions } from '@kbn/server-route-repository-utils'; +import { SLORoutesDependencies } from './types'; interface RegisterRoutes { - config: SloConfig; core: CoreSetup; - repository: AbstractSloServerRouteRepository; + repository: Record>; logger: Logger; - dependencies: RegisterRoutesDependencies; + dependencies: SLORoutesDependencies; } -export interface RegisterRoutesDependencies { - pluginsSetup: { - core: CoreSetup; - ruleRegistry: RuleRegistryPluginSetupContract; - }; - getSpacesStart: () => Promise; - ruleDataService: RuleDataPluginService; - getRulesClientWithRequest: (request: KibanaRequest) => Promise; - getRacClientWithRequest: (request: KibanaRequest) => Promise; - getDataViewsStart: () => Promise; -} - -export function registerRoutes({ config, repository, core, logger, dependencies }: RegisterRoutes) { - const routes = Object.values(repository); - - const router = core.http.createRouter(); - - routes.forEach((route) => { - const { endpoint, options, handler, params } = route; - const { pathname, method } = parseEndpoint(endpoint); - - (router[method] as RouteRegistrar)( - { - path: pathname, - validate: passThroughValidationObject, - options, - }, - async (context, request, response) => { - try { - const decodedParams = decodeRequestParams( - stripNullishRequestParameters({ - params: request.params, - body: request.body, - query: request.query, - }), - (params as IoTsParamsObject) ?? t.strict({}) - ); - - const data = await handler({ - config, - context, - request, - logger, - params: decodedParams, - dependencies, - }); - - if (data === undefined) { - return response.noContent(); - } - - return response.ok({ body: data }); - } catch (error) { - if (error instanceof ObservabilityError) { - logger.error(error.message); - return response.customError({ - statusCode: getHTTPResponseCode(error), - body: { - message: error.message, - }, - }); - } - - if (axios.isAxiosError(error)) { - logger.error(error); - return response.customError({ - statusCode: error.response?.status || 500, - body: { - message: error.message, - }, - }); - } - - if (Boom.isBoom(error)) { - logger.error(error.output.payload.message); - return response.customError({ - statusCode: error.output.statusCode, - body: { message: error.output.payload.message }, - }); - } - - logger.error(error); - const opts = { - statusCode: 500, - body: { - message: error.message, - }, - }; - - if (error instanceof errors.RequestAbortedError) { - opts.statusCode = 499; - opts.body.message = 'Client closed request'; - } - - return response.customError(opts); - } - } - ); +export function registerServerRoutes({ repository, core, logger, dependencies }: RegisterRoutes) { + registerRoutes({ + repository, + dependencies, + core, + logger, }); } diff --git a/x-pack/plugins/observability_solution/slo/server/routes/slo/route.ts b/x-pack/plugins/observability_solution/slo/server/routes/slo/route.ts index 838adc72cfd08..9e63a4b02fe7b 100644 --- a/x-pack/plugins/observability_solution/slo/server/routes/slo/route.ts +++ b/x-pack/plugins/observability_solution/slo/server/routes/slo/route.ts @@ -7,32 +7,30 @@ import { errors } from '@elastic/elasticsearch'; import { failedDependency, forbidden } from '@hapi/boom'; +import { KibanaRequest } from '@kbn/core-http-server'; import { + PutSLOSettingsParams, createSLOParamsSchema, deleteSLOInstancesParamsSchema, deleteSLOParamsSchema, fetchHistoricalSummaryParamsSchema, - fetchHistoricalSummaryResponseSchema, fetchSLOHealthParamsSchema, - findSloDefinitionsParamsSchema, findSLOGroupsParamsSchema, findSLOParamsSchema, + findSloDefinitionsParamsSchema, getPreviewDataParamsSchema, getSLOBurnRatesParamsSchema, getSLOInstancesParamsSchema, getSLOParamsSchema, manageSLOParamsSchema, putSLOServerlessSettingsParamsSchema, - PutSLOSettingsParams, putSLOSettingsParamsSchema, resetSLOParamsSchema, updateSLOParamsSchema, } from '@kbn/slo-schema'; import { getOverviewParamsSchema } from '@kbn/slo-schema/src/rest_specs/routes/get_overview'; -import { KibanaRequest } from '@kbn/core-http-server'; -import { RegisterRoutesDependencies } from '../register_routes'; -import { GetSLOsOverview } from '../../services/get_slos_overview'; import type { IndicatorTypes } from '../../domain/models'; +import { executeWithErrorHandler } from '../../errors'; import { CreateSLO, DefaultBurnRatesClient, @@ -54,6 +52,7 @@ import { getGlobalDiagnosis } from '../../services/get_diagnosis'; import { GetPreviewData } from '../../services/get_preview_data'; import { GetSLOInstances } from '../../services/get_slo_instances'; import { GetSLOSuggestions } from '../../services/get_slo_suggestions'; +import { GetSLOsOverview } from '../../services/get_slos_overview'; import { DefaultHistoricalSummaryClient } from '../../services/historical_summary_client'; import { ManageSLO } from '../../services/manage_slo'; import { ResetSLO } from '../../services/reset_slo'; @@ -71,8 +70,8 @@ import { TimesliceMetricTransformGenerator, TransformGenerator, } from '../../services/transform_generators'; -import type { SloRequestHandlerContext } from '../../types'; import { createSloServerRoute } from '../create_slo_server_route'; +import { SLORoutesDependencies } from '../types'; const transformGenerators: Record = { 'sli.apm.transactionDuration': new ApmTransactionDurationTransformGenerator(), @@ -84,17 +83,17 @@ const transformGenerators: Record = { 'sli.metric.timeslice': new TimesliceMetricTransformGenerator(), }; -const assertPlatinumLicense = async (context: SloRequestHandlerContext) => { - const licensing = await context.licensing; - const hasCorrectLicense = licensing.license.hasAtLeast('platinum'); +const assertPlatinumLicense = async (plugins: SLORoutesDependencies['plugins']) => { + const licensing = await plugins.licensing.start(); + const hasCorrectLicense = (await licensing.getLicense()).hasAtLeast('platinum'); if (!hasCorrectLicense) { throw forbidden('Platinum license or higher is needed to make use of this feature.'); } }; -const getSpaceId = async (deps: RegisterRoutesDependencies, request: KibanaRequest) => { - const spaces = await deps.getSpacesStart(); +const getSpaceId = async (plugins: SLORoutesDependencies['plugins'], request: KibanaRequest) => { + const spaces = await plugins.spaces.start(); return (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; }; @@ -105,19 +104,19 @@ const createSLORoute = createSloServerRoute({ access: 'public', }, params: createSLOParamsSchema, - handler: async ({ context, params, logger, dependencies, request }) => { - await assertPlatinumLicense(context); + handler: async ({ context, response, params, logger, request, plugins, corePlugins }) => { + await assertPlatinumLicense(plugins); - const dataViews = await dependencies.getDataViewsStart(); + const dataViews = await plugins.dataViews.start(); const core = await context.core; const scopedClusterClient = core.elasticsearch.client; const esClient = core.elasticsearch.client.asCurrentUser; - const basePath = dependencies.pluginsSetup.core.http.basePath; const soClient = core.savedObjects.client; + const basePath = corePlugins.http.basePath; const repository = new KibanaSavedObjectsSLORepository(soClient, logger); const [spaceId, dataViewsService] = await Promise.all([ - getSpaceId(dependencies, request), + getSpaceId(plugins, request), dataViews.dataViewsServiceFactory(soClient, esClient), ]); const transformManager = new DefaultTransformManager( @@ -143,7 +142,7 @@ const createSLORoute = createSloServerRoute({ basePath ); - return await createSLO.execute(params.body); + return await executeWithErrorHandler(() => createSLO.execute(params.body)); }, }); @@ -154,13 +153,12 @@ const inspectSLORoute = createSloServerRoute({ access: 'internal', }, params: createSLOParamsSchema, - handler: async ({ context, params, logger, dependencies, request }) => { - await assertPlatinumLicense(context); + handler: async ({ context, params, logger, request, plugins, corePlugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const dataViews = await dependencies.getDataViewsStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; - const basePath = dependencies.pluginsSetup.core.http.basePath; + const dataViews = await plugins.dataViews.start(); + const spaceId = await getSpaceId(plugins, request); + const basePath = corePlugins.http.basePath; const core = await context.core; const scopedClusterClient = core.elasticsearch.client; const esClient = core.elasticsearch.client.asCurrentUser; @@ -191,7 +189,7 @@ const inspectSLORoute = createSloServerRoute({ basePath ); - return createSLO.inspect(params.body); + return await executeWithErrorHandler(() => createSLO.inspect(params.body)); }, }); @@ -202,14 +200,13 @@ const updateSLORoute = createSloServerRoute({ access: 'public', }, params: updateSLOParamsSchema, - handler: async ({ context, request, params, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ context, request, params, logger, plugins, corePlugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; - const dataViews = await dependencies.getDataViewsStart(); + const spaceId = await getSpaceId(plugins, request); + const dataViews = await plugins.dataViews.start(); - const basePath = dependencies.pluginsSetup.core.http.basePath; + const basePath = corePlugins.http.basePath; const core = await context.core; const scopedClusterClient = core.elasticsearch.client; const esClient = core.elasticsearch.client.asCurrentUser; @@ -240,9 +237,7 @@ const updateSLORoute = createSloServerRoute({ basePath ); - const response = await updateSLO.execute(params.path.id, params.body); - - return response; + return await executeWithErrorHandler(() => updateSLO.execute(params.path.id, params.body)); }, }); @@ -253,18 +248,19 @@ const deleteSLORoute = createSloServerRoute({ access: 'public', }, params: deleteSLOParamsSchema, - handler: async ({ request, context, params, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ request, response, context, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; - const dataViews = await dependencies.getDataViewsStart(); + const spaceId = await getSpaceId(plugins, request); + const dataViews = await plugins.dataViews.start(); const core = await context.core; const scopedClusterClient = core.elasticsearch.client; const esClient = core.elasticsearch.client.asCurrentUser; const soClient = core.savedObjects.client; - const rulesClient = await dependencies.getRulesClientWithRequest(request); + + const alerting = await plugins.alerting.start(); + const rulesClient = await alerting.getRulesClientWithRequest(request); const dataViewsService = await dataViews.dataViewsServiceFactory(soClient, esClient); @@ -292,7 +288,8 @@ const deleteSLORoute = createSloServerRoute({ rulesClient ); - await deleteSLO.execute(params.path.id); + await executeWithErrorHandler(() => deleteSLO.execute(params.path.id)); + return response.noContent(); }, }); @@ -303,11 +300,10 @@ const getSLORoute = createSloServerRoute({ access: 'public', }, params: getSLOParamsSchema, - handler: async ({ request, context, params, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ request, context, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaceId = await getSpaceId(plugins, request); const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; @@ -317,7 +313,9 @@ const getSLORoute = createSloServerRoute({ const defintionClient = new SloDefinitionClient(repository, esClient, logger); const getSLO = new GetSLO(defintionClient, summaryClient); - return await getSLO.execute(params.path.id, spaceId, params.query); + return await executeWithErrorHandler(() => + getSLO.execute(params.path.id, spaceId, params.query) + ); }, }); @@ -328,12 +326,11 @@ const enableSLORoute = createSloServerRoute({ access: 'public', }, params: manageSLOParamsSchema, - handler: async ({ request, context, params, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ request, response, context, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; - const dataViews = await dependencies.getDataViewsStart(); + const spaceId = await getSpaceId(plugins, request); + const dataViews = await plugins.dataViews.start(); const core = await context.core; const scopedClusterClient = core.elasticsearch.client; @@ -356,9 +353,9 @@ const enableSLORoute = createSloServerRoute({ const manageSLO = new ManageSLO(repository, transformManager, summaryTransformManager); - const response = await manageSLO.enable(params.path.id); + await executeWithErrorHandler(() => manageSLO.enable(params.path.id)); - return response; + return response.noContent(); }, }); @@ -369,12 +366,11 @@ const disableSLORoute = createSloServerRoute({ access: 'public', }, params: manageSLOParamsSchema, - handler: async ({ request, context, params, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ response, request, context, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; - const dataViews = await dependencies.getDataViewsStart(); + const spaceId = await getSpaceId(plugins, request); + const dataViews = await plugins.dataViews.start(); const core = await context.core; const scopedClusterClient = core.elasticsearch.client; @@ -397,9 +393,8 @@ const disableSLORoute = createSloServerRoute({ const manageSLO = new ManageSLO(repository, transformManager, summaryTransformManager); - const response = await manageSLO.disable(params.path.id); - - return response; + await executeWithErrorHandler(() => manageSLO.disable(params.path.id)); + return response.noContent(); }, }); @@ -410,17 +405,16 @@ const resetSLORoute = createSloServerRoute({ access: 'public', }, params: resetSLOParamsSchema, - handler: async ({ context, request, params, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ context, request, params, logger, plugins, corePlugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const dataViews = await dependencies.getDataViewsStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const dataViews = await plugins.dataViews.start(); + const spaceId = await getSpaceId(plugins, request); const core = await context.core; const scopedClusterClient = core.elasticsearch.client; const soClient = core.savedObjects.client; const esClient = core.elasticsearch.client.asCurrentUser; - const basePath = dependencies.pluginsSetup.core.http.basePath; + const basePath = corePlugins.http.basePath; const dataViewsService = await dataViews.dataViewsServiceFactory(soClient, esClient); const repository = new KibanaSavedObjectsSLORepository(soClient, logger); @@ -448,9 +442,7 @@ const resetSLORoute = createSloServerRoute({ basePath ); - const response = await resetSLO.execute(params.path.id); - - return response; + return await executeWithErrorHandler(() => resetSLO.execute(params.path.id)); }, }); @@ -461,11 +453,10 @@ const findSLORoute = createSloServerRoute({ access: 'public', }, params: findSLOParamsSchema, - handler: async ({ context, request, params, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ context, request, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaceId = await getSpaceId(plugins, request); const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const repository = new KibanaSavedObjectsSLORepository(soClient, logger); @@ -473,7 +464,7 @@ const findSLORoute = createSloServerRoute({ const findSLO = new FindSLO(repository, summarySearchClient); - return await findSLO.execute(params?.query ?? {}); + return await executeWithErrorHandler(() => findSLO.execute(params?.query ?? {})); }, }); @@ -484,16 +475,15 @@ const findSLOGroupsRoute = createSloServerRoute({ access: 'internal', }, params: findSLOGroupsParamsSchema, - handler: async ({ context, request, params, logger, dependencies }) => { - await assertPlatinumLicense(context); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService.getActiveSpace(request))?.id ?? 'default'; + handler: async ({ context, request, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); + + const spaceId = await getSpaceId(plugins, request); const soClient = (await context.core).savedObjects.client; const coreContext = context.core; const esClient = (await coreContext).elasticsearch.client.asCurrentUser; const findSLOGroups = new FindSLOGroups(esClient, soClient, logger, spaceId); - const response = await findSLOGroups.execute(params?.query ?? {}); - return response; + return await executeWithErrorHandler(() => findSLOGroups.execute(params?.query ?? {})); }, }); @@ -503,12 +493,12 @@ const getSLOSuggestionsRoute = createSloServerRoute({ tags: ['access:slo_read'], access: 'internal', }, - handler: async ({ context }) => { - await assertPlatinumLicense(context); + handler: async ({ context, plugins }) => { + await assertPlatinumLicense(plugins); const soClient = (await context.core).savedObjects.client; const getSLOSuggestions = new GetSLOSuggestions(soClient); - return await getSLOSuggestions.execute(); + return await executeWithErrorHandler(() => getSLOSuggestions.execute()); }, }); @@ -519,13 +509,14 @@ const deleteSloInstancesRoute = createSloServerRoute({ access: 'public', }, params: deleteSLOInstancesParamsSchema, - handler: async ({ context, params }) => { - await assertPlatinumLicense(context); + handler: async ({ response, context, params, plugins }) => { + await assertPlatinumLicense(plugins); const esClient = (await context.core).elasticsearch.client.asCurrentUser; const deleteSloInstances = new DeleteSLOInstances(esClient); - await deleteSloInstances.execute(params.body); + await executeWithErrorHandler(() => deleteSloInstances.execute(params.body)); + return response.noContent(); }, }); @@ -536,16 +527,14 @@ const findSloDefinitionsRoute = createSloServerRoute({ access: 'public', }, params: findSloDefinitionsParamsSchema, - handler: async ({ context, params, logger }) => { - await assertPlatinumLicense(context); + handler: async ({ context, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); const soClient = (await context.core).savedObjects.client; const repository = new KibanaSavedObjectsSLORepository(soClient, logger); const findSloDefinitions = new FindSLODefinitions(repository); - const response = await findSloDefinitions.execute(params?.query ?? {}); - - return response; + return await executeWithErrorHandler(() => findSloDefinitions.execute(params?.query ?? {})); }, }); @@ -556,15 +545,13 @@ const fetchHistoricalSummary = createSloServerRoute({ access: 'internal', }, params: fetchHistoricalSummaryParamsSchema, - handler: async ({ context, params, logger }) => { - await assertPlatinumLicense(context); + handler: async ({ context, params, plugins }) => { + await assertPlatinumLicense(plugins); const esClient = (await context.core).elasticsearch.client.asCurrentUser; const historicalSummaryClient = new DefaultHistoricalSummaryClient(esClient); - const historicalSummary = await historicalSummaryClient.fetch(params.body); - - return fetchHistoricalSummaryResponseSchema.encode(historicalSummary); + return await executeWithErrorHandler(() => historicalSummaryClient.fetch(params.body)); }, }); @@ -575,18 +562,15 @@ const getSLOInstancesRoute = createSloServerRoute({ access: 'internal', }, params: getSLOInstancesParamsSchema, - handler: async ({ context, params, logger }) => { - await assertPlatinumLicense(context); + handler: async ({ context, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const repository = new KibanaSavedObjectsSLORepository(soClient, logger); - const getSLOInstances = new GetSLOInstances(repository, esClient); - const response = await getSLOInstances.execute(params.path.id); - - return response; + return await executeWithErrorHandler(() => getSLOInstances.execute(params.path.id)); }, }); @@ -597,9 +581,9 @@ const getDiagnosisRoute = createSloServerRoute({ access: 'internal', }, params: undefined, - handler: async ({ context }) => { + handler: async ({ context, plugins }) => { const esClient = (await context.core).elasticsearch.client.asCurrentUser; - const licensing = await context.licensing; + const licensing = await plugins.licensing.start(); try { const response = await getGlobalDiagnosis(esClient, licensing); @@ -620,8 +604,8 @@ const fetchSloHealthRoute = createSloServerRoute({ access: 'internal', }, params: fetchSLOHealthParamsSchema, - handler: async ({ context, params, logger }) => { - await assertPlatinumLicense(context); + handler: async ({ context, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); const core = await context.core; const scopedClusterClient = core.elasticsearch.client; @@ -631,7 +615,7 @@ const fetchSloHealthRoute = createSloServerRoute({ const getSLOHealth = new GetSLOHealth(esClient, scopedClusterClient, repository); - return await getSLOHealth.execute(params.body); + return await executeWithErrorHandler(() => getSLOHealth.execute(params.body)); }, }); @@ -642,28 +626,29 @@ const getSloBurnRates = createSloServerRoute({ access: 'internal', }, params: getSLOBurnRatesParamsSchema, - handler: async ({ request, context, params, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ request, context, params, logger, plugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService.getActiveSpace(request))?.id ?? 'default'; + const spaceId = await getSpaceId(plugins, request); const esClient = (await context.core).elasticsearch.client.asCurrentUser; const soClient = (await context.core).savedObjects.client; const { instanceId, windows, remoteName } = params.body; - return await getBurnRates({ - instanceId, - spaceId, - windows, - remoteName, - sloId: params.path.id, - services: { - soClient, - esClient, - logger, - }, - }); + return await executeWithErrorHandler(() => + getBurnRates({ + instanceId, + spaceId, + windows, + remoteName, + sloId: params.path.id, + services: { + soClient, + esClient, + logger, + }, + }) + ); }, }); @@ -674,12 +659,11 @@ const getPreviewData = createSloServerRoute({ access: 'internal', }, params: getPreviewDataParamsSchema, - handler: async ({ request, context, params, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ request, context, params, plugins }) => { + await assertPlatinumLicense(plugins); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; - const dataViews = await dependencies.getDataViewsStart(); + const spaceId = await getSpaceId(plugins, request); + const dataViews = await plugins.dataViews.start(); const esClient = (await context.core).elasticsearch.client.asCurrentUser; const soClient = (await context.core).savedObjects.client; @@ -695,11 +679,12 @@ const getSloSettingsRoute = createSloServerRoute({ tags: ['access:slo_read'], access: 'internal', }, - handler: async ({ context }) => { - await assertPlatinumLicense(context); + handler: async ({ context, plugins }) => { + await assertPlatinumLicense(plugins); const soClient = (await context.core).savedObjects.client; - return await getSloSettings(soClient); + + return await executeWithErrorHandler(() => getSloSettings(soClient)); }, }); @@ -711,11 +696,13 @@ const putSloSettings = (isServerless?: boolean) => access: 'internal', }, params: isServerless ? putSLOServerlessSettingsParamsSchema : putSLOSettingsParamsSchema, - handler: async ({ context, params }) => { - await assertPlatinumLicense(context); + handler: async ({ context, params, plugins }) => { + await assertPlatinumLicense(plugins); const soClient = (await context.core).savedObjects.client; - return await storeSloSettings(soClient, params.body as PutSLOSettingsParams); + return await executeWithErrorHandler(() => + storeSloSettings(soClient, params.body as PutSLOSettingsParams) + ); }, }); @@ -726,17 +713,19 @@ const getSLOsOverview = createSloServerRoute({ access: 'internal', }, params: getOverviewParamsSchema, - handler: async ({ context, params, request, logger, dependencies }) => { - await assertPlatinumLicense(context); + handler: async ({ context, params, request, logger, plugins }) => { + await assertPlatinumLicense(plugins); const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; - const racClient = await dependencies.getRacClientWithRequest(request); + const ruleRegistry = await plugins.ruleRegistry.start(); + const racClient = await ruleRegistry.getRacClientWithRequest(request); - const spaces = await dependencies.getSpacesStart(); - const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; - const rulesClient = await dependencies.getRulesClientWithRequest(request); + const spaceId = await getSpaceId(plugins, request); + + const alerting = await plugins.alerting.start(); + const rulesClient = await alerting.getRulesClientWithRequest(request); const slosOverview = new GetSLOsOverview( soClient, @@ -746,7 +735,8 @@ const getSLOsOverview = createSloServerRoute({ rulesClient, racClient ); - return await slosOverview.execute(params?.query ?? {}); + + return await executeWithErrorHandler(() => slosOverview.execute(params?.query ?? {})); }, }); diff --git a/x-pack/plugins/observability_solution/slo/server/routes/types.ts b/x-pack/plugins/observability_solution/slo/server/routes/types.ts index a16ffbcc10fa7..cb5057cee4056 100644 --- a/x-pack/plugins/observability_solution/slo/server/routes/types.ts +++ b/x-pack/plugins/observability_solution/slo/server/routes/types.ts @@ -4,32 +4,21 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import type { EndpointOf, ReturnOf, ServerRouteRepository } from '@kbn/server-route-repository'; -import { KibanaRequest, Logger } from '@kbn/core/server'; +import { CoreSetup } from '@kbn/core/server'; +import type { DefaultRouteHandlerResources } from '@kbn/server-route-repository'; +import { SLOPluginSetupDependencies, SLOPluginStartDependencies } from '../types'; -import { SloServerRouteRepository } from './get_slo_server_route_repository'; -import { SloRequestHandlerContext } from '../types'; -import { RegisterRoutesDependencies } from './register_routes'; -import { SloConfig } from '..'; - -export type { SloServerRouteRepository }; - -export interface SloRouteHandlerResources { - context: SloRequestHandlerContext; - dependencies: RegisterRoutesDependencies; - logger: Logger; - request: KibanaRequest; - config: SloConfig; -} - -export interface SloRouteCreateOptions { - options: { - tags: string[]; - access?: 'public' | 'internal'; +export interface SLORoutesDependencies { + plugins: { + [key in keyof SLOPluginSetupDependencies]: { + setup: Required[key]; + }; + } & { + [key in keyof SLOPluginStartDependencies]: { + start: () => Promise[key]>; + }; }; + corePlugins: CoreSetup; } -export type AbstractSloServerRouteRepository = ServerRouteRepository; - -export type ObservabilityAPIReturnType> = - ReturnOf; +export type SLORouteHandlerResources = SLORoutesDependencies & DefaultRouteHandlerResources; diff --git a/x-pack/plugins/observability_solution/slo/server/services/get_diagnosis.ts b/x-pack/plugins/observability_solution/slo/server/services/get_diagnosis.ts index 7a090de252c1d..df0a7b1952406 100644 --- a/x-pack/plugins/observability_solution/slo/server/services/get_diagnosis.ts +++ b/x-pack/plugins/observability_solution/slo/server/services/get_diagnosis.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; -import { LicensingApiRequestHandlerContext } from '@kbn/licensing-plugin/server'; +import { LicensingPluginStart } from '@kbn/licensing-plugin/server'; export const MINIMUM_INDEX_PRIVILEGE_SET_EDITOR = [ 'write', @@ -26,9 +26,9 @@ export const TOTAL_INDEX_PRIVILEGE_SET_VIEWER = ['read', 'read_cross_cluster']; export async function getGlobalDiagnosis( esClient: ElasticsearchClient, - licensing: LicensingApiRequestHandlerContext + licensing: LicensingPluginStart ) { - const licenseInfo = licensing.license.toJSON(); + const licenseInfo = (await licensing.getLicense()).toJSON(); const userWritePrivileges = await esClient.security.hasPrivileges({ index: [ { diff --git a/x-pack/plugins/observability_solution/slo/server/services/tasks/orphan_summary_cleanup_task.test.ts b/x-pack/plugins/observability_solution/slo/server/services/tasks/orphan_summary_cleanup_task.test.ts index b947e0985c580..31b74b3cf9ed4 100644 --- a/x-pack/plugins/observability_solution/slo/server/services/tasks/orphan_summary_cleanup_task.test.ts +++ b/x-pack/plugins/observability_solution/slo/server/services/tasks/orphan_summary_cleanup_task.test.ts @@ -5,14 +5,13 @@ * 2.0. */ -import { getDeleteQueryFilter, SloOrphanSummaryCleanupTask } from './orphan_summary_cleanup_task'; -import { taskManagerMock } from '@kbn/task-manager-plugin/server/mocks'; - -import { loggerMock } from '@kbn/logging-mocks'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; -import { times } from 'lodash'; import { savedObjectsClientMock } from '@kbn/core-saved-objects-api-server-mocks'; +import { loggerMock } from '@kbn/logging-mocks'; +import { taskManagerMock } from '@kbn/task-manager-plugin/server/mocks'; +import { times } from 'lodash'; import { SLO_SUMMARY_DESTINATION_INDEX_PATTERN } from '../../../common/constants'; +import { getDeleteQueryFilter, SloOrphanSummaryCleanupTask } from './orphan_summary_cleanup_task'; const taskManagerSetup = taskManagerMock.createSetup(); const taskManagerStart = taskManagerMock.createStart(); diff --git a/x-pack/plugins/observability_solution/slo/server/services/tasks/orphan_summary_cleanup_task.ts b/x-pack/plugins/observability_solution/slo/server/services/tasks/orphan_summary_cleanup_task.ts index bdbb955050358..c3d56854f4946 100644 --- a/x-pack/plugins/observability_solution/slo/server/services/tasks/orphan_summary_cleanup_task.ts +++ b/x-pack/plugins/observability_solution/slo/server/services/tasks/orphan_summary_cleanup_task.ts @@ -15,8 +15,8 @@ import { AggregationsCompositeAggregateKey } from '@elastic/elasticsearch/lib/ap import { ALL_SPACES_ID } from '@kbn/spaces-plugin/common/constants'; import { StoredSLODefinition } from '../../domain/models'; import { SO_SLO_TYPE } from '../../saved_objects'; -import { SloConfig } from '../..'; import { SLO_SUMMARY_DESTINATION_INDEX_PATTERN } from '../../../common/constants'; +import { SLOConfig } from '../../types'; export const TASK_TYPE = 'SLO:ORPHAN_SUMMARIES-CLEANUP-TASK'; @@ -49,9 +49,9 @@ export class SloOrphanSummaryCleanupTask { private taskManager?: TaskManagerStartContract; private soClient?: SavedObjectsClientContract; private esClient?: ElasticsearchClient; - private config: SloConfig; + private config: SLOConfig; - constructor(taskManager: TaskManagerSetupContract, logger: Logger, config: SloConfig) { + constructor(taskManager: TaskManagerSetupContract, logger: Logger, config: SLOConfig) { this.logger = logger; this.config = config; diff --git a/x-pack/plugins/observability_solution/slo/server/types.ts b/x-pack/plugins/observability_solution/slo/server/types.ts index 86bf0ac0b94ab..b9269f49c4d9f 100644 --- a/x-pack/plugins/observability_solution/slo/server/types.ts +++ b/x-pack/plugins/observability_solution/slo/server/types.ts @@ -5,15 +5,49 @@ * 2.0. */ -import type { LicensingApiRequestHandlerContext } from '@kbn/licensing-plugin/server'; -import type { AlertingApiRequestHandlerContext } from '@kbn/alerting-plugin/server'; -import type { CustomRequestHandlerContext, CoreRequestHandlerContext } from '@kbn/core/server'; +import type { PluginSetupContract, PluginStartContract } from '@kbn/alerting-plugin/server'; +import { CloudSetup } from '@kbn/cloud-plugin/server'; +import { DataViewsServerPluginStart } from '@kbn/data-views-plugin/server'; +import { FeaturesPluginSetup } from '@kbn/features-plugin/server'; +import type { LicensingPluginSetup, LicensingPluginStart } from '@kbn/licensing-plugin/server'; +import { + RuleRegistryPluginSetupContract, + RuleRegistryPluginStartContract, +} from '@kbn/rule-registry-plugin/server'; +import { SharePluginSetup } from '@kbn/share-plugin/server'; +import { SpacesPluginSetup, SpacesPluginStart } from '@kbn/spaces-plugin/server'; +import { + TaskManagerSetupContract, + TaskManagerStartContract, +} from '@kbn/task-manager-plugin/server'; +import { UsageCollectionSetup } from '@kbn/usage-collection-plugin/server'; -/** - * @internal - */ -export type SloRequestHandlerContext = CustomRequestHandlerContext<{ - licensing: LicensingApiRequestHandlerContext; - alerting: AlertingApiRequestHandlerContext; - core: Promise; -}>; +export type { SLOConfig } from '../common/config'; + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface SLOServerSetup {} + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface SLOServerStart {} + +export interface SLOPluginSetupDependencies { + alerting: PluginSetupContract; + ruleRegistry: RuleRegistryPluginSetupContract; + share: SharePluginSetup; + features: FeaturesPluginSetup; + taskManager: TaskManagerSetupContract; + spaces: SpacesPluginSetup; + cloud?: CloudSetup; + usageCollection: UsageCollectionSetup; + licensing: LicensingPluginSetup; + dataViews: DataViewsServerPluginStart; +} + +export interface SLOPluginStartDependencies { + alerting: PluginStartContract; + taskManager: TaskManagerStartContract; + spaces?: SpacesPluginStart; + ruleRegistry: RuleRegistryPluginStartContract; + dataViews: DataViewsServerPluginStart; + licensing: LicensingPluginStart; +} diff --git a/x-pack/plugins/observability_solution/slo/tsconfig.json b/x-pack/plugins/observability_solution/slo/tsconfig.json index e10293188e644..23efcc39698b1 100644 --- a/x-pack/plugins/observability_solution/slo/tsconfig.json +++ b/x-pack/plugins/observability_solution/slo/tsconfig.json @@ -96,6 +96,8 @@ "@kbn/core-theme-browser", "@kbn/ebt-tools", "@kbn/observability-alerting-rule-utils", - "@kbn/discover-shared-plugin" + "@kbn/discover-shared-plugin", + "@kbn/server-route-repository-client", + "@kbn/server-route-repository-utils" ] } diff --git a/x-pack/plugins/observability_solution/synthetics/public/plugin.ts b/x-pack/plugins/observability_solution/synthetics/public/plugin.ts index 15de2de6d5eee..e8fbedfa0ecb1 100644 --- a/x-pack/plugins/observability_solution/synthetics/public/plugin.ts +++ b/x-pack/plugins/observability_solution/synthetics/public/plugin.ts @@ -60,7 +60,7 @@ import { ServerlessPluginSetup, ServerlessPluginStart } from '@kbn/serverless/pu import type { UiActionsSetup } from '@kbn/ui-actions-plugin/public'; import type { PresentationUtilPluginStart } from '@kbn/presentation-util-plugin/public'; import { DashboardStart, DashboardSetup } from '@kbn/dashboard-plugin/public'; -import { SloPublicStart } from '@kbn/slo-plugin/public'; +import { SLOPublicStart } from '@kbn/slo-plugin/public'; import { registerSyntheticsEmbeddables } from './apps/embeddables/register_embeddables'; import { kibanaService } from './utils/kibana_service'; import { PLUGIN } from '../common/constants/plugin'; @@ -111,7 +111,7 @@ export interface ClientPluginsStart { usageCollection: UsageCollectionStart; serverless: ServerlessPluginStart; licenseManagement?: LicenseManagementUIPluginSetup; - slo?: SloPublicStart; + slo?: SLOPublicStart; presentationUtil: PresentationUtilPluginStart; dashboard: DashboardStart; } diff --git a/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/find_slo.ts b/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/find_slo.ts index 1d1be9dc338af..6c49cb9df751e 100644 --- a/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/find_slo.ts +++ b/x-pack/test/api_integration/deployment_agnostic/apis/observability/slo/find_slo.ts @@ -67,7 +67,6 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { .get(`/api/observability/slos`) .set(adminRoleAuthc.apiKeyHeader) .set(internalHeaders) - .set('elastic-api-version', '1') .send(); expect(response.body.results).length(2); @@ -76,7 +75,6 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { .get(`/api/observability/slos?kqlQuery=slo.name%3Airrelevant`) .set(adminRoleAuthc.apiKeyHeader) .set(internalHeaders) - .set('elastic-api-version', '1') .send() .expect(200); @@ -87,7 +85,6 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { .get(`/api/observability/slos?kqlQuery=slo.name%3Aintegration`) .set(adminRoleAuthc.apiKeyHeader) .set(internalHeaders) - .set('elastic-api-version', '1') .send() .expect(200);