From 593d3911728cf68093925836ae2031746c7db6cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Fern=C3=A1ndez=20Haro?= Date: Wed, 1 May 2024 17:41:31 +0200 Subject: [PATCH] Add `@typescript-eslint/no-floating-promises` (#181456) Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Aleh Zasypkin Co-authored-by: Patrick Mueller --- examples/response_stream/server/plugin.ts | 2 +- .../server/routes/reducer_stream.ts | 69 +++--- .../server/routes/single_string_stream.ts | 4 +- examples/search_examples/server/plugin.ts | 2 +- .../http/cookie_session_storage.test.ts | 2 +- .../server/integration_tests/http/oas.test.ts | 2 +- .../integration_tests/http/router.test.ts | 6 +- .../migrations/group2/cleanup.test.ts | 6 +- .../migrations/group3/actions/actions.test.ts | 8 +- .../group3/actions/actions_test_suite.ts | 8 +- .../group3/default_search_fields.test.ts | 4 +- .../group3/split_failed_to_clone.test.ts | 4 +- .../group3/type_registrations.test.ts | 4 +- .../wait_for_migration_completion.test.ts | 2 +- .../migrations/kibana_migrator_test_kit.ts | 6 +- .../validation/validator.test.ts | 4 +- .../eslint/types.eslint.config.template.js | 10 + .../server/core/core.test.ts | 10 +- .../server/rpc/procedures/bulk_get.test.ts | 16 +- .../server/rpc/procedures/create.test.ts | 12 +- .../server/rpc/procedures/delete.test.ts | 12 +- .../server/rpc/procedures/get.test.ts | 12 +- .../server/rpc/procedures/msearch.test.ts | 8 +- .../server/rpc/procedures/search.test.ts | 12 +- .../server/rpc/procedures/update.test.ts | 12 +- .../server/rpc/rpc_service.test.ts | 20 +- .../query/route_handler_context.test.ts | 10 +- .../server/search/collectors/search/usage.ts | 4 +- .../data/server/search/search_service.ts | 2 +- .../search/session/session_service.test.ts | 58 ++--- .../expressions/load_index_pattern.test.ts | 2 +- .../server/rest_api_routes/internal/fields.ts | 2 +- .../rest_api_routes/internal/fields_for.ts | 2 +- .../public/create_data_view.test.ts | 4 +- .../public/default_data_view.test.ts | 8 +- .../public/delete_data_view.test.ts | 4 +- .../public/fields/update_fields.test.ts | 4 +- .../public/get_data_view.test.ts | 4 +- .../public/get_data_views.test.ts | 4 +- .../public/has_user_data_view.test.ts | 4 +- .../create_runtime_field.test.ts | 4 +- .../delete_runtime_field.test.ts | 4 +- .../runtime_fields/get_runtime_field.test.ts | 4 +- .../runtime_fields/put_runtime_field.test.ts | 4 +- .../update_runtime_field.test.ts | 4 +- .../public/update_data_view.test.ts | 4 +- .../server/locator/title_from_locator.test.ts | 2 +- .../server/routes/file_kind/upload.test.ts | 2 +- .../files/server/routes/file_kind/upload.ts | 2 +- .../cloud/cloud_provider_collector.ts | 2 +- .../cloud/detector/cloud_detector.mock.ts | 2 +- src/plugins/maps_ems/server/plugin.ts | 5 +- src/plugins/navigation/server/plugin.ts | 14 +- .../server/stream_factory.test.ts | 4 +- x-pack/plugins/actions/server/plugin.ts | 10 +- .../server/routes/connector/get/get.test.ts | 2 +- .../routes/connector/get_all/get_all.test.ts | 2 +- .../get_all_system/get_all_system.test.ts | 2 +- .../connector/list_types/list_types.test.ts | 2 +- .../list_types_system.test.ts | 2 +- .../actions/server/routes/create.test.ts | 2 +- .../actions/server/routes/delete.test.ts | 2 +- .../actions/server/routes/execute.test.ts | 2 +- .../routes/get_oauth_access_token.test.ts | 2 +- .../server/routes/legacy/create.test.ts | 2 +- .../server/routes/legacy/delete.test.ts | 2 +- .../server/routes/legacy/execute.test.ts | 2 +- .../actions/server/routes/legacy/get.test.ts | 2 +- .../server/routes/legacy/get_all.test.ts | 2 +- .../routes/legacy/list_action_types.test.ts | 2 +- .../server/routes/legacy/update.test.ts | 2 +- .../actions/server/routes/update.test.ts | 2 +- x-pack/plugins/actions/server/usage/task.ts | 4 +- x-pack/plugins/aiops/server/plugin.ts | 2 +- .../analysis_handlers/grouping_handler.ts | 2 +- .../analysis_handlers/histogram_handler.ts | 2 +- .../route_handler_factory.ts | 2 +- .../lib/install_with_timeout.ts | 10 +- .../methods/delete/delete_backfill.test.ts | 2 +- .../methods/delete/delete_backfill.ts | 2 +- .../rule/methods/create/create_rule.test.ts | 2 +- .../rule/methods/update/update_rule.test.ts | 2 +- .../bulk_mark_api_keys_for_invalidation.ts | 2 +- x-pack/plugins/alerting/server/plugin.ts | 16 +- .../apis/delete/delete_backfill_route.test.ts | 2 +- .../apis/find/find_backfill_route.test.ts | 2 +- .../apis/get/get_backfill_route.test.ts | 2 +- .../schedule/schedule_backfill_route.test.ts | 2 +- .../server/routes/delete_rule.test.ts | 2 +- .../routes/get_action_error_log.test.ts | 2 +- .../routes/get_rule_alert_summary.test.ts | 2 +- .../routes/get_rule_execution_kpi.test.ts | 2 +- .../routes/get_rule_execution_log.test.ts | 2 +- .../server/routes/legacy/create.test.ts | 2 +- .../server/routes/legacy/delete.test.ts | 2 +- .../server/routes/legacy/find.test.ts | 2 +- .../alerting/server/routes/legacy/get.test.ts | 2 +- .../routes/legacy/list_alert_types.test.ts | 2 +- .../server/routes/legacy/update.test.ts | 2 +- .../archive_maintenance_window_route.test.ts | 4 +- ...bulk_get_maintenance_windows_route.test.ts | 4 +- .../create_maintenance_window_route.test.ts | 4 +- .../delete_maintenance_window_route.test.ts | 4 +- .../find_maintenance_windows_route.test.ts | 4 +- .../finish_maintenance_window_route.test.ts | 4 +- .../get/get_maintenance_window_route.test.ts | 4 +- ...t_active_maintenance_windows_route.test.ts | 2 +- .../update_maintenance_window_route.test.ts | 4 +- .../aggregate/aggregate_rules_route.test.ts | 2 +- .../bulk_delete_rules_route.test.ts | 2 +- .../bulk_disable_rules_route.test.ts | 2 +- .../bulk_edit/bulk_edit_rules_route.test.ts | 2 +- .../bulk_enable_rules_route.test.ts | 2 +- .../rule/apis/clone/clone_rule_route.test.ts | 2 +- .../apis/create/create_rule_route.test.ts | 2 +- .../rule/apis/find/find_rules_route.test.ts | 2 +- .../rule/apis/get/get_rule_route.test.ts | 2 +- .../apis/resolve/resolve_rule_route.test.ts | 2 +- .../rule/apis/tags/get_rule_tags.test.ts | 2 +- .../apis/update/update_rule_route.test.ts | 2 +- .../alerting/server/routes/rule_types.test.ts | 2 +- .../lib/add_generated_action_values.test.ts | 2 +- .../tests/get_action_error_log.test.ts | 6 +- .../tests/get_alert_summary.test.ts | 6 +- .../tests/get_execution_log.test.ts | 14 +- .../rules_client/tests/update_api_key.test.ts | 2 +- .../server/task_runner/task_runner.ts | 2 +- x-pack/plugins/alerting/server/usage/task.ts | 2 +- x-pack/plugins/canvas/server/plugin.ts | 2 +- .../canvas/server/routes/shareables/zip.ts | 2 +- .../server/authorization/authorization.ts | 2 +- ...able_state_and_external_references.test.ts | 4 +- .../plugins/cases/server/telemetry/index.ts | 2 +- .../cloud_defend/server/lib/fleet_util.ts | 12 +- x-pack/plugins/cloud_defend/server/plugin.ts | 33 +-- .../fleet_integration/fleet_integration.ts | 12 +- .../cloud_security_posture/server/plugin.ts | 168 +++++++------- .../server/routes/setup_routes.ts | 2 +- .../server/plugin.ts | 2 +- .../data_stream/results_data_stream.test.ts | 4 +- .../server/plugin.ts | 16 +- .../server/ai_assistant_service/index.ts | 2 +- .../server/lib/executor.test.ts | 9 +- .../elastic_assistant/server/lib/executor.ts | 2 +- .../execute_custom_llm_chain/index.test.ts | 4 +- .../execute_custom_llm_chain/index.ts | 2 +- .../routes/post_actions_connector_execute.ts | 2 +- .../encrypted_saved_objects/server/mocks.ts | 8 +- .../encrypted_saved_objects/tsconfig.json | 1 + .../lib/enterprise_search_config_api.test.ts | 2 +- .../create_ml_inference_pipeline.test.ts | 4 +- ...t_ml_inference_pipeline_processors.test.ts | 4 +- .../server/lib/ml/fetch_ml_models.test.ts | 4 +- .../ml/get_ml_model_deployment_status.test.ts | 4 +- .../lib/ml/start_ml_model_deployment.test.ts | 4 +- .../lib/ml/start_ml_model_download.test.ts | 4 +- .../get_ml_inference_pipelines.test.ts | 4 +- .../enterprise_search/server/plugin.ts | 6 +- .../app_search/adaptive_relevance.test.ts | 20 +- .../server/routes/app_search/engines.test.ts | 20 +- .../routes/app_search/onboarding.test.ts | 4 +- .../routes/app_search/result_settings.test.ts | 8 +- .../routes/app_search/search_settings.test.ts | 12 +- .../routes/app_search/search_ui.test.ts | 4 +- .../routes/workplace_search/oauth.test.ts | 12 +- .../routes/workplace_search/security.test.ts | 8 +- .../routes/workplace_search/sources.test.ts | 8 +- .../event_log/server/event_log_client.test.ts | 4 +- .../event_log/server/event_logger.test.ts | 4 +- x-pack/plugins/event_log/server/plugin.ts | 17 +- .../server/telemetry/usage_collector.ts | 2 +- x-pack/plugins/fleet/server/plugin.ts | 16 +- x-pack/plugins/fleet/server/routes/index.ts | 2 +- .../services/agent_policy_create.test.ts | 18 +- .../server/services/agents/action_runner.ts | 8 +- .../services/artifacts/artifacts.test.ts | 6 +- .../server/services/download_source.test.ts | 4 +- .../server/services/epm/archive/extract.ts | 6 +- .../epm/kibana/assets/install.test.ts | 2 +- .../epm/packages/_install_package.test.ts | 6 +- .../server/services/epm/packages/install.ts | 2 +- .../services/epm/registry/index.test.ts | 2 +- .../services/epm/registry/requests.test.ts | 4 +- .../fleet/server/services/files/index.test.ts | 4 +- .../fleet/server/services/fleet_proxies.ts | 16 +- .../server/services/fleet_usage_logger.ts | 2 +- .../fleet/server/services/output.test.ts | 6 +- .../server/services/package_policy.test.ts | 6 +- .../security/message_signing_service.ts | 2 +- .../security/uninstall_token_service/index.ts | 4 +- .../fleet/server/telemetry/sender.test.ts | 4 +- .../plugins/fleet/server/telemetry/sender.ts | 18 +- .../license_api_guard/server/license.test.ts | 9 +- .../license_management/server/plugin.ts | 2 +- ...ception_list_items_point_in_time_finder.ts | 4 +- ...ind_exception_list_point_in_time_finder.ts | 4 +- ...ception_list_items_point_in_time_finder.ts | 4 +- .../models/data_recognizer/data_recognizer.ts | 2 +- .../models/job_service/model_snapshots.ts | 2 +- .../json_schema_service.ts | 10 +- x-pack/plugins/ml/server/plugin.ts | 12 +- .../server/kibana_monitoring/bulk_uploader.ts | 23 +- x-pack/plugins/monitoring/server/plugin.ts | 2 +- .../services/connectors_email_service.test.ts | 16 +- .../services/licensed_email_service.test.ts | 4 +- .../apm/server/lib/apm_telemetry/index.ts | 64 +++--- .../create_apm_event_client/index.test.ts | 2 +- .../apm/server/plugin.ts | 24 +- .../settings/agent_configuration/route.ts | 2 +- .../create_or_update_custom_link.test.ts | 8 +- ..._legacy_apm_indices_to_space_aware.test.ts | 4 +- .../asset_manager/server/plugin.ts | 2 +- ...er_inventory_metric_threshold_rule_type.ts | 2 +- .../register_log_threshold_rule_type.ts | 2 +- .../register_metric_threshold_rule_type.ts | 2 +- .../log_entries/log_entries_service.ts | 2 +- .../observability/server/plugin.ts | 2 +- .../bedrock/process_bedrock_stream.ts | 2 +- .../server/service/client/index.test.ts | 3 +- .../profiling/server/plugin.ts | 67 +++--- .../slo/server/plugin.ts | 62 ++--- .../slo/server/routes/register_routes.ts | 4 +- .../slo/server/routes/slo/route.ts | 50 ++--- .../tasks/orphan_summary_cleanup_task.ts | 4 +- .../synthetics/server/lib.ts | 11 +- .../synthetics/server/plugin.ts | 4 +- .../add_monitor/add_monitor_api.ts | 11 +- .../synthetics_monitor/get_all_monitors.ts | 3 +- .../synthetics_private_location.ts | 2 +- .../project_monitor_formatter.ts | 3 +- .../synthetics_monitor_client.ts | 3 +- .../synthetics_service.test.ts | 5 +- .../synthetics_service/synthetics_service.ts | 8 +- .../server/synthetics_service/utils/mocks.ts | 2 +- .../server/telemetry/sender.test.ts | 4 +- .../synthetics/server/telemetry/sender.ts | 17 +- .../uptime/server/legacy_uptime/lib/lib.ts | 2 +- .../create_transforms/create_transforms.ts | 12 +- .../osquery/server/lib/telemetry/receiver.ts | 2 +- .../osquery/server/lib/update_global_packs.ts | 6 +- x-pack/plugins/osquery/server/plugin.ts | 142 ++++++------ .../reporting/server/lib/store/store.test.ts | 2 +- x-pack/plugins/rule_registry/server/plugin.ts | 31 +-- .../resource_installer.test.ts | 6 +- .../server/search_strategy/search_strategy.ts | 4 +- .../server/browsers/chromium/driver.ts | 6 +- .../chromium/driver_factory/index.test.ts | 2 +- .../browsers/chromium/driver_factory/index.ts | 4 +- .../server/formats/pdf/index.ts | 4 +- .../server/lib/notebook_catalog.test.ts | 12 +- .../server/lib/conversational_chain.test.ts | 4 +- .../server/lib/conversational_chain.ts | 2 +- .../search_playground/server/routes.ts | 21 +- .../saved_objects/ensure_authorized.test.ts | 6 +- .../endpoint/lib/artifacts/task.test.ts | 2 +- .../complete_external_actions_task.ts | 6 +- ...plete_external_actions_task_runner.test.ts | 4 +- .../server/endpoint/routes/resolver.ts | 17 +- .../server/endpoint/routes/resolver/events.ts | 3 +- .../endpoint/routes/resolver/tree/handler.ts | 7 +- .../artifacts/unified_manifest_client.ts | 6 +- .../server/endpoint/utils/queue_processor.ts | 2 +- .../fleet_integration.test.ts | 4 +- .../fleet_integration/fleet_integration.ts | 6 +- .../handlers/create_event_filters.ts | 8 +- .../remove_protection_updates_note.ts | 7 +- ...y_create_rule_actions_saved_object.test.ts | 12 +- ...gacy_get_rule_actions_saved_object.test.ts | 4 +- .../rule_preview/api/preview_rules/route.ts | 2 +- ...dule_notification_response_actions.test.ts | 8 +- .../schedule_notification_response_actions.ts | 35 +-- .../asset_criticality_data_client.test.ts | 12 +- .../risk_score/tasks/risk_scoring_task.ts | 2 +- .../product_features_service.test.ts | 20 +- .../server/lib/telemetry/receiver.ts | 2 +- .../server/lib/telemetry/sender.ts | 17 +- .../server/lib/telemetry/task_metrics.test.ts | 10 +- .../lib/telemetry/tasks/configuration.ts | 6 +- .../lib/telemetry/tasks/detection_rule.ts | 6 +- .../server/lib/telemetry/tasks/diagnostic.ts | 6 +- .../server/lib/telemetry/tasks/endpoint.ts | 4 +- .../server/lib/telemetry/tasks/filterlists.ts | 6 +- .../telemetry/tasks/prebuilt_rule_alerts.ts | 10 +- .../lib/telemetry/tasks/security_lists.ts | 4 +- .../server/lib/telemetry/tasks/timelines.ts | 6 +- .../telemetry/tasks/timelines_diagnostic.ts | 6 +- .../routes/timelines/copy_timeline/index.ts | 2 +- .../security_solution/server/plugin.ts | 211 ++++++++++-------- .../server/usage/queries/get_case_comments.ts | 2 +- .../usage/queries/get_detection_rules.ts | 2 +- .../usage/queries/legacy_get_rule_actions.ts | 2 +- .../server/plugin.ts | 28 ++- .../server/lib/indices/fetch_index.test.ts | 20 +- .../serverless_search/server/plugin.ts | 35 ++- .../server/routes/api_key_routes.ts | 4 +- .../server/routes/indices_routes.ts | 3 +- .../create_default_space.test.ts | 4 +- .../routes/api/external/copy_to_space.ts | 44 ++-- .../external/disable_legacy_url_aliases.ts | 12 +- .../spaces_client/spaces_client.test.ts | 8 +- .../lib/get_shape_filters.test.ts | 4 +- .../connector_types/servicenow_sir/service.ts | 2 +- .../server/buffered_task_store.test.ts | 2 +- .../server/lib/bulk_operation_buffer.test.ts | 81 +++---- .../server/lib/remove_if_exists.test.ts | 2 +- .../server/lib/result_type.test.ts | 4 +- .../server/metrics/task_metrics_collector.ts | 2 +- x-pack/plugins/task_manager/server/mocks.ts | 2 +- .../server/polling/task_poller.ts | 4 +- .../plugins/task_manager/server/task_pool.ts | 22 +- .../server/task_scheduling.test.ts | 9 +- .../task_manager/server/task_scheduling.ts | 8 +- .../threat_intelligence/server/plugin.ts | 2 +- x-pack/plugins/timelines/server/plugin.ts | 2 +- x-pack/plugins/transform/server/plugin.ts | 57 +++-- .../api/audit_messages/register_route.ts | 15 +- .../api/delete_transforms/register_route.ts | 11 +- .../route_handler_factory.ts | 5 +- .../api/field_histograms/register_route.ts | 11 +- .../reauthorize_transforms/register_route.ts | 11 +- .../route_handler_factory.ts | 4 +- .../api/reset_transforms/register_route.ts | 9 +- .../schedule_now_transforms/register_route.ts | 9 +- .../api/start_transforms/register_route.ts | 9 +- .../api/stop_transforms/register_route.ts | 9 +- .../api/transforms_all/register_route.ts | 13 +- .../api/transforms_create/register_route.ts | 15 +- .../route_handler_factory.ts | 4 +- .../api/transforms_nodes/register_route.ts | 11 +- .../transforms_nodes/route_handler_factory.ts | 5 +- .../api/transforms_preview/register_route.ts | 9 +- .../api/transforms_single/register_route.ts | 11 +- .../transforms_stats_all/register_route.ts | 15 +- .../transforms_stats_single/register_route.ts | 13 +- .../api/transforms_update/register_route.ts | 13 +- x-pack/plugins/transform/server/types.ts | 8 +- .../transform/server/usage/collector.ts | 7 +- .../server/data/lib/time_series_query.test.ts | 2 +- .../triggers_actions_ui/server/plugin.ts | 17 +- .../server/routes/config.test.ts | 4 +- .../server/routes/config.ts | 4 +- .../server/lib/reindexing/worker.ts | 37 +-- .../upgrade_assistant/server/plugin.ts | 2 +- .../plugins/kibana_cors_test/server/plugin.ts | 4 +- .../server/init_routes.ts | 4 +- 345 files changed, 1664 insertions(+), 1430 deletions(-) diff --git a/examples/response_stream/server/plugin.ts b/examples/response_stream/server/plugin.ts index 9620a58ae517b..6bb0c55003059 100644 --- a/examples/response_stream/server/plugin.ts +++ b/examples/response_stream/server/plugin.ts @@ -27,7 +27,7 @@ export class ResponseStreamPlugin implements Plugin { public setup(core: CoreSetup, plugins: ResponseStreamSetupPlugins) { const router = core.http.createRouter(); - core.getStartServices().then(([_, depsStart]) => { + void core.getStartServices().then(([_, depsStart]) => { defineReducerStreamRoute(router, this.logger); defineSimpleStringStreamRoute(router, this.logger); }); diff --git a/examples/response_stream/server/routes/reducer_stream.ts b/examples/response_stream/server/routes/reducer_stream.ts index 5e03cd0732e74..02606b8c44756 100644 --- a/examples/response_stream/server/routes/reducer_stream.ts +++ b/examples/response_stream/server/routes/reducer_stream.ts @@ -85,44 +85,45 @@ export const defineReducerStreamRoute = (router: IRouter, logger: Logger) => { let progress = 0; async function pushStreamUpdate() { - setTimeout(() => { - try { - progress++; - - if (progress > 100 || shouldStop) { - end(); - return; - } - - push(updateProgressAction(progress)); - - const randomEntity = entities[Math.floor(Math.random() * entities.length)]; - const randomAction = actions[Math.floor(Math.random() * actions.length)]; - - if (randomAction === 'add') { - const randomCommits = Math.floor(Math.random() * 100); - push(addToEntityAction(randomEntity, randomCommits)); - } else if (randomAction === 'delete') { - push(deleteEntityAction(randomEntity)); - } else if (randomAction === 'throw-error') { - // Throw an error. It should not crash Kibana! - // It should be caught and logged to the Kibana server console. - throw new Error('There was a (simulated) server side error!'); - } else if (randomAction === 'emit-error') { - // Emit an error as a stream action. - push(errorAction('(Simulated) error pushed to the stream')); - return; - } - - pushStreamUpdate(); - } catch (e) { - logger.error(e); + await new Promise((resolve) => + setTimeout(resolve, Math.floor(Math.random() * maxTimeoutMs)) + ); + try { + progress++; + + if (progress > 100 || shouldStop) { + end(); + return; } - }, Math.floor(Math.random() * maxTimeoutMs)); + + push(updateProgressAction(progress)); + + const randomEntity = entities[Math.floor(Math.random() * entities.length)]; + const randomAction = actions[Math.floor(Math.random() * actions.length)]; + + if (randomAction === 'add') { + const randomCommits = Math.floor(Math.random() * 100); + push(addToEntityAction(randomEntity, randomCommits)); + } else if (randomAction === 'delete') { + push(deleteEntityAction(randomEntity)); + } else if (randomAction === 'throw-error') { + // Throw an error. It should not crash Kibana! + // It should be caught and logged to the Kibana server console. + throw new Error('There was a (simulated) server side error!'); + } else if (randomAction === 'emit-error') { + // Emit an error as a stream action. + push(errorAction('(Simulated) error pushed to the stream')); + return; + } + + void pushStreamUpdate(); + } catch (e) { + logger.error(e); + } } // do not call this using `await` so it will run asynchronously while we return the stream already. - pushStreamUpdate(); + void pushStreamUpdate(); return response.ok(responseWithHeaders); } diff --git a/examples/response_stream/server/routes/single_string_stream.ts b/examples/response_stream/server/routes/single_string_stream.ts index 26c26f0fc6b66..d9cb65686b71e 100644 --- a/examples/response_stream/server/routes/single_string_stream.ts +++ b/examples/response_stream/server/routes/single_string_stream.ts @@ -67,7 +67,7 @@ export const defineSimpleStringStreamRoute = (router: IRouter, logger: Logger) = await timeout(Math.floor(Math.random() * maxTimeoutMs)); if (!shouldStop) { - pushStreamUpdate(); + void pushStreamUpdate(); } } else { end(); @@ -78,7 +78,7 @@ export const defineSimpleStringStreamRoute = (router: IRouter, logger: Logger) = } // do not call this using `await` so it will run asynchronously while we return the stream already. - pushStreamUpdate(); + void pushStreamUpdate(); return response.ok(responseWithHeaders); } diff --git a/examples/search_examples/server/plugin.ts b/examples/search_examples/server/plugin.ts index 57a8b055f9b44..27680a3287aba 100644 --- a/examples/search_examples/server/plugin.ts +++ b/examples/search_examples/server/plugin.ts @@ -48,7 +48,7 @@ export class SearchExamplesPlugin this.logger.debug('search_examples: Setup'); const router = core.http.createRouter(); - core.getStartServices().then(([_, depsStart]) => { + void core.getStartServices().then(([_, depsStart]) => { const myStrategy = mySearchStrategyProvider(depsStart.data); const fibonacciStrategy = fibonacciStrategyProvider(); deps.data.search.registerSearchStrategy('myStrategy', myStrategy); diff --git a/src/core/server/integration_tests/http/cookie_session_storage.test.ts b/src/core/server/integration_tests/http/cookie_session_storage.test.ts index 90343da759ccb..4a71502db0ccb 100644 --- a/src/core/server/integration_tests/http/cookie_session_storage.test.ts +++ b/src/core/server/integration_tests/http/cookie_session_storage.test.ts @@ -439,7 +439,7 @@ describe('Cookie based SessionStorage', () => { await server.preboot(prebootDeps); const { server: innerServer } = await server.setup(setupDeps); - expect( + await expect( createCookieSessionStorageFactory(logger.get(), innerServer, { ...cookieOptions, sameSite: 'None', diff --git a/src/core/server/integration_tests/http/oas.test.ts b/src/core/server/integration_tests/http/oas.test.ts index d0adbb0d29ea7..602b9c76cefa2 100644 --- a/src/core/server/integration_tests/http/oas.test.ts +++ b/src/core/server/integration_tests/http/oas.test.ts @@ -67,7 +67,7 @@ afterEach(async () => { it('is disabled by default', async () => { const server = await startService(); - supertest(server.listener).get('/api/oas').expect(404); + await supertest(server.listener).get('/api/oas').expect(404); }); it('handles requests when enabled', async () => { diff --git a/src/core/server/integration_tests/http/router.test.ts b/src/core/server/integration_tests/http/router.test.ts index 42cd093244a48..e7640e39c3263 100644 --- a/src/core/server/integration_tests/http/router.test.ts +++ b/src/core/server/integration_tests/http/router.test.ts @@ -333,15 +333,15 @@ describe('Options', () => { let i = 0; const intervalId = setInterval(() => { if (i < body.length) { - request.write(body[i++]); + void request.write(body[i++]); } else { clearInterval(intervalId); - request.end((err, res) => { + void request.end((err, res) => { resolve(res); }); } }, interval); - request.on('error', (err) => { + void request.on('error', (err) => { clearInterval(intervalId); reject(err); }); diff --git a/src/core/server/integration_tests/saved_objects/migrations/group2/cleanup.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group2/cleanup.test.ts index 026eaa462aa54..7f04f37589f69 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group2/cleanup.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group2/cleanup.test.ts @@ -131,13 +131,13 @@ const setupBaseline = async () => { // inject corrupt saved objects directly using esClient await Promise.all( - savedObjects.map((savedObject) => { + savedObjects.map((savedObject) => client.create({ index: defaultKibanaIndex, refresh: 'wait_for', ...savedObject, - }); - }) + }) + ) ); return client; diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions.test.ts index 7a2a8b06c9b1c..2b6c7136519ff 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions.test.ts @@ -425,7 +425,7 @@ describe('migration actions', () => { const redStatusResponse = await client.cluster.health({ index: 'red_then_yellow_index' }); expect(redStatusResponse.status).toBe('red'); - client.indices.putSettings({ + void client.indices.putSettings({ index: 'red_then_yellow_index', body: { // Enable all shard allocation so that the index status turns yellow @@ -574,7 +574,7 @@ describe('migration actions', () => { let indexGreen = false; setTimeout(() => { - client.indices.putSettings({ + void client.indices.putSettings({ index: 'clone_red_then_green_index', body: { // Enable all shard allocation so that the index status goes green @@ -1844,7 +1844,7 @@ describe('migration actions', () => { let indexYellow = false; setTimeout(() => { - client.indices.putSettings({ + void client.indices.putSettings({ index: 'red_then_yellow_index', body: { // Renable allocation so that the status becomes yellow @@ -1897,7 +1897,7 @@ describe('migration actions', () => { let indexGreen = false; setTimeout(() => { - client.indices.putSettings({ + void client.indices.putSettings({ index: 'yellow_then_green_index', body: { // Set 0 replican so that this index becomes green diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts index a16041a73011e..c114293823cb7 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/actions/actions_test_suite.ts @@ -464,7 +464,7 @@ export const runActionTestSuite = ({ const redStatusResponse = await client.cluster.health({ index: 'red_then_yellow_index' }); expect(redStatusResponse.status).toBe('red'); - client.indices.putSettings({ + void client.indices.putSettings({ index: 'red_then_yellow_index', body: { // Enable all shard allocation so that the index status turns yellow @@ -619,7 +619,7 @@ export const runActionTestSuite = ({ let indexGreen = false; setTimeout(() => { - client.indices.putSettings({ + void client.indices.putSettings({ index: 'clone_red_then_green_index', body: { // Enable all shard allocation so that the index status goes green @@ -1898,7 +1898,7 @@ export const runActionTestSuite = ({ let indexYellow = false; setTimeout(() => { - client.indices.putSettings({ + void client.indices.putSettings({ index: 'red_then_yellow_index', body: { // Renable allocation so that the status becomes yellow @@ -1951,7 +1951,7 @@ export const runActionTestSuite = ({ let indexGreen = false; setTimeout(() => { - client.indices.putSettings({ + void client.indices.putSettings({ index: 'yellow_then_green_index', body: { // Set 0 replican so that this index becomes green diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/default_search_fields.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/default_search_fields.test.ts index 4101c22c23d50..52a1d68255332 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/default_search_fields.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/default_search_fields.test.ts @@ -11,9 +11,9 @@ import { createRoot } from '@kbn/core-test-helpers-kbn-server'; describe('SO default search fields', () => { let root: ReturnType; - afterEach(() => { + afterEach(async () => { try { - root?.shutdown(); + await root?.shutdown(); } catch (e) { /* trap */ } diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/split_failed_to_clone.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/split_failed_to_clone.test.ts index 1642e4059a885..306c91aae5902 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/split_failed_to_clone.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/split_failed_to_clone.test.ts @@ -132,14 +132,14 @@ describe.skip('when splitting .kibana into multiple indices and one clone fails' }); // cause a failure when cloning .kibana_slow_clone_* indices - client.cluster.putSettings({ persistent: { 'cluster.max_shards_per_node': 15 } }); + void client.cluster.putSettings({ persistent: { 'cluster.max_shards_per_node': 15 } }); await expect(runMigrationsWhichFailsWhenCloning()).rejects.toThrowError( /cluster_shard_limit_exceeded/ ); // remove the failure - client.cluster.putSettings({ persistent: { 'cluster.max_shards_per_node': 20 } }); + void client.cluster.putSettings({ persistent: { 'cluster.max_shards_per_node': 20 } }); const { runMigrations: runMigrations2ndTime } = await migratorTestKitFactory(); await runMigrations2ndTime(); diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/type_registrations.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/type_registrations.test.ts index 6b3d97206a094..43f0d03b86552 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/type_registrations.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/type_registrations.test.ts @@ -149,9 +149,9 @@ const previouslyRegisteredTypes = [ describe('SO type registrations', () => { let root: ReturnType; - afterEach(() => { + afterEach(async () => { try { - root?.shutdown(); + await root?.shutdown(); } catch (e) { /* trap */ } diff --git a/src/core/server/integration_tests/saved_objects/migrations/group3/wait_for_migration_completion.test.ts b/src/core/server/integration_tests/saved_objects/migrations/group3/wait_for_migration_completion.test.ts index 7d2a2bf8145cf..459cfc921badf 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/group3/wait_for_migration_completion.test.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/group3/wait_for_migration_completion.test.ts @@ -60,7 +60,7 @@ describe('migration with waitForCompletion=true', () => { await root.preboot(); await root.setup(); - root.start(); + void root.start(); const esClient = esServer.es.getClient(); await retryAsync( diff --git a/src/core/server/integration_tests/saved_objects/migrations/kibana_migrator_test_kit.ts b/src/core/server/integration_tests/saved_objects/migrations/kibana_migrator_test_kit.ts index db89ae88068fb..1440d6d9d91d3 100644 --- a/src/core/server/integration_tests/saved_objects/migrations/kibana_migrator_test_kit.ts +++ b/src/core/server/integration_tests/saved_objects/migrations/kibana_migrator_test_kit.ts @@ -123,7 +123,7 @@ export const getEsClient = async ({ // configure logging system const loggingConf = await firstValueFrom(configService.atPath('logging')); - loggingSystem.upgrade(loggingConf); + await loggingSystem.upgrade(loggingConf); return await getElasticsearchClient(configService, loggerFactory, kibanaVersion); }; @@ -148,7 +148,7 @@ export const getKibanaMigratorTestKit = async ({ // configure logging system const loggingConf = await firstValueFrom(configService.atPath('logging')); - loggingSystem.upgrade(loggingConf); + await loggingSystem.upgrade(loggingConf); const rawClient = await getElasticsearchClient(configService, loggerFactory, kibanaVersion); const client = clientWrapperFactory ? clientWrapperFactory(rawClient) : rawClient; @@ -568,7 +568,7 @@ export const getCurrentVersionTypeRegistry = async ({ await root.preboot(); const coreSetup = await root.setup(); const typeRegistry = coreSetup.savedObjects.getTypeRegistry(); - root.shutdown(); // do not await for it, or we might block the tests + void root.shutdown(); // do not await for it, or we might block the tests return typeRegistry; }; diff --git a/src/core/server/integration_tests/saved_objects/validation/validator.test.ts b/src/core/server/integration_tests/saved_objects/validation/validator.test.ts index 63909b14c290f..a0dc22440f1df 100644 --- a/src/core/server/integration_tests/saved_objects/validation/validator.test.ts +++ b/src/core/server/integration_tests/saved_objects/validation/validator.test.ts @@ -186,7 +186,7 @@ describe.skip('validates saved object types when a schema is provided', () => { }); it('is superseded by migration errors and does not run if a migration fails', async () => { - expect(async () => { + await expect(async () => { await savedObjectsClient.create( 'migration-error', { @@ -233,7 +233,7 @@ describe.skip('validates saved object types when a schema is provided', () => { describe('when validating with a config schema', () => { it('throws when an invalid attribute is provided', async () => { - expect(async () => { + await expect(async () => { await savedObjectsClient.create( 'schema-using-kbn-config', { diff --git a/src/dev/eslint/types.eslint.config.template.js b/src/dev/eslint/types.eslint.config.template.js index 08cbaf3b02325..db17de6f08e3e 100644 --- a/src/dev/eslint/types.eslint.config.template.js +++ b/src/dev/eslint/types.eslint.config.template.js @@ -24,4 +24,14 @@ module.exports = { rules: { '@typescript-eslint/consistent-type-exports': 'error', }, + overrides: [ + { + files: ['server/**/*'], + rules: { + // Let's focus on server-side errors first to avoid server crashes. + // We'll tackle /public eventually. + '@typescript-eslint/no-floating-promises': 'error', + }, + }, + ], }; diff --git a/src/plugins/content_management/server/core/core.test.ts b/src/plugins/content_management/server/core/core.test.ts index 2eafd1dc4df91..075eb6a383e8b 100644 --- a/src/plugins/content_management/server/core/core.test.ts +++ b/src/plugins/content_management/server/core/core.test.ts @@ -309,7 +309,7 @@ describe('Content Core', () => { { title: 'Hello' }, { id: '1234' } // We send this "id" option to specify the id of the content created ); - expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ + await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ contentTypeId: FOO_CONTENT_ID, result: { item: { @@ -327,7 +327,7 @@ describe('Content Core', () => { await fooContentCrud!.create(ctx, { title: 'Hello' }, { id: '1234' }); await fooContentCrud!.update(ctx, '1234', { title: 'changed' }); - expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ + await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ contentTypeId: FOO_CONTENT_ID, result: { item: { @@ -363,7 +363,7 @@ describe('Content Core', () => { }, }); - expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ + await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ contentTypeId: FOO_CONTENT_ID, result: { item: { @@ -380,14 +380,14 @@ describe('Content Core', () => { const { fooContentCrud, ctx, cleanUp } = setup({ registerFooType: true }); await fooContentCrud!.create(ctx, { title: 'Hello' }, { id: '1234' }); - expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ + await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ contentTypeId: FOO_CONTENT_ID, result: { item: expect.any(Object), }, }); await fooContentCrud!.delete(ctx, '1234'); - expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ + await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({ contentTypeId: FOO_CONTENT_ID, result: { item: undefined, diff --git a/src/plugins/content_management/server/rpc/procedures/bulk_get.test.ts b/src/plugins/content_management/server/rpc/procedures/bulk_get.test.ts index baeb9c08471c7..d79af15b136d2 100644 --- a/src/plugins/content_management/server/rpc/procedures/bulk_get.test.ts +++ b/src/plugins/content_management/server/rpc/procedures/bulk_get.test.ts @@ -264,16 +264,16 @@ describe('RPC -> bulkGet()', () => { }); describe('validation', () => { - test('should validate that content type definition exist', () => { + test('should validate that content type definition exist', async () => { const { ctx } = setup(); - expect(() => fn(ctx, { contentTypeId: 'unknown', ids: ['123', '456'] })).rejects.toEqual( - new Error('Content [unknown] is not registered.') - ); + await expect(() => + fn(ctx, { contentTypeId: 'unknown', ids: ['123', '456'] }) + ).rejects.toEqual(new Error('Content [unknown] is not registered.')); }); - test('should throw if the request version is higher than the registered version', () => { + test('should throw if the request version is higher than the registered version', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: FOO_CONTENT_ID, ids: ['123', '456'], @@ -284,9 +284,9 @@ describe('RPC -> bulkGet()', () => { }); describe('object versioning', () => { - test('should expose a utility to transform and validate services objects', () => { + test('should expose a utility to transform and validate services objects', async () => { const { ctx, storage } = setup(); - fn(ctx, { contentTypeId: FOO_CONTENT_ID, ids: ['1234'], version: 1 }); + await fn(ctx, { contentTypeId: FOO_CONTENT_ID, ids: ['1234'], version: 1 }); const [[storageContext]] = storage.bulkGet.mock.calls; // getTransforms() utils should be available from context diff --git a/src/plugins/content_management/server/rpc/procedures/create.test.ts b/src/plugins/content_management/server/rpc/procedures/create.test.ts index ec877d2ea0d0d..5bf8a63462f69 100644 --- a/src/plugins/content_management/server/rpc/procedures/create.test.ts +++ b/src/plugins/content_management/server/rpc/procedures/create.test.ts @@ -230,16 +230,16 @@ describe('RPC -> create()', () => { }); describe('validation', () => { - test('should validate that content type definition exist', () => { + test('should validate that content type definition exist', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: 'unknown', data: { title: 'Hello' } }) ).rejects.toEqual(new Error('Content [unknown] is not registered.')); }); - test('should throw if the request version is higher than the registered version', () => { + test('should throw if the request version is higher than the registered version', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: FOO_CONTENT_ID, data: { title: 'Hello' }, @@ -250,9 +250,9 @@ describe('RPC -> create()', () => { }); describe('object versioning', () => { - test('should expose a utility to transform and validate services objects', () => { + test('should expose a utility to transform and validate services objects', async () => { const { ctx, storage } = setup(); - fn(ctx, { contentTypeId: FOO_CONTENT_ID, data: { title: 'Hello' }, version: 1 }); + await fn(ctx, { contentTypeId: FOO_CONTENT_ID, data: { title: 'Hello' }, version: 1 }); const [[storageContext]] = storage.create.mock.calls; // getTransforms() utils should be available from context diff --git a/src/plugins/content_management/server/rpc/procedures/delete.test.ts b/src/plugins/content_management/server/rpc/procedures/delete.test.ts index 5becd91a7b7d4..0d9089eecc19b 100644 --- a/src/plugins/content_management/server/rpc/procedures/delete.test.ts +++ b/src/plugins/content_management/server/rpc/procedures/delete.test.ts @@ -210,16 +210,16 @@ describe('RPC -> delete()', () => { }); describe('validation', () => { - test('should validate that content type definition exist', () => { + test('should validate that content type definition exist', async () => { const { ctx } = setup(); - expect(() => fn(ctx, { contentTypeId: 'unknown', id: '1234' })).rejects.toEqual( + await expect(() => fn(ctx, { contentTypeId: 'unknown', id: '1234' })).rejects.toEqual( new Error('Content [unknown] is not registered.') ); }); - test('should throw if the request version is higher than the registered version', () => { + test('should throw if the request version is higher than the registered version', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: FOO_CONTENT_ID, id: '1234', @@ -230,9 +230,9 @@ describe('RPC -> delete()', () => { }); describe('object versioning', () => { - test('should expose a utility to transform and validate services objects', () => { + test('should expose a utility to transform and validate services objects', async () => { const { ctx, storage } = setup(); - fn(ctx, { contentTypeId: FOO_CONTENT_ID, id: '1234', version: 1 }); + await fn(ctx, { contentTypeId: FOO_CONTENT_ID, id: '1234', version: 1 }); const [[storageContext]] = storage.delete.mock.calls; // getTransforms() utils should be available from context diff --git a/src/plugins/content_management/server/rpc/procedures/get.test.ts b/src/plugins/content_management/server/rpc/procedures/get.test.ts index 83affb9e725ae..6a304c325cd13 100644 --- a/src/plugins/content_management/server/rpc/procedures/get.test.ts +++ b/src/plugins/content_management/server/rpc/procedures/get.test.ts @@ -215,16 +215,16 @@ describe('RPC -> get()', () => { }); describe('validation', () => { - test('should validate that content type definition exist', () => { + test('should validate that content type definition exist', async () => { const { ctx } = setup(); - expect(() => fn(ctx, { contentTypeId: 'unknown', id: '1234' })).rejects.toEqual( + await expect(() => fn(ctx, { contentTypeId: 'unknown', id: '1234' })).rejects.toEqual( new Error('Content [unknown] is not registered.') ); }); - test('should throw if the request version is higher than the registered version', () => { + test('should throw if the request version is higher than the registered version', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: FOO_CONTENT_ID, id: '1234', @@ -235,9 +235,9 @@ describe('RPC -> get()', () => { }); describe('object versioning', () => { - test('should expose a utility to transform and validate services objects', () => { + test('should expose a utility to transform and validate services objects', async () => { const { ctx, storage } = setup(); - fn(ctx, { contentTypeId: FOO_CONTENT_ID, id: '1234', version: 1 }); + await fn(ctx, { contentTypeId: FOO_CONTENT_ID, id: '1234', version: 1 }); const [[storageContext]] = storage.get.mock.calls; // getTransforms() utils should be available from context diff --git a/src/plugins/content_management/server/rpc/procedures/msearch.test.ts b/src/plugins/content_management/server/rpc/procedures/msearch.test.ts index 7b28fae6d3b49..0cf899a59ae36 100644 --- a/src/plugins/content_management/server/rpc/procedures/msearch.test.ts +++ b/src/plugins/content_management/server/rpc/procedures/msearch.test.ts @@ -245,9 +245,9 @@ describe('RPC -> mSearch()', () => { }); describe('validation', () => { - test('should validate that content type definition exist', () => { + test('should validate that content type definition exist', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypes: [{ contentTypeId: 'unknown', version: 1 }], query: { text: 'Hello' }, @@ -255,9 +255,9 @@ describe('RPC -> mSearch()', () => { ).rejects.toEqual(new Error('Content [unknown] is not registered.')); }); - test('should throw if the request version is higher than the registered version', () => { + test('should throw if the request version is higher than the registered version', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypes: [{ contentTypeId: 'foo', version: 7 }], query: { text: 'Hello' }, diff --git a/src/plugins/content_management/server/rpc/procedures/search.test.ts b/src/plugins/content_management/server/rpc/procedures/search.test.ts index 2d7ef1501d102..0ee18e68d2299 100644 --- a/src/plugins/content_management/server/rpc/procedures/search.test.ts +++ b/src/plugins/content_management/server/rpc/procedures/search.test.ts @@ -247,16 +247,16 @@ describe('RPC -> search()', () => { }); describe('validation', () => { - test('should validate that content type definition exist', () => { + test('should validate that content type definition exist', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: 'unknown', query: { text: 'Hello' } }) ).rejects.toEqual(new Error('Content [unknown] is not registered.')); }); - test('should throw if the request version is higher than the registered version', () => { + test('should throw if the request version is higher than the registered version', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: FOO_CONTENT_ID, query: { text: 'Hello' }, @@ -267,9 +267,9 @@ describe('RPC -> search()', () => { }); describe('object versioning', () => { - test('should expose a utility to transform and validate services objects', () => { + test('should expose a utility to transform and validate services objects', async () => { const { ctx, storage } = setup(); - fn(ctx, { contentTypeId: FOO_CONTENT_ID, query: { text: 'Hello' }, version: 1 }); + await fn(ctx, { contentTypeId: FOO_CONTENT_ID, query: { text: 'Hello' }, version: 1 }); const [[storageContext]] = storage.search.mock.calls; // getTransforms() utils should be available from context diff --git a/src/plugins/content_management/server/rpc/procedures/update.test.ts b/src/plugins/content_management/server/rpc/procedures/update.test.ts index ad721d045be1d..48d8a846961a5 100644 --- a/src/plugins/content_management/server/rpc/procedures/update.test.ts +++ b/src/plugins/content_management/server/rpc/procedures/update.test.ts @@ -240,16 +240,16 @@ describe('RPC -> update()', () => { }); describe('validation', () => { - test('should validate that content type definition exist', () => { + test('should validate that content type definition exist', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: 'unknown', id: '123', data: { title: 'Hello' } }) ).rejects.toEqual(new Error('Content [unknown] is not registered.')); }); - test('should throw if the request version is higher than the registered version', () => { + test('should throw if the request version is higher than the registered version', async () => { const { ctx } = setup(); - expect(() => + await expect(() => fn(ctx, { contentTypeId: FOO_CONTENT_ID, id: '123', @@ -261,9 +261,9 @@ describe('RPC -> update()', () => { }); describe('object versioning', () => { - test('should expose a utility to transform and validate services objects', () => { + test('should expose a utility to transform and validate services objects', async () => { const { ctx, storage } = setup(); - fn(ctx, { + await fn(ctx, { contentTypeId: FOO_CONTENT_ID, id: '123', version: 1, diff --git a/src/plugins/content_management/server/rpc/rpc_service.test.ts b/src/plugins/content_management/server/rpc/rpc_service.test.ts index 0ac81a3c3fa8f..197c1f257b585 100644 --- a/src/plugins/content_management/server/rpc/rpc_service.test.ts +++ b/src/plugins/content_management/server/rpc/rpc_service.test.ts @@ -11,21 +11,21 @@ import { ProcedureDefinition, RpcService } from './rpc_service'; describe('RpcService', () => { describe('register()', () => { - test('should register a procedure', () => { + test('should register a procedure', async () => { const rpc = new RpcService<{}, 'foo'>(); const fn = jest.fn(); const procedure: ProcedureDefinition<{}> = { fn }; rpc.register('foo', procedure); const context = {}; - rpc.call(context, 'foo'); + await rpc.call(context, 'foo'); expect(fn).toHaveBeenCalledWith(context, undefined); }); }); describe('call()', () => { - test('should require a schema if an input is passed', () => { + test('should require a schema if an input is passed', async () => { const rpc = new RpcService<{}, 'foo'>(); const fn = jest.fn(); const procedure: ProcedureDefinition<{}> = { fn }; @@ -34,7 +34,7 @@ describe('RpcService', () => { const context = {}; const input = { foo: 'bar' }; - expect(() => { + await expect(() => { return rpc.call(context, 'foo', input); }).rejects.toEqual(new Error('Input schema missing for [foo] procedure.')); }); @@ -60,15 +60,15 @@ describe('RpcService', () => { expect(result).toEqual(output); }); - test('should throw an error if the procedure is not registered', () => { + test('should throw an error if the procedure is not registered', async () => { const rpc = new RpcService(); - expect(() => { + await expect(() => { return rpc.call(undefined, 'unknown'); }).rejects.toEqual(new Error('Procedure [unknown] is not registered.')); }); - test('should validate that the input is valid', () => { + test('should validate that the input is valid', async () => { const rpc = new RpcService<{}, 'foo'>(); const fn = jest.fn(); @@ -81,12 +81,12 @@ describe('RpcService', () => { const context = {}; const input = { bad: 'unknown prop' }; - expect(() => { + await expect(() => { return rpc.call(context, 'foo', input); }).rejects.toEqual(new Error('[foo]: expected value of type [string] but got [undefined]')); }); - test('should validate the output if schema is provided', () => { + test('should validate the output if schema is provided', async () => { const rpc = new RpcService<{}, 'foo'>(); const fn = jest.fn().mockResolvedValue({ bad: 'unknown prop' }); @@ -97,7 +97,7 @@ describe('RpcService', () => { rpc.register('foo', procedure); const context = {}; - expect(() => { + await expect(() => { return rpc.call(context, 'foo'); }).rejects.toEqual(new Error('[foo]: expected value of type [string] but got [undefined]')); }); diff --git a/src/plugins/data/server/query/route_handler_context.test.ts b/src/plugins/data/server/query/route_handler_context.test.ts index 5976db550f182..d2a9a14fe1fce 100644 --- a/src/plugins/data/server/query/route_handler_context.test.ts +++ b/src/plugins/data/server/query/route_handler_context.test.ts @@ -207,12 +207,12 @@ describe('saved query route handler context', () => { const response = context.create(savedQueryAttributes); - expect(response).rejects.toMatchInlineSnapshot(`[Error: An Error]`); + await expect(response).rejects.toMatchInlineSnapshot(`[Error: An Error]`); }); it('should throw an error if the saved query does not have a title', async () => { const response = context.create({ ...savedQueryAttributes, title: '' }); - expect(response).rejects.toMatchInlineSnapshot( + await expect(response).rejects.toMatchInlineSnapshot( `[Error: Cannot create query without a title]` ); }); @@ -266,12 +266,12 @@ describe('saved query route handler context', () => { const response = context.update('foo', savedQueryAttributes); - expect(response).rejects.toMatchInlineSnapshot(`[Error: An Error]`); + await expect(response).rejects.toMatchInlineSnapshot(`[Error: An Error]`); }); it('should throw an error if the saved query does not have a title', async () => { const response = context.create({ ...savedQueryAttributes, title: '' }); - expect(response).rejects.toMatchInlineSnapshot( + await expect(response).rejects.toMatchInlineSnapshot( `[Error: Cannot create query without a title]` ); }); @@ -609,7 +609,7 @@ describe('saved query route handler context', () => { }); const result = context.get('food'); - expect(result).rejects.toMatchInlineSnapshot( + await expect(result).rejects.toMatchInlineSnapshot( `[Error: Multiple saved queries found with ID: food (legacy URL alias conflict)]` ); }); diff --git a/src/plugins/data/server/search/collectors/search/usage.ts b/src/plugins/data/server/search/collectors/search/usage.ts index 65eafd28538e3..50d71fbc8ddff 100644 --- a/src/plugins/data/server/search/collectors/search/usage.ts +++ b/src/plugins/data/server/search/collectors/search/usage.ts @@ -88,11 +88,11 @@ export function searchUsageObserver( next(response: IEsSearchResponse) { if (isRestore || isRunningResponse(response)) return; logger.debug(`trackSearchStatus:success, took:${response.rawResponse.took}`); - usage?.trackSuccess(response.rawResponse.took); + void usage?.trackSuccess(response.rawResponse.took); }, error(e: Error) { logger.debug(`trackSearchStatus:error, ${e}`); - usage?.trackError(); + void usage?.trackError(); }, }; } diff --git a/src/plugins/data/server/search/search_service.ts b/src/plugins/data/server/search/search_service.ts index ad4dec61cab7c..12b84ca0c5694 100644 --- a/src/plugins/data/server/search/search_service.ts +++ b/src/plugins/data/server/search/search_service.ts @@ -256,7 +256,7 @@ export class SearchService implements Plugin { registerFunction: expressions.registerFunction, }); - firstValueFrom(this.initializerContext.config.create()).then((value) => { + void firstValueFrom(this.initializerContext.config.create()).then((value) => { if (value.search.aggs.shardDelay.enabled) { aggs.types.registerBucket(SHARD_DELAY_AGG_NAME, getShardDelayBucketAgg); expressions.registerFunction(aggShardDelay); diff --git a/src/plugins/data/server/search/session/session_service.test.ts b/src/plugins/data/server/search/session/session_service.test.ts index 481fabcfa423e..212eb810f227e 100644 --- a/src/plugins/data/server/search/session/session_service.test.ts +++ b/src/plugins/data/server/search/session/session_service.test.ts @@ -102,31 +102,31 @@ describe('SearchSessionService', () => { expect(savedObjectsClient.create).not.toHaveBeenCalled(); }); - it('Save throws', () => { - expect(() => + it('Save throws', async () => { + await expect(() => service.save({ savedObjectsClient }, mockUser1, sessionId, {}) ).rejects.toBeInstanceOf(Error); }); - it('Update throws', () => { + it('Update throws', async () => { const attributes = { name: 'new_name' }; const response = service.update({ savedObjectsClient }, mockUser1, sessionId, attributes); - expect(response).rejects.toBeInstanceOf(Error); + await expect(response).rejects.toBeInstanceOf(Error); }); - it('Cancel throws', () => { + it('Cancel throws', async () => { const response = service.cancel({ savedObjectsClient }, mockUser1, sessionId); - expect(response).rejects.toBeInstanceOf(Error); + await expect(response).rejects.toBeInstanceOf(Error); }); - it('getId throws', () => { + it('getId throws', async () => { const response = service.getId({ savedObjectsClient }, mockUser1, {}, {}); - expect(response).rejects.toBeInstanceOf(Error); + await expect(response).rejects.toBeInstanceOf(Error); }); - it('Delete throws', () => { + it('Delete throws', async () => { const response = service.delete({ savedObjectsClient }, mockUser1, sessionId); - expect(response).rejects.toBeInstanceOf(Error); + await expect(response).rejects.toBeInstanceOf(Error); }); }); @@ -156,7 +156,7 @@ describe('SearchSessionService', () => { const coreStart = coreMock.createStart(); await flushPromises(); - await service.start(coreStart, {}); + service.start(coreStart, {}); }); afterEach(() => { @@ -164,22 +164,22 @@ describe('SearchSessionService', () => { }); describe('save', () => { - it('throws if `name` is not provided', () => { - expect(() => + it('throws if `name` is not provided', async () => { + await expect(() => service.save({ savedObjectsClient }, mockUser1, sessionId, {}) ).rejects.toMatchInlineSnapshot(`[Error: Name is required]`); }); - it('throws if `appId` is not provided', () => { - expect( + it('throws if `appId` is not provided', async () => { + await expect( service.save({ savedObjectsClient }, mockUser1, sessionId, { name: 'banana', }) ).rejects.toMatchInlineSnapshot(`[Error: AppId is required]`); }); - it('throws if `locatorId` is not provided', () => { - expect( + it('throws if `locatorId` is not provided', async () => { + await expect( service.save({ savedObjectsClient }, mockUser1, sessionId, { name: 'banana', appId: 'nanana', @@ -220,10 +220,10 @@ describe('SearchSessionService', () => { expect(callAttributes).toHaveProperty('username', mockUser1.username); }); - it('throws error if user conflicts', () => { + it('throws error if user conflicts', async () => { savedObjectsClient.get.mockResolvedValue(mockSavedObject); - expect( + await expect( service.get({ savedObjectsClient }, mockUser2, sessionId) ).rejects.toMatchInlineSnapshot(`[Error: Not Found]`); }); @@ -614,7 +614,7 @@ describe('SearchSessionService', () => { expect(callAttributes).toHaveProperty('name', attributes.name); }); - it('throws if user conflicts', () => { + it('throws if user conflicts', async () => { const mockUpdateSavedObject = { ...mockSavedObject, attributes: {}, @@ -623,7 +623,7 @@ describe('SearchSessionService', () => { savedObjectsClient.update.mockResolvedValue(mockUpdateSavedObject); const attributes = { name: 'new_name' }; - expect( + await expect( service.update({ savedObjectsClient }, mockUser2, sessionId, attributes) ).rejects.toMatchInlineSnapshot(`[Error: Not Found]`); }); @@ -659,10 +659,10 @@ describe('SearchSessionService', () => { expect(callAttributes).toHaveProperty('isCanceled', true); }); - it('throws if user conflicts', () => { + it('throws if user conflicts', async () => { savedObjectsClient.get.mockResolvedValue(mockSavedObject); - expect( + await expect( service.cancel({ savedObjectsClient }, mockUser2, sessionId) ).rejects.toMatchInlineSnapshot(`[Error: Not Found]`); }); @@ -803,18 +803,18 @@ describe('SearchSessionService', () => { }); describe('getId', () => { - it('throws if `sessionId` is not provided', () => { + it('throws if `sessionId` is not provided', async () => { const searchRequest = { params: {} }; - expect(() => + await expect(() => service.getId({ savedObjectsClient }, mockUser1, searchRequest, {}) ).rejects.toMatchInlineSnapshot(`[Error: Session ID is required]`); }); - it('throws if there is not a saved object', () => { + it('throws if there is not a saved object', async () => { const searchRequest = { params: {} }; - expect(() => + await expect(() => service.getId({ savedObjectsClient }, mockUser1, searchRequest, { sessionId, isStored: false, @@ -824,10 +824,10 @@ describe('SearchSessionService', () => { ); }); - it('throws if not restoring a saved session', () => { + it('throws if not restoring a saved session', async () => { const searchRequest = { params: {} }; - expect(() => + await expect(() => service.getId({ savedObjectsClient }, mockUser1, searchRequest, { sessionId, isStored: true, diff --git a/src/plugins/data_views/server/expressions/load_index_pattern.test.ts b/src/plugins/data_views/server/expressions/load_index_pattern.test.ts index 94bd854e6734c..2c59a35349912 100644 --- a/src/plugins/data_views/server/expressions/load_index_pattern.test.ts +++ b/src/plugins/data_views/server/expressions/load_index_pattern.test.ts @@ -35,7 +35,7 @@ describe('indexPattern expression function', () => { test('throws if getKibanaRequest is not available', async () => { const indexPatternDefinition = getFunctionDefinition({ getStartDependencies }); - expect(async () => { + await expect(async () => { await indexPatternDefinition().fn(null, { id: '1' }, {} as any); }).rejects.toThrowErrorMatchingInlineSnapshot( `"A KibanaRequest is required to execute this search on the server. Please provide a request object to the expression execution params."` diff --git a/src/plugins/data_views/server/rest_api_routes/internal/fields.ts b/src/plugins/data_views/server/rest_api_routes/internal/fields.ts index 0536422476228..99ce0736a9ead 100644 --- a/src/plugins/data_views/server/rest_api_routes/internal/fields.ts +++ b/src/plugins/data_views/server/rest_api_routes/internal/fields.ts @@ -137,7 +137,7 @@ const handler: (isRollupsEnabled: () => boolean) => RequestHandler<{}, IQuery, I } }; -export const registerFields = async ( +export const registerFields = ( router: IRouter, getStartServices: StartServicesAccessor< DataViewsServerPluginStartDependencies, diff --git a/src/plugins/data_views/server/rest_api_routes/internal/fields_for.ts b/src/plugins/data_views/server/rest_api_routes/internal/fields_for.ts index 439dc6795b682..0daadeaf567c3 100644 --- a/src/plugins/data_views/server/rest_api_routes/internal/fields_for.ts +++ b/src/plugins/data_views/server/rest_api_routes/internal/fields_for.ts @@ -207,7 +207,7 @@ const handler: (isRollupsEnabled: () => boolean) => RequestHandler<{}, IQuery, I } }; -export const registerFieldForWildcard = async ( +export const registerFieldForWildcard = ( router: IRouter, getStartServices: StartServicesAccessor< DataViewsServerPluginStartDependencies, diff --git a/src/plugins/data_views/server/rest_api_routes/public/create_data_view.test.ts b/src/plugins/data_views/server/rest_api_routes/public/create_data_view.test.ts index 206ca278a85d7..89e01734977e7 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/create_data_view.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/create_data_view.test.ts @@ -11,9 +11,9 @@ import { dataViewsService } from '../../mocks'; import { getUsageCollection } from './test_utils'; describe('create data view', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); - createDataView({ + await createDataView({ dataViewsService, spec: {}, counterName: 'POST /path', diff --git a/src/plugins/data_views/server/rest_api_routes/public/default_data_view.test.ts b/src/plugins/data_views/server/rest_api_routes/public/default_data_view.test.ts index 9af8688913229..f6ec3861f994f 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/default_data_view.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/default_data_view.test.ts @@ -11,9 +11,9 @@ import { dataViewsService } from '../../mocks'; import { getUsageCollection } from './test_utils'; describe('default data view', () => { - it('set - calls usageCollection', () => { + it('set - calls usageCollection', async () => { const usageCollection = getUsageCollection(); - setDefault({ + await setDefault({ dataViewsService, counterName: 'POST /path', usageCollection, @@ -23,9 +23,9 @@ describe('default data view', () => { expect(usageCollection.incrementCounter).toBeCalledTimes(1); }); - it('get - calls usageCollection', () => { + it('get - calls usageCollection', async () => { const usageCollection = getUsageCollection(); - getDefault({ + await getDefault({ dataViewsService, counterName: 'GET /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/delete_data_view.test.ts b/src/plugins/data_views/server/rest_api_routes/public/delete_data_view.test.ts index d1c41e8bc8d47..f3e902fa5be65 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/delete_data_view.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/delete_data_view.test.ts @@ -11,9 +11,9 @@ import { dataViewsService } from '../../mocks'; import { getUsageCollection } from './test_utils'; describe('delete data view', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); - deleteDataView({ + await deleteDataView({ dataViewsService, counterName: 'DELETE /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/fields/update_fields.test.ts b/src/plugins/data_views/server/rest_api_routes/public/fields/update_fields.test.ts index c2ff246568c84..06a4f89b25d85 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/fields/update_fields.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/fields/update_fields.test.ts @@ -12,7 +12,7 @@ import { getUsageCollection } from '../test_utils'; import { DataViewLazy } from '../../../../common'; describe('create runtime field', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); dataViewsService.getDataViewLazy.mockImplementation( @@ -27,7 +27,7 @@ describe('create runtime field', () => { } as unknown as DataViewLazy) ); - updateFields({ + await updateFields({ dataViewsService, counterName: 'POST /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/get_data_view.test.ts b/src/plugins/data_views/server/rest_api_routes/public/get_data_view.test.ts index b035d48072f4c..963e3a64ceeb5 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/get_data_view.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/get_data_view.test.ts @@ -11,9 +11,9 @@ import { dataViewsService } from '../../mocks'; import { getUsageCollection } from './test_utils'; describe('get default data view', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); - getDataView({ + await getDataView({ dataViewsService, counterName: 'GET /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/get_data_views.test.ts b/src/plugins/data_views/server/rest_api_routes/public/get_data_views.test.ts index d3cd1d68af018..ae5ed06674d15 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/get_data_views.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/get_data_views.test.ts @@ -11,9 +11,9 @@ import { dataViewsService } from '../../mocks'; import { getUsageCollection } from './test_utils'; describe('get all data views', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); - getDataViews({ + await getDataViews({ dataViewsService, counterName: 'GET /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/has_user_data_view.test.ts b/src/plugins/data_views/server/rest_api_routes/public/has_user_data_view.test.ts index fc2f763580e99..d2e549d7ded2b 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/has_user_data_view.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/has_user_data_view.test.ts @@ -11,9 +11,9 @@ import { dataViewsService } from '../../mocks'; import { getUsageCollection } from './test_utils'; describe('get default data view', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); - hasUserDataView({ + await hasUserDataView({ dataViewsService, counterName: 'GET /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/create_runtime_field.test.ts b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/create_runtime_field.test.ts index 30ba66ec22b55..ba7f59c1b4474 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/create_runtime_field.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/create_runtime_field.test.ts @@ -12,7 +12,7 @@ import { getUsageCollection } from '../test_utils'; import { DataViewLazy } from '../../../../common'; describe('create runtime field', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); dataViewsService.getDataViewLazy.mockImplementation( @@ -28,7 +28,7 @@ describe('create runtime field', () => { } as unknown as DataViewLazy) ); - createRuntimeField({ + await createRuntimeField({ dataViewsService, counterName: 'POST /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/delete_runtime_field.test.ts b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/delete_runtime_field.test.ts index 6f0fb6ab168d8..955fbdff4ffab 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/delete_runtime_field.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/delete_runtime_field.test.ts @@ -12,7 +12,7 @@ import { getUsageCollection } from '../test_utils'; import { DataViewLazy } from '../../../../common'; describe('delete runtime field', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); dataViewsService.getDataViewLazy.mockImplementation( @@ -23,7 +23,7 @@ describe('delete runtime field', () => { } as unknown as DataViewLazy) ); - deleteRuntimeField({ + await deleteRuntimeField({ dataViewsService, counterName: 'DELETE /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/get_runtime_field.test.ts b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/get_runtime_field.test.ts index 8693c78961bfc..c5080a16178fc 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/get_runtime_field.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/get_runtime_field.test.ts @@ -12,7 +12,7 @@ import { getUsageCollection } from '../test_utils'; import { DataViewLazy } from '../../../../common'; describe('get runtime field', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); dataViewsService.getDataViewLazy.mockImplementation( @@ -25,7 +25,7 @@ describe('get runtime field', () => { } as unknown as DataViewLazy) ); - getRuntimeField({ + await getRuntimeField({ dataViewsService, counterName: 'GET /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/put_runtime_field.test.ts b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/put_runtime_field.test.ts index a0ea59c8e663c..8b0a75d5aa970 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/put_runtime_field.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/put_runtime_field.test.ts @@ -12,7 +12,7 @@ import { getUsageCollection } from '../test_utils'; import { DataViewLazy } from '../../../../common'; describe('put runtime field', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); dataViewsService.getDataViewLazy.mockImplementation( @@ -27,7 +27,7 @@ describe('put runtime field', () => { } as unknown as DataViewLazy) ); - putRuntimeField({ + await putRuntimeField({ dataViewsService, counterName: 'PUT /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/update_runtime_field.test.ts b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/update_runtime_field.test.ts index 69154d89f3a1d..8e70b6ad4bf6e 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/update_runtime_field.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/runtime_fields/update_runtime_field.test.ts @@ -12,7 +12,7 @@ import { getUsageCollection } from '../test_utils'; import { DataViewLazy } from '../../../../common'; describe('update runtime field', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); dataViewsService.getDataViewLazy.mockImplementation( @@ -29,7 +29,7 @@ describe('update runtime field', () => { } as unknown as DataViewLazy) ); - updateRuntimeField({ + await updateRuntimeField({ dataViewsService, counterName: 'POST /path', usageCollection, diff --git a/src/plugins/data_views/server/rest_api_routes/public/update_data_view.test.ts b/src/plugins/data_views/server/rest_api_routes/public/update_data_view.test.ts index 4f4056a6d597a..64ab989457f4c 100644 --- a/src/plugins/data_views/server/rest_api_routes/public/update_data_view.test.ts +++ b/src/plugins/data_views/server/rest_api_routes/public/update_data_view.test.ts @@ -11,9 +11,9 @@ import { dataViewsService } from '../../mocks'; import { getUsageCollection } from './test_utils'; describe('get default data view', () => { - it('call usageCollection', () => { + it('call usageCollection', async () => { const usageCollection = getUsageCollection(); - updateDataView({ + await updateDataView({ dataViewsService, counterName: 'GET /path', usageCollection, diff --git a/src/plugins/discover/server/locator/title_from_locator.test.ts b/src/plugins/discover/server/locator/title_from_locator.test.ts index f3e459a8bf39b..abb0636c32a1f 100644 --- a/src/plugins/discover/server/locator/title_from_locator.test.ts +++ b/src/plugins/discover/server/locator/title_from_locator.test.ts @@ -105,7 +105,7 @@ test(`throws error if DiscoverAppLocatorParams do not contain a saved search ID` return await provider(mockPayload[0].params); }; - expect(testFn).rejects.toEqual( + await expect(testFn).rejects.toEqual( new Error('DiscoverAppLocatorParams must contain a saved search reference') ); }); diff --git a/src/plugins/files/server/routes/file_kind/upload.test.ts b/src/plugins/files/server/routes/file_kind/upload.test.ts index 49a207ea80345..ae85a9e371c47 100644 --- a/src/plugins/files/server/routes/file_kind/upload.test.ts +++ b/src/plugins/files/server/routes/file_kind/upload.test.ts @@ -36,7 +36,7 @@ describe('upload', () => { beforeEach(async () => { ({ ctx, fileService } = createFileKindsRequestHandlerContextMock()); uploadContent = jest.fn(); - deleteFn = jest.fn(); + deleteFn = jest.fn(async () => {}); // We need it to be a promise, or it'll crash because of missing `.catch` fileService.getById.mockResolvedValueOnce({ id: 'test', data: { size: 1 }, diff --git a/src/plugins/files/server/routes/file_kind/upload.ts b/src/plugins/files/server/routes/file_kind/upload.ts index 9a97f685cc85d..74faaf9334fe9 100644 --- a/src/plugins/files/server/routes/file_kind/upload.ts +++ b/src/plugins/files/server/routes/file_kind/upload.ts @@ -76,7 +76,7 @@ export const handler: CreateHandler = async ({ files, fileKind }, req, logger.info( `File (id: ${file.id}) upload aborted. Deleting file due to self-destruct flag.` ); - file.delete(); // fire and forget + file.delete().catch(() => {}); // fire and forget } return res.customError({ body: { message: e.message }, statusCode: 499 }); } diff --git a/src/plugins/kibana_usage_collection/server/collectors/cloud/cloud_provider_collector.ts b/src/plugins/kibana_usage_collection/server/collectors/cloud/cloud_provider_collector.ts index 6939b20f4169c..76f79ed50348a 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/cloud/cloud_provider_collector.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/cloud/cloud_provider_collector.ts @@ -27,7 +27,7 @@ export function registerCloudProviderUsageCollector( const cloudDetector = new CloudDetector(); // determine the cloud service in the background - cloudDetector.detectCloudService(ac.signal); + cloudDetector.detectCloudService(ac.signal).catch(() => {}); const collector = usageCollection.makeUsageCollector({ type: 'cloud_provider', diff --git a/src/plugins/kibana_usage_collection/server/collectors/cloud/detector/cloud_detector.mock.ts b/src/plugins/kibana_usage_collection/server/collectors/cloud/detector/cloud_detector.mock.ts index 82e321c93783d..67697cac87b6c 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/cloud/detector/cloud_detector.mock.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/cloud/detector/cloud_detector.mock.ts @@ -8,7 +8,7 @@ const create = () => { const mock = { - detectCloudService: jest.fn(), + detectCloudService: jest.fn(async () => {}), // We need it to be a promise, or it'll crash because of missing `.catch` getCloudDetails: jest.fn(), }; diff --git a/src/plugins/maps_ems/server/plugin.ts b/src/plugins/maps_ems/server/plugin.ts index ebdc6814fd6eb..255fbaf4f912a 100644 --- a/src/plugins/maps_ems/server/plugin.ts +++ b/src/plugins/maps_ems/server/plugin.ts @@ -38,7 +38,10 @@ export class MapsEmsPlugin implements Plugin { isEnterprisePlus = enterprise.state === 'valid'; } - plugins.licensing.refresh().then(updateLicenseState); + plugins.licensing + .refresh() + .then(updateLicenseState) + .catch(() => {}); plugins.licensing.license$.subscribe(updateLicenseState); } diff --git a/src/plugins/navigation/server/plugin.ts b/src/plugins/navigation/server/plugin.ts index e5d83b915b897..6724ed8c20c53 100644 --- a/src/plugins/navigation/server/plugin.ts +++ b/src/plugins/navigation/server/plugin.ts @@ -36,14 +36,12 @@ export class NavigationServerPlugin if (plugins.cloud?.isCloudEnabled && !this.isServerless()) { const config = this.initializerContext.config.get(); - core.getStartServices().then(([coreStart, deps]) => { - deps.cloudExperiments?.getVariation(SOLUTION_NAV_FEATURE_FLAG_NAME, false).then((value) => { - if (value) { - core.uiSettings.registerGlobal(getUiSettings(config)); - } else { - this.removeUiSettings(coreStart, getUiSettings(config)); - } - }); + void core.getStartServices().then(async ([coreStart, deps]) => { + if (await deps.cloudExperiments?.getVariation(SOLUTION_NAV_FEATURE_FLAG_NAME, false)) { + core.uiSettings.registerGlobal(getUiSettings(config)); + } else { + await this.removeUiSettings(coreStart, getUiSettings(config)); + } }); } diff --git a/x-pack/packages/ml/response_stream/server/stream_factory.test.ts b/x-pack/packages/ml/response_stream/server/stream_factory.test.ts index 4b75cf4e0826a..839e7bfdfb9de 100644 --- a/x-pack/packages/ml/response_stream/server/stream_factory.test.ts +++ b/x-pack/packages/ml/response_stream/server/stream_factory.test.ts @@ -93,7 +93,7 @@ describe('streamFactory', () => { // the browser on the client side will automatically take care of unzipping // without the need for additional custom code. it('should encode and receive a compressed string based stream', (done) => { - (async () => { + void (async () => { const { end, push, responseWithHeaders } = streamFactory( { 'accept-encoding': 'gzip', @@ -133,7 +133,7 @@ describe('streamFactory', () => { }); it('should encode and receive a compressed NDJSON based stream', (done) => { - (async () => { + void (async () => { const { DELIMITER, end, push, responseWithHeaders } = streamFactory( { 'accept-encoding': 'gzip', diff --git a/x-pack/plugins/actions/server/plugin.ts b/x-pack/plugins/actions/server/plugin.ts index ac5b3206b722f..b01199b4e7667 100644 --- a/x-pack/plugins/actions/server/plugin.ts +++ b/x-pack/plugins/actions/server/plugin.ts @@ -580,15 +580,17 @@ export class ActionsPlugin implements Plugin { - scheduleActionsTelemetry(this.telemetryLogger, plugins.taskManager); - }); + this.eventLogService!.isEsContextReady() + .then(() => { + scheduleActionsTelemetry(this.telemetryLogger, plugins.taskManager); + }) + .catch(() => {}); if (this.actionsConfig.preconfiguredAlertHistoryEsIndex) { createAlertHistoryIndexTemplate({ client: core.elasticsearch.client.asInternalUser, logger: this.logger, - }); + }).catch(() => {}); } this.validateEnabledConnectorTypes(plugins); diff --git a/x-pack/plugins/actions/server/routes/connector/get/get.test.ts b/x-pack/plugins/actions/server/routes/connector/get/get.test.ts index e191a721a59a9..28293ae7947f2 100644 --- a/x-pack/plugins/actions/server/routes/connector/get/get.test.ts +++ b/x-pack/plugins/actions/server/routes/connector/get/get.test.ts @@ -149,7 +149,7 @@ describe('getConnectorRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/routes/connector/get_all/get_all.test.ts b/x-pack/plugins/actions/server/routes/connector/get_all/get_all.test.ts index 223a2d56c0843..0ab3b57e238cf 100644 --- a/x-pack/plugins/actions/server/routes/connector/get_all/get_all.test.ts +++ b/x-pack/plugins/actions/server/routes/connector/get_all/get_all.test.ts @@ -89,7 +89,7 @@ describe('getAllConnectorsRoute', () => { const [context, req, res] = mockHandlerArguments({ actionsClient }, {}, ['ok']); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/routes/connector/get_all_system/get_all_system.test.ts b/x-pack/plugins/actions/server/routes/connector/get_all_system/get_all_system.test.ts index 8130c8cd3a809..07221aacddde7 100644 --- a/x-pack/plugins/actions/server/routes/connector/get_all_system/get_all_system.test.ts +++ b/x-pack/plugins/actions/server/routes/connector/get_all_system/get_all_system.test.ts @@ -125,7 +125,7 @@ describe('getAllConnectorsIncludingSystemRoute', () => { const [context, req, res] = mockHandlerArguments({ actionsClient }, {}, ['ok']); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/routes/connector/list_types/list_types.test.ts b/x-pack/plugins/actions/server/routes/connector/list_types/list_types.test.ts index 91419ac562324..e7370c7638a89 100644 --- a/x-pack/plugins/actions/server/routes/connector/list_types/list_types.test.ts +++ b/x-pack/plugins/actions/server/routes/connector/list_types/list_types.test.ts @@ -241,7 +241,7 @@ describe('listTypesRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/routes/connector/list_types_system/list_types_system.test.ts b/x-pack/plugins/actions/server/routes/connector/list_types_system/list_types_system.test.ts index af6e057cafc9c..07d2d3adcd4f3 100644 --- a/x-pack/plugins/actions/server/routes/connector/list_types_system/list_types_system.test.ts +++ b/x-pack/plugins/actions/server/routes/connector/list_types_system/list_types_system.test.ts @@ -242,7 +242,7 @@ describe('listTypesWithSystemRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/routes/create.test.ts b/x-pack/plugins/actions/server/routes/create.test.ts index dd1317f57cd27..7d9c7fd1a5899 100644 --- a/x-pack/plugins/actions/server/routes/create.test.ts +++ b/x-pack/plugins/actions/server/routes/create.test.ts @@ -172,7 +172,7 @@ describe('createActionRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); }); test('validates body to prevent empty strings', async () => { diff --git a/x-pack/plugins/actions/server/routes/delete.test.ts b/x-pack/plugins/actions/server/routes/delete.test.ts index 160092eb8c101..b250e607738e6 100644 --- a/x-pack/plugins/actions/server/routes/delete.test.ts +++ b/x-pack/plugins/actions/server/routes/delete.test.ts @@ -104,7 +104,7 @@ describe('deleteActionRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/routes/execute.test.ts b/x-pack/plugins/actions/server/routes/execute.test.ts index 3bcd2cf60811d..39319ff1dabf2 100644 --- a/x-pack/plugins/actions/server/routes/execute.test.ts +++ b/x-pack/plugins/actions/server/routes/execute.test.ts @@ -167,7 +167,7 @@ describe('executeActionRoute', () => { const [, handler] = router.post.mock.calls[0]; - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/routes/get_oauth_access_token.test.ts b/x-pack/plugins/actions/server/routes/get_oauth_access_token.test.ts index ae06068273ca3..c1b7dd26aff15 100644 --- a/x-pack/plugins/actions/server/routes/get_oauth_access_token.test.ts +++ b/x-pack/plugins/actions/server/routes/get_oauth_access_token.test.ts @@ -216,7 +216,7 @@ describe('getOAuthAccessToken', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/routes/legacy/create.test.ts b/x-pack/plugins/actions/server/routes/legacy/create.test.ts index e711f73265f53..05993e44746f9 100644 --- a/x-pack/plugins/actions/server/routes/legacy/create.test.ts +++ b/x-pack/plugins/actions/server/routes/legacy/create.test.ts @@ -141,7 +141,7 @@ describe('createActionRoute', () => { const [context, req, res] = mockHandlerArguments({ actionsClient }, {}); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); }); it('should track every call', async () => { diff --git a/x-pack/plugins/actions/server/routes/legacy/delete.test.ts b/x-pack/plugins/actions/server/routes/legacy/delete.test.ts index e16614a57fd04..2bfb5c7810e46 100644 --- a/x-pack/plugins/actions/server/routes/legacy/delete.test.ts +++ b/x-pack/plugins/actions/server/routes/legacy/delete.test.ts @@ -112,7 +112,7 @@ describe('deleteActionRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/actions/server/routes/legacy/execute.test.ts b/x-pack/plugins/actions/server/routes/legacy/execute.test.ts index 53e7d038dfea5..c989731407650 100644 --- a/x-pack/plugins/actions/server/routes/legacy/execute.test.ts +++ b/x-pack/plugins/actions/server/routes/legacy/execute.test.ts @@ -170,7 +170,7 @@ describe('executeActionRoute', () => { const [, handler] = router.post.mock.calls[0]; - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/actions/server/routes/legacy/get.test.ts b/x-pack/plugins/actions/server/routes/legacy/get.test.ts index 6a19400da0fb5..732c964fb8284 100644 --- a/x-pack/plugins/actions/server/routes/legacy/get.test.ts +++ b/x-pack/plugins/actions/server/routes/legacy/get.test.ts @@ -146,7 +146,7 @@ describe('getActionRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/actions/server/routes/legacy/get_all.test.ts b/x-pack/plugins/actions/server/routes/legacy/get_all.test.ts index e999c769f3dbb..e8657e56259e1 100644 --- a/x-pack/plugins/actions/server/routes/legacy/get_all.test.ts +++ b/x-pack/plugins/actions/server/routes/legacy/get_all.test.ts @@ -97,7 +97,7 @@ describe('getAllActionRoute', () => { const [context, req, res] = mockHandlerArguments({ actionsClient }, {}, ['ok']); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/actions/server/routes/legacy/list_action_types.test.ts b/x-pack/plugins/actions/server/routes/legacy/list_action_types.test.ts index 4674bbb9936a6..ec57c4b9a99a9 100644 --- a/x-pack/plugins/actions/server/routes/legacy/list_action_types.test.ts +++ b/x-pack/plugins/actions/server/routes/legacy/list_action_types.test.ts @@ -159,7 +159,7 @@ describe('listActionTypesRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/actions/server/routes/legacy/update.test.ts b/x-pack/plugins/actions/server/routes/legacy/update.test.ts index 304b504636c91..493d1c873690e 100644 --- a/x-pack/plugins/actions/server/routes/legacy/update.test.ts +++ b/x-pack/plugins/actions/server/routes/legacy/update.test.ts @@ -172,7 +172,7 @@ describe('updateActionRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/actions/server/routes/update.test.ts b/x-pack/plugins/actions/server/routes/update.test.ts index aef179264ac48..9fdac7740129d 100644 --- a/x-pack/plugins/actions/server/routes/update.test.ts +++ b/x-pack/plugins/actions/server/routes/update.test.ts @@ -174,7 +174,7 @@ describe('updateActionRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyAccessAndContext).toHaveBeenCalledWith(licenseState, expect.any(Function)); }); diff --git a/x-pack/plugins/actions/server/usage/task.ts b/x-pack/plugins/actions/server/usage/task.ts index 85e06f0422431..1496974581e89 100644 --- a/x-pack/plugins/actions/server/usage/task.ts +++ b/x-pack/plugins/actions/server/usage/task.ts @@ -32,7 +32,9 @@ export function initializeActionsTelemetry( } export function scheduleActionsTelemetry(logger: Logger, taskManager: TaskManagerStartContract) { - scheduleTasks(logger, taskManager); + scheduleTasks(logger, taskManager).catch(() => { + // it shouldn't throw anything. But adding the catch just in case + }); } function registerActionsTelemetryTask( diff --git a/x-pack/plugins/aiops/server/plugin.ts b/x-pack/plugins/aiops/server/plugin.ts index 81ad429c387e0..7e99a89dab5b5 100755 --- a/x-pack/plugins/aiops/server/plugin.ts +++ b/x-pack/plugins/aiops/server/plugin.ts @@ -62,7 +62,7 @@ export class AiopsPlugin const router = core.http.createRouter(); // Register server side APIs - core.getStartServices().then(([coreStart, depsStart]) => { + void core.getStartServices().then(([coreStart, depsStart]) => { defineLogRateAnalysisRoute(router, aiopsLicense, this.logger, coreStart, this.usageCounter); defineCategorizationFieldValidationRoute(router, aiopsLicense, this.usageCounter); }); diff --git a/x-pack/plugins/aiops/server/routes/log_rate_analysis/analysis_handlers/grouping_handler.ts b/x-pack/plugins/aiops/server/routes/log_rate_analysis/analysis_handlers/grouping_handler.ts index 5266858e6d3bc..3c7a1f4ff5478 100644 --- a/x-pack/plugins/aiops/server/routes/log_rate_analysis/analysis_handlers/grouping_handler.ts +++ b/x-pack/plugins/aiops/server/routes/log_rate_analysis/analysis_handlers/grouping_handler.ts @@ -221,7 +221,7 @@ export const groupingHandlerFactory = } }, MAX_CONCURRENT_QUERIES); - groupHistogramQueue.push(significantItemGroups); + await groupHistogramQueue.push(significantItemGroups); await groupHistogramQueue.drain(); } } catch (e) { diff --git a/x-pack/plugins/aiops/server/routes/log_rate_analysis/analysis_handlers/histogram_handler.ts b/x-pack/plugins/aiops/server/routes/log_rate_analysis/analysis_handlers/histogram_handler.ts index 1a61edde6864b..8fd134df69cac 100644 --- a/x-pack/plugins/aiops/server/routes/log_rate_analysis/analysis_handlers/histogram_handler.ts +++ b/x-pack/plugins/aiops/server/routes/log_rate_analysis/analysis_handlers/histogram_handler.ts @@ -156,7 +156,7 @@ export const histogramHandlerFactory = } }, MAX_CONCURRENT_QUERIES); - fieldValueHistogramQueue.push(significantTerms); + await fieldValueHistogramQueue.push(significantTerms); await fieldValueHistogramQueue.drain(); } diff --git a/x-pack/plugins/aiops/server/routes/log_rate_analysis/route_handler_factory.ts b/x-pack/plugins/aiops/server/routes/log_rate_analysis/route_handler_factory.ts index 69b9cc923799d..0864efbcf63da 100644 --- a/x-pack/plugins/aiops/server/routes/log_rate_analysis/route_handler_factory.ts +++ b/x-pack/plugins/aiops/server/routes/log_rate_analysis/route_handler_factory.ts @@ -133,7 +133,7 @@ export function routeHandlerFactory( } // Do not call this using `await` so it will run asynchronously while we return the stream already. - runAnalysis(); + void runAnalysis(); return response.ok(responseWithHeaders); }); diff --git a/x-pack/plugins/alerting/server/alerts_service/lib/install_with_timeout.ts b/x-pack/plugins/alerting/server/alerts_service/lib/install_with_timeout.ts index 759aeba71cd41..e93dcf2e09f34 100644 --- a/x-pack/plugins/alerting/server/alerts_service/lib/install_with_timeout.ts +++ b/x-pack/plugins/alerting/server/alerts_service/lib/install_with_timeout.ts @@ -48,10 +48,12 @@ export const installWithTimeout = async ({ reject(new Error(msg)); }, timeoutMs); - firstValueFrom(pluginStop$).then(() => { - clearTimeout(timeoutId); - reject(new InstallShutdownError()); - }); + firstValueFrom(pluginStop$) + .then(() => { + clearTimeout(timeoutId); + reject(new InstallShutdownError()); + }) + .catch(() => reject(new InstallShutdownError())); }); }; diff --git a/x-pack/plugins/alerting/server/application/backfill/methods/delete/delete_backfill.test.ts b/x-pack/plugins/alerting/server/application/backfill/methods/delete/delete_backfill.test.ts index 89ab626bed462..4a2ac84515fe9 100644 --- a/x-pack/plugins/alerting/server/application/backfill/methods/delete/delete_backfill.test.ts +++ b/x-pack/plugins/alerting/server/application/backfill/methods/delete/delete_backfill.test.ts @@ -121,7 +121,7 @@ describe('deleteBackfill()', () => { let rulesClient: RulesClient; beforeEach(async () => { - jest.resetAllMocks(); + jest.clearAllMocks(); rulesClient = new RulesClient(rulesClientParams); unsecuredSavedObjectsClient.get.mockResolvedValue(mockAdHocRunSO); unsecuredSavedObjectsClient.delete.mockResolvedValue({}); diff --git a/x-pack/plugins/alerting/server/application/backfill/methods/delete/delete_backfill.ts b/x-pack/plugins/alerting/server/application/backfill/methods/delete/delete_backfill.ts index fe43e3555e8d3..3851efc1c2ebd 100644 --- a/x-pack/plugins/alerting/server/application/backfill/methods/delete/delete_backfill.ts +++ b/x-pack/plugins/alerting/server/application/backfill/methods/delete/delete_backfill.ts @@ -85,7 +85,7 @@ async function deleteWithOCC(context: RulesClientContext, { id }: { id: string } ); // remove the associated task - context.taskManager.removeIfExists(id); + context.taskManager.removeIfExists(id).catch(() => {}); return removeResult; } catch (err) { diff --git a/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.test.ts b/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.test.ts index a2f1c0dfa92f1..9ace9c2d8f491 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.test.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/create/create_rule.test.ts @@ -3062,7 +3062,7 @@ describe('create()', () => { rulesClientParams.createAPIKey.mockImplementation(() => { throw new Error('no'); }); - expect( + await expect( async () => await rulesClient.create({ data }) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Error creating rule: could not create API key - no"` diff --git a/x-pack/plugins/alerting/server/application/rule/methods/update/update_rule.test.ts b/x-pack/plugins/alerting/server/application/rule/methods/update/update_rule.test.ts index d9bc9c8816845..748b41c0d2f1a 100644 --- a/x-pack/plugins/alerting/server/application/rule/methods/update/update_rule.test.ts +++ b/x-pack/plugins/alerting/server/application/rule/methods/update/update_rule.test.ts @@ -1618,7 +1618,7 @@ describe('update()', () => { rulesClientParams.createAPIKey.mockImplementation(() => { throw new Error('no'); }); - expect( + await expect( async () => await rulesClient.update({ id: '1', diff --git a/x-pack/plugins/alerting/server/invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation.ts b/x-pack/plugins/alerting/server/invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation.ts index 6711dd3fd6d24..bde9cd8aa2131 100644 --- a/x-pack/plugins/alerting/server/invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation.ts +++ b/x-pack/plugins/alerting/server/invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation.ts @@ -14,7 +14,7 @@ export const bulkMarkApiKeysForInvalidation = async ( logger: Logger, savedObjectsClient: SavedObjectsClientContract ): Promise => { - withSpan({ name: 'bulkMarkApiKeysForInvalidation', type: 'rules' }, async () => { + await withSpan({ name: 'bulkMarkApiKeysForInvalidation', type: 'rules' }, async () => { if (apiKeys.length === 0) { return; } diff --git a/x-pack/plugins/alerting/server/plugin.ts b/x-pack/plugins/alerting/server/plugin.ts index 907c85ab27da5..f0006e6974e33 100644 --- a/x-pack/plugins/alerting/server/plugin.ts +++ b/x-pack/plugins/alerting/server/plugin.ts @@ -617,12 +617,16 @@ export class AlertingPlugin { : Promise.resolve([]); }); - this.eventLogService!.isEsContextReady().then(() => { - scheduleAlertingTelemetry(this.telemetryLogger, plugins.taskManager); - }); - - scheduleAlertingHealthCheck(this.logger, this.config, plugins.taskManager); - scheduleApiKeyInvalidatorTask(this.telemetryLogger, this.config, plugins.taskManager); + this.eventLogService!.isEsContextReady() + .then(() => { + scheduleAlertingTelemetry(this.telemetryLogger, plugins.taskManager); + }) + .catch(() => {}); // it shouldn't reject, but just in case + + scheduleAlertingHealthCheck(this.logger, this.config, plugins.taskManager).catch(() => {}); // it shouldn't reject, but just in case + scheduleApiKeyInvalidatorTask(this.telemetryLogger, this.config, plugins.taskManager).catch( + () => {} + ); // it shouldn't reject, but just in case return { listTypes: ruleTypeRegistry!.list.bind(this.ruleTypeRegistry!), diff --git a/x-pack/plugins/alerting/server/routes/backfill/apis/delete/delete_backfill_route.test.ts b/x-pack/plugins/alerting/server/routes/backfill/apis/delete/delete_backfill_route.test.ts index 55a8ea2ae22ea..5ba4b736fa81e 100644 --- a/x-pack/plugins/alerting/server/routes/backfill/apis/delete/delete_backfill_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/backfill/apis/delete/delete_backfill_route.test.ts @@ -65,6 +65,6 @@ describe('deleteBackfillRoute', () => { }); const [, handler] = router.delete.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: { id: 'abc' } }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/backfill/apis/find/find_backfill_route.test.ts b/x-pack/plugins/alerting/server/routes/backfill/apis/find/find_backfill_route.test.ts index fb461fa416f9b..a8a0a210c8817 100644 --- a/x-pack/plugins/alerting/server/routes/backfill/apis/find/find_backfill_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/backfill/apis/find/find_backfill_route.test.ts @@ -140,6 +140,6 @@ describe('findBackfillRoute', () => { }); const [, handler] = router.post.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ rulesClient }, { body: mockFindOptions }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/backfill/apis/get/get_backfill_route.test.ts b/x-pack/plugins/alerting/server/routes/backfill/apis/get/get_backfill_route.test.ts index f24018b1c8deb..79ac8df1ed4b5 100644 --- a/x-pack/plugins/alerting/server/routes/backfill/apis/get/get_backfill_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/backfill/apis/get/get_backfill_route.test.ts @@ -99,6 +99,6 @@ describe('getBackfillRoute', () => { const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ rulesClient }, { params: { id: 'abc' } }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/backfill/apis/schedule/schedule_backfill_route.test.ts b/x-pack/plugins/alerting/server/routes/backfill/apis/schedule/schedule_backfill_route.test.ts index 30545a3ac1617..c08cca6dfe683 100644 --- a/x-pack/plugins/alerting/server/routes/backfill/apis/schedule/schedule_backfill_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/backfill/apis/schedule/schedule_backfill_route.test.ts @@ -148,6 +148,6 @@ describe('scheduleBackfillRoute', () => { { rulesClient }, { body: mockScheduleOptions } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/delete_rule.test.ts b/x-pack/plugins/alerting/server/routes/delete_rule.test.ts index b64dff27c5b90..71222d859d3c8 100644 --- a/x-pack/plugins/alerting/server/routes/delete_rule.test.ts +++ b/x-pack/plugins/alerting/server/routes/delete_rule.test.ts @@ -102,7 +102,7 @@ describe('deleteRuleRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/get_action_error_log.test.ts b/x-pack/plugins/alerting/server/routes/get_action_error_log.test.ts index 408ed049044c6..f95fe38a5ee64 100644 --- a/x-pack/plugins/alerting/server/routes/get_action_error_log.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_action_error_log.test.ts @@ -115,7 +115,7 @@ describe('getActionErrorLogRoute', () => { ['notFound'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( `[Error: Saved object [alert/1] not found]` ); }); diff --git a/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.test.ts b/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.test.ts index 5eca11c27a4b2..319de59a01bfd 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule_alert_summary.test.ts @@ -114,7 +114,7 @@ describe('getRuleAlertSummaryRoute', () => { ['notFound'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( `[Error: Saved object [alert/1] not found]` ); }); diff --git a/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts b/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts index e92b54769d329..af64b80851695 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule_execution_kpi.test.ts @@ -99,7 +99,7 @@ describe('getRuleExecutionKPIRoute', () => { ['notFound'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( `[Error: Saved object [alert/1] not found]` ); }); diff --git a/x-pack/plugins/alerting/server/routes/get_rule_execution_log.test.ts b/x-pack/plugins/alerting/server/routes/get_rule_execution_log.test.ts index a0dd57da558eb..3b1f950fb45c6 100644 --- a/x-pack/plugins/alerting/server/routes/get_rule_execution_log.test.ts +++ b/x-pack/plugins/alerting/server/routes/get_rule_execution_log.test.ts @@ -145,7 +145,7 @@ describe('getRuleExecutionLogRoute', () => { ['notFound'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot( `[Error: Saved object [alert/1] not found]` ); }); diff --git a/x-pack/plugins/alerting/server/routes/legacy/create.test.ts b/x-pack/plugins/alerting/server/routes/legacy/create.test.ts index e090cac73a932..d50d7fcb79e38 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/create.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/create.test.ts @@ -432,7 +432,7 @@ describe('createAlertRoute', () => { const [context, req, res] = mockHandlerArguments({ rulesClient }, {}); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/legacy/delete.test.ts b/x-pack/plugins/alerting/server/routes/legacy/delete.test.ts index fee6b3db736fe..9a3ccdf84c82c 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/delete.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/delete.test.ts @@ -108,7 +108,7 @@ describe('deleteAlertRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/legacy/find.test.ts b/x-pack/plugins/alerting/server/routes/legacy/find.test.ts index 60ca90865be1d..013fa119dbdf1 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/find.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/find.test.ts @@ -149,7 +149,7 @@ describe('findAlertRoute', () => { }, ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/legacy/get.test.ts b/x-pack/plugins/alerting/server/routes/legacy/get.test.ts index 7d1a6ac656896..e97996837f1d7 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/get.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/get.test.ts @@ -151,7 +151,7 @@ describe('getAlertRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.test.ts b/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.test.ts index c680007f197e1..b9abeafd00ecc 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/list_alert_types.test.ts @@ -219,7 +219,7 @@ describe('listAlertTypesRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/legacy/update.test.ts b/x-pack/plugins/alerting/server/routes/legacy/update.test.ts index 9e23470215d36..44a4cf629813a 100644 --- a/x-pack/plugins/alerting/server/routes/legacy/update.test.ts +++ b/x-pack/plugins/alerting/server/routes/legacy/update.test.ts @@ -225,7 +225,7 @@ describe('updateAlertRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/archive/archive_maintenance_window_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/archive/archive_maintenance_window_route.test.ts index 040ba6e8ea9ab..dfd5073ae1026 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/archive/archive_maintenance_window_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/archive/archive_maintenance_window_route.test.ts @@ -112,7 +112,7 @@ describe('archiveMaintenanceWindowRoute', () => { }, } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { @@ -127,6 +127,6 @@ describe('archiveMaintenanceWindowRoute', () => { const [, handler] = router.post.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/bulk_get/bulk_get_maintenance_windows_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/bulk_get/bulk_get_maintenance_windows_route.test.ts index c39fe061b69e5..eaab39665fb6b 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/bulk_get/bulk_get_maintenance_windows_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/bulk_get/bulk_get_maintenance_windows_route.test.ts @@ -110,7 +110,7 @@ describe('bulkGetMaintenanceWindowRoute', () => { { maintenanceWindowClient }, { body: { ids: ['test-id-1', 'test-id-2', 'test-id-3'] } } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { @@ -124,6 +124,6 @@ describe('bulkGetMaintenanceWindowRoute', () => { }); const [, handler] = router.post.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/create/create_maintenance_window_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/create/create_maintenance_window_route.test.ts index 5437533ba8342..9cac558652d76 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/create/create_maintenance_window_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/create/create_maintenance_window_route.test.ts @@ -101,7 +101,7 @@ describe('createMaintenanceWindowRoute', () => { { maintenanceWindowClient }, { body: createParams } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { @@ -116,6 +116,6 @@ describe('createMaintenanceWindowRoute', () => { const [, handler] = router.post.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/delete/delete_maintenance_window_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/delete/delete_maintenance_window_route.test.ts index 7ac0db328cf9d..b248fe1394318 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/delete/delete_maintenance_window_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/delete/delete_maintenance_window_route.test.ts @@ -85,7 +85,7 @@ describe('deleteMaintenanceWindowRoute', () => { { maintenanceWindowClient }, { params: { id: 'test-id' } } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { @@ -100,6 +100,6 @@ describe('deleteMaintenanceWindowRoute', () => { const [, handler] = router.delete.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/find/find_maintenance_windows_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/find/find_maintenance_windows_route.test.ts index a9a7d22e20751..21d821d2e0db3 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/find/find_maintenance_windows_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/find/find_maintenance_windows_route.test.ts @@ -93,7 +93,7 @@ describe('findMaintenanceWindowsRoute', () => { }); const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { @@ -107,6 +107,6 @@ describe('findMaintenanceWindowsRoute', () => { }); const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/finish/finish_maintenance_window_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/finish/finish_maintenance_window_route.test.ts index e7ec470839fe9..4141d114c98d8 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/finish/finish_maintenance_window_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/finish/finish_maintenance_window_route.test.ts @@ -88,7 +88,7 @@ describe('finishMaintenanceWindowRoute', () => { { maintenanceWindowClient }, { params: { id: 'test-id' } } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { @@ -102,6 +102,6 @@ describe('finishMaintenanceWindowRoute', () => { }); const [, handler] = router.post.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/get/get_maintenance_window_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/get/get_maintenance_window_route.test.ts index 9e17aed88eaf0..487878fdb0e9a 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/get/get_maintenance_window_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/get/get_maintenance_window_route.test.ts @@ -88,7 +88,7 @@ describe('getMaintenanceWindowRoute', () => { { maintenanceWindowClient }, { params: { id: 'test-id' } } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { @@ -102,6 +102,6 @@ describe('getMaintenanceWindowRoute', () => { }); const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/get_active/get_active_maintenance_windows_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/get_active/get_active_maintenance_windows_route.test.ts index c9f9fa2841374..4121aeb1d7f11 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/get_active/get_active_maintenance_windows_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/get_active/get_active_maintenance_windows_route.test.ts @@ -92,7 +92,7 @@ describe('getActiveMaintenanceWindowsRoute', () => { }); const [, handler] = router.get.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { diff --git a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/update/update_maintenance_window_route.test.ts b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/update/update_maintenance_window_route.test.ts index d7425b150d1ea..a4bc9701f99a1 100644 --- a/x-pack/plugins/alerting/server/routes/maintenance_window/apis/update/update_maintenance_window_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/maintenance_window/apis/update/update_maintenance_window_route.test.ts @@ -115,7 +115,7 @@ describe('updateMaintenanceWindowRoute', () => { body: updateParams, } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); test('ensures only platinum license can access API', async () => { @@ -129,6 +129,6 @@ describe('updateMaintenanceWindowRoute', () => { }); const [, handler] = router.post.mock.calls[0]; const [context, req, res] = mockHandlerArguments({ maintenanceWindowClient }, { body: {} }); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); }); diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/aggregate/aggregate_rules_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/aggregate/aggregate_rules_route.test.ts index 51a7da620dfb3..77221de2d714b 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/aggregate/aggregate_rules_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/aggregate/aggregate_rules_route.test.ts @@ -316,7 +316,7 @@ describe('aggregateRulesRoute', () => { }, ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/bulk_delete/bulk_delete_rules_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/bulk_delete/bulk_delete_rules_route.test.ts index 3f2a31ac6cc96..90a13ba09a4cf 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/bulk_delete/bulk_delete_rules_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/bulk_delete/bulk_delete_rules_route.test.ts @@ -100,7 +100,7 @@ describe('bulkDeleteRulesRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); it('ensures the rule type gets validated for the license', async () => { diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/bulk_disable/bulk_disable_rules_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/bulk_disable/bulk_disable_rules_route.test.ts index cd71a78a5f51c..0dc0793118c23 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/bulk_disable/bulk_disable_rules_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/bulk_disable/bulk_disable_rules_route.test.ts @@ -101,7 +101,7 @@ describe('bulkDisableRulesRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); it('ensures the rule type gets validated for the license', async () => { diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/bulk_edit/bulk_edit_rules_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/bulk_edit/bulk_edit_rules_route.test.ts index 82480acf779f9..295299db3a117 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/bulk_edit/bulk_edit_rules_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/bulk_edit/bulk_edit_rules_route.test.ts @@ -169,7 +169,7 @@ describe('bulkEditRulesRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); it('ensures the rule type gets validated for the license', async () => { diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/bulk_enable/bulk_enable_rules_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/bulk_enable/bulk_enable_rules_route.test.ts index 9a0d22dadc9a4..272d91997a9f5 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/bulk_enable/bulk_enable_rules_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/bulk_enable/bulk_enable_rules_route.test.ts @@ -103,7 +103,7 @@ describe('bulkEnableRulesRoute', () => { } ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: Failure]`); }); it('ensures the rule type gets validated for the license', async () => { diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/clone/clone_rule_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/clone/clone_rule_route.test.ts index 4ae904261eb24..13c6a69087635 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/clone/clone_rule_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/clone/clone_rule_route.test.ts @@ -198,7 +198,7 @@ describe('cloneRuleRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/create/create_rule_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/create/create_rule_route.test.ts index 8f488dafd2fa5..ba6c3c25a1c43 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/create/create_rule_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/create/create_rule_route.test.ts @@ -632,7 +632,7 @@ describe('createRuleRoute', () => { const [context, req, res] = mockHandlerArguments({ rulesClient }, {}); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/find/find_rules_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/find/find_rules_route.test.ts index 53c339a66b864..4e3c9b635ec3a 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/find/find_rules_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/find/find_rules_route.test.ts @@ -360,7 +360,7 @@ describe('findRulesRoute', () => { }, ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/get/get_rule_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/get/get_rule_route.test.ts index f854109f16f1b..a9ae97e521ef5 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/get/get_rule_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/get/get_rule_route.test.ts @@ -188,7 +188,7 @@ describe('getRuleRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/resolve/resolve_rule_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/resolve/resolve_rule_route.test.ts index bd6c8e144e91c..7b7d871007060 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/resolve/resolve_rule_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/resolve/resolve_rule_route.test.ts @@ -197,7 +197,7 @@ describe('resolveRuleRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/tags/get_rule_tags.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/tags/get_rule_tags.test.ts index a8a1992480841..02b9fd4e32a5f 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/tags/get_rule_tags.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/tags/get_rule_tags.test.ts @@ -118,7 +118,7 @@ describe('getRuleTagsRoute', () => { }, ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/rule/apis/update/update_rule_route.test.ts b/x-pack/plugins/alerting/server/routes/rule/apis/update/update_rule_route.test.ts index c04c1aa345d1a..e1ed7b52ae710 100644 --- a/x-pack/plugins/alerting/server/routes/rule/apis/update/update_rule_route.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule/apis/update/update_rule_route.test.ts @@ -273,7 +273,7 @@ describe('updateRuleRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/routes/rule_types.test.ts b/x-pack/plugins/alerting/server/routes/rule_types.test.ts index f14c3472dcc93..a6483f15f9f1c 100644 --- a/x-pack/plugins/alerting/server/routes/rule_types.test.ts +++ b/x-pack/plugins/alerting/server/routes/rule_types.test.ts @@ -250,7 +250,7 @@ describe('ruleTypesRoute', () => { ['ok'] ); - expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); + await expect(handler(context, req, res)).rejects.toMatchInlineSnapshot(`[Error: OMG]`); expect(verifyApiAccess).toHaveBeenCalledWith(licenseState); }); diff --git a/x-pack/plugins/alerting/server/rules_client/lib/add_generated_action_values.test.ts b/x-pack/plugins/alerting/server/rules_client/lib/add_generated_action_values.test.ts index 5a969e7e8c836..ac58ab1a12685 100644 --- a/x-pack/plugins/alerting/server/rules_client/lib/add_generated_action_values.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/lib/add_generated_action_values.test.ts @@ -148,7 +148,7 @@ describe('addGeneratedActionValues()', () => { }); test('throws error if KQL is not valid', async () => { - expect(async () => + await expect(async () => addGeneratedActionValues( [ { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_action_error_log.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_action_error_log.test.ts index 8df9883247683..532511fb313f5 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_action_error_log.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_action_error_log.test.ts @@ -507,9 +507,9 @@ describe('getActionErrorLog()', () => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getRuleSavedObject()); eventLogClient.findEventsBySavedObjectIds.mockRejectedValueOnce(new Error('OMG 3!')); - expect(rulesClient.getActionErrorLog(getActionErrorLogParams())).rejects.toMatchInlineSnapshot( - `[Error: OMG 3!]` - ); + await expect( + rulesClient.getActionErrorLog(getActionErrorLogParams()) + ).rejects.toMatchInlineSnapshot(`[Error: OMG 3!]`); }); describe('authorization', () => { beforeEach(() => { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts index b5815b6022cb9..77e3d19a37540 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_alert_summary.test.ts @@ -372,7 +372,7 @@ describe('getAlertSummary()', () => { eventLogClient.findEventsBySavedObjectIds.mockResolvedValueOnce(AlertSummaryFindEventsResult); const dateStart = 'ain"t no way this will get parsed as a date'; - expect(rulesClient.getAlertSummary({ id: '1', dateStart })).rejects.toMatchInlineSnapshot( + await expect(rulesClient.getAlertSummary({ id: '1', dateStart })).rejects.toMatchInlineSnapshot( `[Error: Invalid date for parameter dateStart: "ain"t no way this will get parsed as a date"]` ); }); @@ -381,7 +381,9 @@ describe('getAlertSummary()', () => { unsecuredSavedObjectsClient.get.mockRejectedValueOnce(new Error('OMG!')); eventLogClient.findEventsBySavedObjectIds.mockResolvedValueOnce(AlertSummaryFindEventsResult); - expect(rulesClient.getAlertSummary({ id: '1' })).rejects.toMatchInlineSnapshot(`[Error: OMG!]`); + await expect(rulesClient.getAlertSummary({ id: '1' })).rejects.toMatchInlineSnapshot( + `[Error: OMG!]` + ); }); test('findEvents throws an error', async () => { diff --git a/x-pack/plugins/alerting/server/rules_client/tests/get_execution_log.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/get_execution_log.test.ts index 6bc7076ab3329..f8416e9cdb6b6 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/get_execution_log.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/get_execution_log.test.ts @@ -553,7 +553,7 @@ describe('getExecutionLogForRule()', () => { eventLogClient.aggregateEventsBySavedObjectIds.mockResolvedValueOnce(aggregateResults); const dateStart = 'ain"t no way this will get parsed as a date'; - expect( + await expect( rulesClient.getExecutionLogForRule(getExecutionLogByIdParams({ dateStart })) ).rejects.toMatchInlineSnapshot( `[Error: Invalid date for parameter dateStart: "ain"t no way this will get parsed as a date"]` @@ -565,7 +565,7 @@ describe('getExecutionLogForRule()', () => { eventLogClient.aggregateEventsBySavedObjectIds.mockResolvedValueOnce(aggregateResults); const dateEnd = 'ain"t no way this will get parsed as a date'; - expect( + await expect( rulesClient.getExecutionLogForRule(getExecutionLogByIdParams({ dateEnd })) ).rejects.toMatchInlineSnapshot( `[Error: Invalid date for parameter dateEnd: "ain"t no way this will get parsed as a date"]` @@ -576,7 +576,7 @@ describe('getExecutionLogForRule()', () => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getRuleSavedObject()); eventLogClient.aggregateEventsBySavedObjectIds.mockResolvedValueOnce(aggregateResults); - expect( + await expect( rulesClient.getExecutionLogForRule(getExecutionLogByIdParams({ page: -3 })) ).rejects.toMatchInlineSnapshot(`[Error: Invalid page field "-3" - must be greater than 0]`); }); @@ -585,7 +585,7 @@ describe('getExecutionLogForRule()', () => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getRuleSavedObject()); eventLogClient.aggregateEventsBySavedObjectIds.mockResolvedValueOnce(aggregateResults); - expect( + await expect( rulesClient.getExecutionLogForRule(getExecutionLogByIdParams({ perPage: -3 })) ).rejects.toMatchInlineSnapshot(`[Error: Invalid perPage field "-3" - must be greater than 0]`); }); @@ -594,7 +594,7 @@ describe('getExecutionLogForRule()', () => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getRuleSavedObject()); eventLogClient.aggregateEventsBySavedObjectIds.mockResolvedValueOnce(aggregateResults); - expect( + await expect( rulesClient.getExecutionLogForRule( getExecutionLogByIdParams({ sort: [{ foo: { order: 'desc' } }] }) ) @@ -607,7 +607,7 @@ describe('getExecutionLogForRule()', () => { unsecuredSavedObjectsClient.get.mockRejectedValueOnce(new Error('OMG!')); eventLogClient.aggregateEventsBySavedObjectIds.mockResolvedValueOnce(aggregateResults); - expect( + await expect( rulesClient.getExecutionLogForRule(getExecutionLogByIdParams()) ).rejects.toMatchInlineSnapshot(`[Error: OMG!]`); }); @@ -616,7 +616,7 @@ describe('getExecutionLogForRule()', () => { unsecuredSavedObjectsClient.get.mockResolvedValueOnce(getRuleSavedObject()); eventLogClient.aggregateEventsBySavedObjectIds.mockRejectedValueOnce(new Error('OMG 2!')); - expect( + await expect( rulesClient.getExecutionLogForRule(getExecutionLogByIdParams()) ).rejects.toMatchInlineSnapshot(`[Error: OMG 2!]`); }); diff --git a/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts b/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts index 0f72a1e20d1d5..dbf80eb978d2f 100644 --- a/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts +++ b/x-pack/plugins/alerting/server/rules_client/tests/update_api_key.test.ts @@ -287,7 +287,7 @@ describe('updateApiKey()', () => { rulesClientParams.createAPIKey.mockImplementation(() => { throw new Error('no'); }); - expect( + await expect( async () => await rulesClient.updateApiKey({ id: '1' }) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Error updating API key for rule: could not create API key - no"` diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.ts index 627f88bab4e69..713ee52015239 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.ts @@ -551,7 +551,7 @@ export class TaskRunner< // Most likely a 409 conflict error, which is ok, we'll try again at the next rule run this.logger.debug(`Failed to clear expired snoozes: ${e.message}`); } - })(); + })().catch(() => {}); return runRuleParams; }); diff --git a/x-pack/plugins/alerting/server/usage/task.ts b/x-pack/plugins/alerting/server/usage/task.ts index 507970d436d6f..0cc08db911226 100644 --- a/x-pack/plugins/alerting/server/usage/task.ts +++ b/x-pack/plugins/alerting/server/usage/task.ts @@ -38,7 +38,7 @@ export function initializeAlertingTelemetry( export function scheduleAlertingTelemetry(logger: Logger, taskManager?: TaskManagerStartContract) { if (taskManager) { - scheduleTasks(logger, taskManager); + scheduleTasks(logger, taskManager).catch(() => {}); // it shouldn't reject, but just in case } } diff --git a/x-pack/plugins/canvas/server/plugin.ts b/x-pack/plugins/canvas/server/plugin.ts index 9dd6dc1bdd64f..16e39eb46ee34 100644 --- a/x-pack/plugins/canvas/server/plugin.ts +++ b/x-pack/plugins/canvas/server/plugin.ts @@ -99,7 +99,7 @@ export class CanvasPlugin implements Plugin { public start(coreStart: CoreStart) { const client = coreStart.savedObjects.createInternalRepository(); - initializeTemplates(client); + initializeTemplates(client).catch(() => {}); } public stop() {} diff --git a/x-pack/plugins/canvas/server/routes/shareables/zip.ts b/x-pack/plugins/canvas/server/routes/shareables/zip.ts index 7f5a414c5dba0..d476edb8ca4ac 100644 --- a/x-pack/plugins/canvas/server/routes/shareables/zip.ts +++ b/x-pack/plugins/canvas/server/routes/shareables/zip.ts @@ -33,7 +33,7 @@ export function initializeZipShareableWorkpadRoute(deps: RouteInitializerDeps) { archive.file(SHAREABLE_RUNTIME_FILE, { name: `${SHAREABLE_RUNTIME_NAME}.js` }); const result = { headers: { 'content-type': 'application/zip' }, body: archive }; - archive.finalize(); + await archive.finalize(); return response.ok(result); } diff --git a/x-pack/plugins/cases/server/authorization/authorization.ts b/x-pack/plugins/cases/server/authorization/authorization.ts index e3dc970b38182..c67b69c4f305f 100644 --- a/x-pack/plugins/cases/server/authorization/authorization.ts +++ b/x-pack/plugins/cases/server/authorization/authorization.ts @@ -171,7 +171,7 @@ export class Authorization { return { authorized, unauthorized }; } - private async logSavedObjects({ + private logSavedObjects({ entities, operation, error, diff --git a/x-pack/plugins/cases/server/common/limiter_checker/limiters/persistable_state_and_external_references.test.ts b/x-pack/plugins/cases/server/common/limiter_checker/limiters/persistable_state_and_external_references.test.ts index df40e3841f1d7..d126237dd8aac 100644 --- a/x-pack/plugins/cases/server/common/limiter_checker/limiters/persistable_state_and_external_references.test.ts +++ b/x-pack/plugins/cases/server/common/limiter_checker/limiters/persistable_state_and_external_references.test.ts @@ -39,8 +39,8 @@ describe('PersistableStateAndExternalReferencesLimiter', () => { }); describe('countOfItemsWithinCase', () => { - it('calls the attachment service with the right params', () => { - limiter.countOfItemsWithinCase(caseId); + it('calls the attachment service with the right params', async () => { + await limiter.countOfItemsWithinCase(caseId); expect( attachmentService.countPersistableStateAndExternalReferenceAttachments diff --git a/x-pack/plugins/cases/server/telemetry/index.ts b/x-pack/plugins/cases/server/telemetry/index.ts index af1e9125a8a55..5f10dcc6a3c72 100644 --- a/x-pack/plugins/cases/server/telemetry/index.ts +++ b/x-pack/plugins/cases/server/telemetry/index.ts @@ -36,7 +36,7 @@ interface CreateCasesTelemetryArgs { kibanaVersion: PluginInitializerContext['env']['packageInfo']['version']; } -export const createCasesTelemetry = async ({ +export const createCasesTelemetry = ({ core, taskManager, usageCollection, diff --git a/x-pack/plugins/cloud_defend/server/lib/fleet_util.ts b/x-pack/plugins/cloud_defend/server/lib/fleet_util.ts index 0e51a343e3770..c0db69a5dc128 100644 --- a/x-pack/plugins/cloud_defend/server/lib/fleet_util.ts +++ b/x-pack/plugins/cloud_defend/server/lib/fleet_util.ts @@ -89,9 +89,15 @@ async function addDataViewToAllSpaces(savedObjectsClient: SavedObjectsClientCont perPage: 100, }); - cloudDefendDataViews.saved_objects.forEach((dataView) => { - savedObjectsClient.updateObjectsSpaces([{ id: dataView.id, type: 'index-pattern' }], ['*'], []); - }); + await Promise.all( + cloudDefendDataViews.saved_objects.map((dataView) => + savedObjectsClient.updateObjectsSpaces( + [{ id: dataView.id, type: 'index-pattern' }], + ['*'], + [] + ) + ) + ); } export const getCloudDefendAgentPolicies = async ( diff --git a/x-pack/plugins/cloud_defend/server/plugin.ts b/x-pack/plugins/cloud_defend/server/plugin.ts index c8a6bc5083b1c..b7c5016776816 100644 --- a/x-pack/plugins/cloud_defend/server/plugin.ts +++ b/x-pack/plugins/cloud_defend/server/plugin.ts @@ -55,23 +55,26 @@ export class CloudDefendPlugin implements Plugin { - plugins.fleet.registerExternalCallback( - 'packagePolicyCreate', - async (packagePolicy: NewPackagePolicy): Promise => { - const license = await plugins.licensing.refresh(); - if (isCloudDefendPackage(packagePolicy.package?.name)) { - if (!isSubscriptionAllowed(this.isCloudEnabled, license)) { - throw new Error( - 'To use this feature you must upgrade your subscription or start a trial' - ); + plugins.fleet + .fleetSetupCompleted() + .then(async () => { + plugins.fleet.registerExternalCallback( + 'packagePolicyCreate', + async (packagePolicy: NewPackagePolicy): Promise => { + const license = await plugins.licensing.refresh(); + if (isCloudDefendPackage(packagePolicy.package?.name)) { + if (!isSubscriptionAllowed(this.isCloudEnabled, license)) { + throw new Error( + 'To use this feature you must upgrade your subscription or start a trial' + ); + } } - } - return packagePolicy; - } - ); - }); + return packagePolicy; + } + ); + }) + .catch(() => {}); // it shouldn't reject, but just in case plugins.fleet.registerExternalCallback( 'packagePolicyPostCreate', diff --git a/x-pack/plugins/cloud_security_posture/server/fleet_integration/fleet_integration.ts b/x-pack/plugins/cloud_security_posture/server/fleet_integration/fleet_integration.ts index 0e9cf02ad0663..a3d166cf69688 100644 --- a/x-pack/plugins/cloud_security_posture/server/fleet_integration/fleet_integration.ts +++ b/x-pack/plugins/cloud_security_posture/server/fleet_integration/fleet_integration.ts @@ -29,9 +29,15 @@ async function addDataViewToAllSpaces(savedObjectsClient: SavedObjectsClientCont perPage: 100, }); - cspmDataViews.saved_objects.forEach((dataView) => { - savedObjectsClient.updateObjectsSpaces([{ id: dataView.id, type: 'index-pattern' }], ['*'], []); - }); + await Promise.all( + cspmDataViews.saved_objects.map((dataView) => + savedObjectsClient.updateObjectsSpaces( + [{ id: dataView.id, type: 'index-pattern' }], + ['*'], + [] + ) + ) + ); } export const isCspPackagePolicyInstalled = async ( diff --git a/x-pack/plugins/cloud_security_posture/server/plugin.ts b/x-pack/plugins/cloud_security_posture/server/plugin.ts index 58a143b220857..561d1bcaa7efd 100755 --- a/x-pack/plugins/cloud_security_posture/server/plugin.ts +++ b/x-pack/plugins/cloud_security_posture/server/plugin.ts @@ -100,102 +100,104 @@ export class CspPlugin } public start(core: CoreStart, plugins: CspServerPluginStartDeps): CspServerPluginStart { - plugins.fleet.fleetSetupCompleted().then(async () => { - const packageInfo = await plugins.fleet.packageService.asInternalUser.getInstallation( - CLOUD_SECURITY_POSTURE_PACKAGE_NAME - ); - - // If package is installed we want to make sure all needed assets are installed - if (packageInfo) { - // noinspection ES6MissingAwait - this.initialize(core, plugins.taskManager); - } - - plugins.fleet.registerExternalCallback( - 'packagePolicyCreate', - async (packagePolicy: NewPackagePolicy): Promise => { - const license = await plugins.licensing.refresh(); - if (isCspPackage(packagePolicy.package?.name)) { - if (!isSubscriptionAllowed(this.isCloudEnabled, license)) { - throw new Error( - 'To use this feature you must upgrade your subscription or start a trial' - ); - } + plugins.fleet + .fleetSetupCompleted() + .then(async () => { + const packageInfo = await plugins.fleet.packageService.asInternalUser.getInstallation( + CLOUD_SECURITY_POSTURE_PACKAGE_NAME + ); + + // If package is installed we want to make sure all needed assets are installed + if (packageInfo) { + this.initialize(core, plugins.taskManager).catch(() => {}); + } - if (!isSingleEnabledInput(packagePolicy.inputs)) { - throw new Error('Only one enabled input is allowed per policy'); + plugins.fleet.registerExternalCallback( + 'packagePolicyCreate', + async (packagePolicy: NewPackagePolicy): Promise => { + const license = await plugins.licensing.refresh(); + if (isCspPackage(packagePolicy.package?.name)) { + if (!isSubscriptionAllowed(this.isCloudEnabled, license)) { + throw new Error( + 'To use this feature you must upgrade your subscription or start a trial' + ); + } + + if (!isSingleEnabledInput(packagePolicy.inputs)) { + throw new Error('Only one enabled input is allowed per policy'); + } } - } - return packagePolicy; - } - ); - - plugins.fleet.registerExternalCallback( - 'packagePolicyCreate', - async ( - packagePolicy: NewPackagePolicy, - soClient: SavedObjectsClientContract - ): Promise => { - if (isCspPackage(packagePolicy.package?.name)) { - return cleanupCredentials(packagePolicy); + return packagePolicy; } + ); + + plugins.fleet.registerExternalCallback( + 'packagePolicyCreate', + async ( + packagePolicy: NewPackagePolicy, + soClient: SavedObjectsClientContract + ): Promise => { + if (isCspPackage(packagePolicy.package?.name)) { + return cleanupCredentials(packagePolicy); + } - return packagePolicy; - } - ); - - plugins.fleet.registerExternalCallback( - 'packagePolicyUpdate', - async ( - packagePolicy: UpdatePackagePolicy, - soClient: SavedObjectsClientContract - ): Promise => { - if (isCspPackage(packagePolicy.package?.name)) { - return cleanupCredentials(packagePolicy); + return packagePolicy; } - - return packagePolicy; - } - ); - - plugins.fleet.registerExternalCallback( - 'packagePolicyPostCreate', - async ( - packagePolicy: PackagePolicy, - soClient: SavedObjectsClientContract - ): Promise => { - if (isCspPackage(packagePolicy.package?.name)) { - await this.initialize(core, plugins.taskManager); - await onPackagePolicyPostCreateCallback(this.logger, packagePolicy, soClient); + ); + + plugins.fleet.registerExternalCallback( + 'packagePolicyUpdate', + async ( + packagePolicy: UpdatePackagePolicy, + soClient: SavedObjectsClientContract + ): Promise => { + if (isCspPackage(packagePolicy.package?.name)) { + return cleanupCredentials(packagePolicy); + } return packagePolicy; } + ); + + plugins.fleet.registerExternalCallback( + 'packagePolicyPostCreate', + async ( + packagePolicy: PackagePolicy, + soClient: SavedObjectsClientContract + ): Promise => { + if (isCspPackage(packagePolicy.package?.name)) { + await this.initialize(core, plugins.taskManager); + await onPackagePolicyPostCreateCallback(this.logger, packagePolicy, soClient); + + return packagePolicy; + } - return packagePolicy; - } - ); - - plugins.fleet.registerExternalCallback( - 'packagePolicyPostDelete', - async (deletedPackagePolicies: DeepReadonly) => { - for (const deletedPackagePolicy of deletedPackagePolicies) { - if (isCspPackage(deletedPackagePolicy.package?.name)) { - const soClient = core.savedObjects.createInternalRepository(); - const packagePolicyService = plugins.fleet.packagePolicyService; - const isPackageExists = await isCspPackagePolicyInstalled( - packagePolicyService, - soClient, - this.logger - ); - if (!isPackageExists) { - await this.uninstallResources(plugins.taskManager, this.logger); + return packagePolicy; + } + ); + + plugins.fleet.registerExternalCallback( + 'packagePolicyPostDelete', + async (deletedPackagePolicies: DeepReadonly) => { + for (const deletedPackagePolicy of deletedPackagePolicies) { + if (isCspPackage(deletedPackagePolicy.package?.name)) { + const soClient = core.savedObjects.createInternalRepository(); + const packagePolicyService = plugins.fleet.packagePolicyService; + const isPackageExists = await isCspPackagePolicyInstalled( + packagePolicyService, + soClient, + this.logger + ); + if (!isPackageExists) { + await this.uninstallResources(plugins.taskManager, this.logger); + } } } } - } - ); - }); + ); + }) + .catch(() => {}); // it shouldn't reject, but just in case return {}; } diff --git a/x-pack/plugins/cloud_security_posture/server/routes/setup_routes.ts b/x-pack/plugins/cloud_security_posture/server/routes/setup_routes.ts index 732017db1090f..7b46e4ef113c3 100644 --- a/x-pack/plugins/cloud_security_posture/server/routes/setup_routes.ts +++ b/x-pack/plugins/cloud_security_posture/server/routes/setup_routes.ts @@ -27,7 +27,7 @@ import { defineGetCspBenchmarkRulesStatesRoute } from './benchmark_rules/get_sta * 1. Registers routes * 2. Registers routes handler context */ -export async function setupRoutes({ +export function setupRoutes({ core, logger, isPluginInitialized, diff --git a/x-pack/plugins/cross_cluster_replication/server/plugin.ts b/x-pack/plugins/cross_cluster_replication/server/plugin.ts index 657468b76d615..bf5644a0f8bdd 100644 --- a/x-pack/plugins/cross_cluster_replication/server/plugin.ts +++ b/x-pack/plugins/cross_cluster_replication/server/plugin.ts @@ -57,7 +57,7 @@ export class CrossClusterReplicationServerPlugin implements Plugin { + void firstValueFrom(this.config$).then((config) => { // remoteClusters.isUiEnabled is driven by the xpack.remote_clusters.ui.enabled setting. // The CCR UI depends upon the Remote Clusters UI (e.g. by cross-linking to it), so if // the Remote Clusters UI is disabled we can't show the CCR UI. diff --git a/x-pack/plugins/ecs_data_quality_dashboard/server/lib/data_stream/results_data_stream.test.ts b/x-pack/plugins/ecs_data_quality_dashboard/server/lib/data_stream/results_data_stream.test.ts index 7504a4b55c1cb..8ae7df34888d5 100644 --- a/x-pack/plugins/ecs_data_quality_dashboard/server/lib/data_stream/results_data_stream.test.ts +++ b/x-pack/plugins/ecs_data_quality_dashboard/server/lib/data_stream/results_data_stream.test.ts @@ -100,7 +100,7 @@ describe('ResultsDataStream', () => { it('should not install space if install not executed', async () => { const resultsDataStream = new ResultsDataStream({ kibanaVersion: '8.13.0' }); - expect(resultsDataStream.installSpace('space1')).rejects.toThrowError(); + await expect(resultsDataStream.installSpace('space1')).rejects.toThrowError(); }); it('should throw error if main install had error', async () => { @@ -115,7 +115,7 @@ describe('ResultsDataStream', () => { (dataStreamSpacesAdapter.install as jest.Mock).mockRejectedValueOnce(error); await resultsDataStream.install(params); - expect(resultsDataStream.installSpace('space1')).rejects.toThrowError(error); + await expect(resultsDataStream.installSpace('space1')).rejects.toThrowError(error); }); }); }); diff --git a/x-pack/plugins/ecs_data_quality_dashboard/server/plugin.ts b/x-pack/plugins/ecs_data_quality_dashboard/server/plugin.ts index cb6fe9da7c276..f7b2fa3415147 100755 --- a/x-pack/plugins/ecs_data_quality_dashboard/server/plugin.ts +++ b/x-pack/plugins/ecs_data_quality_dashboard/server/plugin.ts @@ -48,13 +48,15 @@ export class EcsDataQualityDashboardPlugin public setup(core: CoreSetup, plugins: PluginSetupDependencies) { this.logger.debug('ecsDataQualityDashboard: Setup'); - this.resultsDataStream.install({ - esClient: core - .getStartServices() - .then(([{ elasticsearch }]) => elasticsearch.client.asInternalUser), - logger: this.logger, - pluginStop$: this.pluginStop$, - }); + this.resultsDataStream + .install({ + esClient: core + .getStartServices() + .then(([{ elasticsearch }]) => elasticsearch.client.asInternalUser), + logger: this.logger, + pluginStop$: this.pluginStop$, + }) + .catch(() => {}); // it shouldn't reject, but just in case core.http.registerRouteHandlerContext< DataQualityDashboardRequestHandlerContext, diff --git a/x-pack/plugins/elastic_assistant/server/ai_assistant_service/index.ts b/x-pack/plugins/elastic_assistant/server/ai_assistant_service/index.ts index eeb3c6cc4289d..9cc3efb03e195 100644 --- a/x-pack/plugins/elastic_assistant/server/ai_assistant_service/index.ts +++ b/x-pack/plugins/elastic_assistant/server/ai_assistant_service/index.ts @@ -318,7 +318,7 @@ export class AIAssistantService { if (!anonymizationFieldsIndexName) { await this.anonymizationFieldsDataStream.installSpace(spaceId); - this.createDefaultAnonymizationFields(spaceId); + await this.createDefaultAnonymizationFields(spaceId); } } catch (error) { this.options.logger.error( diff --git a/x-pack/plugins/elastic_assistant/server/lib/executor.test.ts b/x-pack/plugins/elastic_assistant/server/lib/executor.test.ts index 1805df38b789b..bacdd6cac1b49 100644 --- a/x-pack/plugins/elastic_assistant/server/lib/executor.test.ts +++ b/x-pack/plugins/elastic_assistant/server/lib/executor.test.ts @@ -17,14 +17,14 @@ import { KibanaRequest } from '@kbn/core-http-server'; import { PluginStartContract as ActionsPluginStart } from '@kbn/actions-plugin/server'; import { ExecuteConnectorRequestBody } from '@kbn/elastic-assistant-common'; import { loggerMock } from '@kbn/logging-mocks'; -import { handleStreamStorage } from './parse_stream'; +import * as ParseStream from './parse_stream'; const request = { body: { subAction: 'invokeAI', message: 'hello', }, } as KibanaRequest; -const onLlmResponse = jest.fn(); +const onLlmResponse = jest.fn(async () => {}); // We need it to be a promise, or it'll crash because of missing `.catch` const connectorId = 'testConnectorId'; const mockLogger = loggerMock.create(); const testProps: Omit = { @@ -38,9 +38,8 @@ const testProps: Omit = { onLlmResponse, logger: mockLogger, }; -jest.mock('./parse_stream'); -const mockHandleStreamStorage = handleStreamStorage as jest.Mock; +const handleStreamStorageSpy = jest.spyOn(ParseStream, 'handleStreamStorage'); describe('executeAction', () => { beforeEach(() => { @@ -83,7 +82,7 @@ describe('executeAction', () => { JSON.stringify(readableStream.pipe(new PassThrough())) ); - expect(mockHandleStreamStorage).toHaveBeenCalledWith({ + expect(handleStreamStorageSpy).toHaveBeenCalledWith({ actionTypeId: '.bedrock', onMessageSent: onLlmResponse, logger: mockLogger, diff --git a/x-pack/plugins/elastic_assistant/server/lib/executor.ts b/x-pack/plugins/elastic_assistant/server/lib/executor.ts index b8fa9fe0c5170..e7797805854ec 100644 --- a/x-pack/plugins/elastic_assistant/server/lib/executor.ts +++ b/x-pack/plugins/elastic_assistant/server/lib/executor.ts @@ -92,7 +92,7 @@ export const executeAction = async ({ logger, responseStream: readable, abortSignal, - }); + }).catch(() => {}); return readable.pipe(new PassThrough()); }; diff --git a/x-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.test.ts b/x-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.test.ts index 103c0932f86c3..7664e970b4df8 100644 --- a/x-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.test.ts +++ b/x-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.test.ts @@ -221,7 +221,7 @@ describe('callAgentExecutor', () => { mockInvokeWithChainCallback({ ...props, agentType }, more), }) ); - const onLlmResponse = jest.fn(); + const onLlmResponse = jest.fn(async () => {}); // We need it to be a promise, or it'll crash because of missing `.catch` await callAgentExecutor({ ...defaultProps, onLlmResponse, isStream: true }); expect(onLlmResponse).toHaveBeenCalledWith( @@ -250,7 +250,7 @@ describe('callAgentExecutor', () => { mockInvokeWithChainCallback({ ...props, agentType }, more), }) ); - const onLlmResponse = jest.fn(); + const onLlmResponse = jest.fn(async () => {}); // We need it to be a promise, or it'll crash because of missing `.catch` await callAgentExecutor({ ...defaultProps, onLlmResponse, isStream: true }); expect(mockPush).toHaveBeenCalledWith({ payload: 'hi', type: 'content' }); diff --git a/x-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.ts b/x-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.ts index e6863fa5550fe..fdecc1365d43c 100644 --- a/x-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.ts +++ b/x-pack/plugins/elastic_assistant/server/lib/langchain/execute_custom_llm_chain/index.ts @@ -162,7 +162,7 @@ export const callAgentExecutor: AgentExecutor = async ({ traceId: streamingSpan?.ids?.['trace.id'], }, isError - ); + ).catch(() => {}); } streamEnd(); didEnd = true; diff --git a/x-pack/plugins/elastic_assistant/server/routes/post_actions_connector_execute.ts b/x-pack/plugins/elastic_assistant/server/routes/post_actions_connector_execute.ts index 32f5fc47ae770..e579996eb13d1 100644 --- a/x-pack/plugins/elastic_assistant/server/routes/post_actions_connector_execute.ts +++ b/x-pack/plugins/elastic_assistant/server/routes/post_actions_connector_execute.ts @@ -378,7 +378,7 @@ export const postActionsConnectorExecuteRoute = ( logger.error(err); const error = transformError(err); if (onLlmResponse) { - onLlmResponse(error.message, {}, true); + await onLlmResponse(error.message, {}, true); } telemetry.reportEvent(INVOKE_ASSISTANT_ERROR_EVENT.eventType, { actionTypeId: request.body.actionTypeId, diff --git a/x-pack/plugins/encrypted_saved_objects/server/mocks.ts b/x-pack/plugins/encrypted_saved_objects/server/mocks.ts index 1bc30c41b6b22..9aa0c8ab2f973 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/mocks.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/mocks.ts @@ -5,6 +5,8 @@ * 2.0. */ +import { savedObjectsClientMock } from '@kbn/core-saved-objects-api-server-mocks'; + import type { EncryptedSavedObjectsPluginSetup, EncryptedSavedObjectsPluginStart } from './plugin'; import type { EncryptedSavedObjectsClient, @@ -33,8 +35,10 @@ function createEncryptedSavedObjectsStartMock() { function createEncryptedSavedObjectsClientMock(opts?: EncryptedSavedObjectsClientOptions) { return { getDecryptedAsInternalUser: jest.fn(), - createPointInTimeFinderDecryptedAsInternalUser: jest.fn(), - } as jest.Mocked; + createPointInTimeFinderDecryptedAsInternalUser: jest.fn((findOptions, deps) => + savedObjectsClientMock.create().createPointInTimeFinder(findOptions, deps) + ), + } as unknown as jest.Mocked; } export const encryptedSavedObjectsMock = { diff --git a/x-pack/plugins/encrypted_saved_objects/tsconfig.json b/x-pack/plugins/encrypted_saved_objects/tsconfig.json index 7b9087064c109..17dea87aca6ee 100644 --- a/x-pack/plugins/encrypted_saved_objects/tsconfig.json +++ b/x-pack/plugins/encrypted_saved_objects/tsconfig.json @@ -11,6 +11,7 @@ "@kbn/utility-types", "@kbn/core-saved-objects-server", "@kbn/core-saved-objects-base-server-internal", + "@kbn/core-saved-objects-api-server-mocks", ], "exclude": [ "target/**/*", diff --git a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts index fb17854f6f674..bae0aacec6ff4 100644 --- a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts @@ -259,7 +259,7 @@ describe('callEnterpriseSearchConfigAPI', () => { jest.useFakeTimers({ legacyFakeTimers: true }); // Warning - callEnterpriseSearchConfigAPI(mockDependencies); + void callEnterpriseSearchConfigAPI(mockDependencies); jest.advanceTimersByTime(150); expect(mockDependencies.log.warn).toHaveBeenCalledWith( 'Enterprise Search access check took over 100ms. Please ensure your Enterprise Search server is responding normally and not adversely impacting Kibana load speeds.' diff --git a/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/create_ml_inference_pipeline.test.ts b/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/create_ml_inference_pipeline.test.ts index 62fc7935b169a..7c3104dc84928 100644 --- a/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/create_ml_inference_pipeline.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/create_ml_inference_pipeline.test.ts @@ -78,7 +78,7 @@ describe('createMlInferencePipeline lib function', () => { ); }); - it('should throw an error without creating the pipeline if it already exists', () => { + it('should throw an error without creating the pipeline if it already exists', async () => { mockClient.ingest.getPipeline.mockImplementation(() => Promise.resolve({ [inferencePipelineGeneratedName]: {}, @@ -91,7 +91,7 @@ describe('createMlInferencePipeline lib function', () => { mockClient as unknown as ElasticsearchClient ); - expect(actualResult).rejects.toThrow(Error); + await expect(actualResult).rejects.toThrow(Error); expect(mockClient.ingest.putPipeline).not.toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/get_ml_inference_pipeline_processors.test.ts b/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/get_ml_inference_pipeline_processors.test.ts index 020d717417820..157c9f13ca055 100644 --- a/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/get_ml_inference_pipeline_processors.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/get_ml_inference_pipeline_processors.test.ts @@ -727,8 +727,8 @@ describe('fetchMlInferencePipelineProcessors lib function', () => { }); describe('when Machine Learning is disabled in the current space', () => { - it('should throw an error', () => { - expect(() => + it('should throw an error', async () => { + await expect(() => fetchMlInferencePipelineProcessors( mockClient as unknown as ElasticsearchClient, undefined, diff --git a/x-pack/plugins/enterprise_search/server/lib/ml/fetch_ml_models.test.ts b/x-pack/plugins/enterprise_search/server/lib/ml/fetch_ml_models.test.ts index 5e2c472dab7ac..9e017424a8f3d 100644 --- a/x-pack/plugins/enterprise_search/server/lib/ml/fetch_ml_models.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/ml/fetch_ml_models.test.ts @@ -35,8 +35,8 @@ describe('fetchMlModels', () => { })); }); - it('errors when there is no trained model provider', () => { - expect(() => fetchMlModels(undefined, mockLogger)).rejects.toThrowError( + it('errors when there is no trained model provider', async () => { + await expect(() => fetchMlModels(undefined, mockLogger)).rejects.toThrowError( 'Machine Learning is not enabled' ); }); diff --git a/x-pack/plugins/enterprise_search/server/lib/ml/get_ml_model_deployment_status.test.ts b/x-pack/plugins/enterprise_search/server/lib/ml/get_ml_model_deployment_status.test.ts index 0b0a42630bcc7..9cc66bdb609f9 100644 --- a/x-pack/plugins/enterprise_search/server/lib/ml/get_ml_model_deployment_status.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/ml/get_ml_model_deployment_status.test.ts @@ -22,8 +22,8 @@ describe('getMlModelDeploymentStatus', () => { jest.clearAllMocks(); }); - it('should error when there is no trained model provider', () => { - expect(() => getMlModelDeploymentStatus('mockModelName', undefined)).rejects.toThrowError( + it('should error when there is no trained model provider', async () => { + await expect(() => getMlModelDeploymentStatus('mockModelName', undefined)).rejects.toThrowError( 'Machine Learning is not enabled' ); }); diff --git a/x-pack/plugins/enterprise_search/server/lib/ml/start_ml_model_deployment.test.ts b/x-pack/plugins/enterprise_search/server/lib/ml/start_ml_model_deployment.test.ts index 67a5c75f0f437..9111bee449ec8 100644 --- a/x-pack/plugins/enterprise_search/server/lib/ml/start_ml_model_deployment.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/ml/start_ml_model_deployment.test.ts @@ -26,8 +26,8 @@ describe('startMlModelDeployment', () => { jest.clearAllMocks(); }); - it('should error when there is no trained model provider', () => { - expect(() => startMlModelDeployment(modelName, undefined)).rejects.toThrowError( + it('should error when there is no trained model provider', async () => { + await expect(() => startMlModelDeployment(modelName, undefined)).rejects.toThrowError( 'Machine Learning is not enabled' ); }); diff --git a/x-pack/plugins/enterprise_search/server/lib/ml/start_ml_model_download.test.ts b/x-pack/plugins/enterprise_search/server/lib/ml/start_ml_model_download.test.ts index 80318eab0ce77..51023f643504e 100644 --- a/x-pack/plugins/enterprise_search/server/lib/ml/start_ml_model_download.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/ml/start_ml_model_download.test.ts @@ -26,8 +26,8 @@ describe('startMlModelDownload', () => { jest.clearAllMocks(); }); - it('should error when there is no trained model provider', () => { - expect(() => startMlModelDownload(knownModelName, undefined)).rejects.toThrowError( + it('should error when there is no trained model provider', async () => { + await expect(() => startMlModelDownload(knownModelName, undefined)).rejects.toThrowError( 'Machine Learning is not enabled' ); }); diff --git a/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.test.ts b/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.test.ts index 0765fafcc9d1d..89ab6abe8ec77 100644 --- a/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.test.ts @@ -25,8 +25,8 @@ describe('getMlInferencePipelines', () => { jest.clearAllMocks(); }); - it('should throw an error if Machine Learning is disabled in the current space', () => { - expect(() => + it('should throw an error if Machine Learning is disabled in the current space', async () => { + await expect(() => getMlInferencePipelines(mockClient as unknown as ElasticsearchClient, undefined) ).rejects.toThrowError('Machine Learning is not enabled'); }); diff --git a/x-pack/plugins/enterprise_search/server/plugin.ts b/x-pack/plugins/enterprise_search/server/plugin.ts index bd1498e0b0b61..24298c55fdffa 100644 --- a/x-pack/plugins/enterprise_search/server/plugin.ts +++ b/x-pack/plugins/enterprise_search/server/plugin.ts @@ -274,11 +274,11 @@ export class EnterpriseSearchPlugin implements Plugin { registerStatsRoutes(dependencies); // Analytics Routes (stand-alone product) - getStartServices().then(([coreStart, { data }]) => { + void getStartServices().then(([coreStart, { data }]) => { registerAnalyticsRoutes({ ...dependencies, data, savedObjects: coreStart.savedObjects }); }); - getStartServices().then(([, { security: securityStart }]) => { + void getStartServices().then(([, { security: securityStart }]) => { registerApiKeysRoutes(dependencies, securityStart); }); @@ -292,7 +292,7 @@ export class EnterpriseSearchPlugin implements Plugin { } let savedObjectsStarted: SavedObjectsServiceStart; - getStartServices().then(([coreStart]) => { + void getStartServices().then(([coreStart]) => { savedObjectsStarted = coreStart.savedObjects; if (usageCollection) { diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/adaptive_relevance.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/adaptive_relevance.test.ts index cec2262c95a2e..4df97172fa0d5 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/adaptive_relevance.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/adaptive_relevance.test.ts @@ -27,8 +27,8 @@ describe('search relevance insights routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, }); @@ -51,8 +51,8 @@ describe('search relevance insights routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, body: { query: 'some query', @@ -80,8 +80,8 @@ describe('search relevance insights routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, }); @@ -104,8 +104,8 @@ describe('search relevance insights routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, body: { curation: { enabled: true } }, }); @@ -129,8 +129,8 @@ describe('search relevance insights routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine', query: 'foo' }, query: { type: 'curation' }, }); diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/engines.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/engines.test.ts index cd1221ec52b80..f86001832a3c6 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/engines.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/engines.test.ts @@ -34,8 +34,8 @@ describe('engine routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute(mockRequest); + it('creates a request handler', async () => { + await mockRouter.callRoute(mockRequest); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/as/engines/collection', @@ -44,7 +44,7 @@ describe('engine routes', () => { }); describe('hasValidData', () => { - it('should correctly validate that the response has data', () => { + it('should correctly validate that the response has data', async () => { mockRequestHandler.createRequest.mockClear(); const response = { meta: { @@ -55,15 +55,15 @@ describe('engine routes', () => { results: [], }; - mockRouter.callRoute(mockRequest); + await mockRouter.callRoute(mockRequest); expect(mockRequestHandler.hasValidData(response)).toBe(true); }); - it('should correctly validate that a response does not have data', () => { + it('should correctly validate that a response does not have data', async () => { mockRequestHandler.createRequest.mockClear(); const response = {}; - mockRouter.callRoute(mockRequest); + await mockRouter.callRoute(mockRequest); expect(mockRequestHandler.hasValidData(response)).toBe(false); }); }); @@ -114,8 +114,8 @@ describe('engine routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute({ body: { name: 'some-engine', language: 'en' } }); + it('creates a request handler', async () => { + await mockRouter.callRoute({ body: { name: 'some-engine', language: 'en' } }); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/as/engines/collection', }); @@ -192,8 +192,8 @@ describe('engine routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute({ + it('creates a request handler', async () => { + await mockRouter.callRoute({ body: { name: 'some-elasticindexed-engine', search_index: { type: 'elasticsearch', index_name: 'search-elastic-index' }, diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/onboarding.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/onboarding.test.ts index 8990a9e1eeab4..bb281983d5382 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/onboarding.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/onboarding.test.ts @@ -26,8 +26,8 @@ describe('engine routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute({ body: {} }); + it('creates a request handler', async () => { + await mockRouter.callRoute({ body: {} }); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/as/onboarding/complete', hasJsonResponse: false, diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/result_settings.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/result_settings.test.ts index d82eb06fce68e..fcbf10c080b30 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/result_settings.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/result_settings.test.ts @@ -35,8 +35,8 @@ describe('result settings routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, }); @@ -59,8 +59,8 @@ describe('result settings routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, body: { result_settings: resultFields, diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/search_settings.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/search_settings.test.ts index 56e60db543c5d..5b6395912766f 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/search_settings.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/search_settings.test.ts @@ -73,8 +73,8 @@ describe('search settings routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, }); @@ -97,8 +97,8 @@ describe('search settings routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, body: searchSettings, }); @@ -122,8 +122,8 @@ describe('search settings routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, }); diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/search_ui.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/search_ui.test.ts index e92dc63952eb5..1cfb52640c09b 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/search_ui.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/search_ui.test.ts @@ -27,8 +27,8 @@ describe('reference application routes', () => { }); }); - it('creates a request to enterprise search', () => { - mockRouter.callRoute({ + it('creates a request to enterprise search', async () => { + await mockRouter.callRoute({ params: { engineName: 'some-engine' }, }); diff --git a/x-pack/plugins/enterprise_search/server/routes/workplace_search/oauth.test.ts b/x-pack/plugins/enterprise_search/server/routes/workplace_search/oauth.test.ts index ab9d5e20cfe92..af703c1d0ceee 100644 --- a/x-pack/plugins/enterprise_search/server/routes/workplace_search/oauth.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/workplace_search/oauth.test.ts @@ -31,8 +31,8 @@ describe('oauth routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute({}); + it('creates a request handler', async () => { + await mockRouter.callRoute({}); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/ws/oauth/authorize', @@ -76,8 +76,8 @@ describe('oauth routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute({}); + it('creates a request handler', async () => { + await mockRouter.callRoute({}); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/ws/oauth/authorize', @@ -117,8 +117,8 @@ describe('oauth routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute({}); + it('creates a request handler', async () => { + await mockRouter.callRoute({}); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/ws/oauth/authorize', diff --git a/x-pack/plugins/enterprise_search/server/routes/workplace_search/security.test.ts b/x-pack/plugins/enterprise_search/server/routes/workplace_search/security.test.ts index 744f0e689cd82..ebcbba2767be3 100644 --- a/x-pack/plugins/enterprise_search/server/routes/workplace_search/security.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/workplace_search/security.test.ts @@ -27,8 +27,8 @@ describe('security routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute({}); + it('creates a request handler', async () => { + await mockRouter.callRoute({}); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/ws/org/security', @@ -53,8 +53,8 @@ describe('security routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute({}); + it('creates a request handler', async () => { + await mockRouter.callRoute({}); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/ws/org/security/source_restrictions', diff --git a/x-pack/plugins/enterprise_search/server/routes/workplace_search/sources.test.ts b/x-pack/plugins/enterprise_search/server/routes/workplace_search/sources.test.ts index ea8caede378de..06b6fce3baee5 100644 --- a/x-pack/plugins/enterprise_search/server/routes/workplace_search/sources.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/workplace_search/sources.test.ts @@ -556,7 +556,7 @@ describe('sources routes', () => { }); }); - it('creates a request handler', () => { + it('creates a request handler', async () => { const mockRequest = { params: { sourceId: '123', @@ -564,7 +564,7 @@ describe('sources routes', () => { }, }; - mockRouter.callRoute(mockRequest); + await mockRouter.callRoute(mockRequest); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/ws/sources/:sourceId/reindex_job/:jobId', @@ -1343,8 +1343,8 @@ describe('sources routes', () => { }); }); - it('creates a request handler', () => { - mockRouter.callRoute(mockRequest as any); + it('creates a request handler', async () => { + await mockRouter.callRoute(mockRequest as any); expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/ws/sources/create', diff --git a/x-pack/plugins/event_log/server/event_log_client.test.ts b/x-pack/plugins/event_log/server/event_log_client.test.ts index d44ae68745245..5abd44061eb4d 100644 --- a/x-pack/plugins/event_log/server/event_log_client.test.ts +++ b/x-pack/plugins/event_log/server/event_log_client.test.ts @@ -167,7 +167,7 @@ describe('EventLogStart', () => { total: 0, data: [], }); - expect( + await expect( eventLogClient.findEventsBySavedObjectIds('saved-object-type', ['saved-object-id'], { start: 'not a date string', }) @@ -181,7 +181,7 @@ describe('EventLogStart', () => { total: 0, data: [], }); - expect( + await expect( eventLogClient.findEventsBySavedObjectIds('saved-object-type', ['saved-object-id'], { end: 'not a date string', }) diff --git a/x-pack/plugins/event_log/server/event_logger.test.ts b/x-pack/plugins/event_log/server/event_logger.test.ts index a9295ada0dd85..ccf5b9a39d7d5 100644 --- a/x-pack/plugins/event_log/server/event_logger.test.ts +++ b/x-pack/plugins/event_log/server/event_logger.test.ts @@ -48,7 +48,7 @@ describe('EventLogger', () => { eventLogger.logEvent({}); await waitForLogEvent(systemLogger); - delay(WRITE_LOG_WAIT_MILLIS); // sleep a bit since event logging is async + await delay(WRITE_LOG_WAIT_MILLIS); // sleep a bit since event logging is async expect(esContext.esAdapter.indexDocument).toHaveBeenCalled(); }); @@ -61,7 +61,7 @@ describe('EventLogger', () => { eventLogger.logEvent({}); await waitForLogEvent(systemLogger); - delay(WRITE_LOG_WAIT_MILLIS); // sleep a bit longer since event logging is async + await delay(WRITE_LOG_WAIT_MILLIS); // sleep a bit longer since event logging is async expect(esContext.esAdapter.indexDocument).toHaveBeenCalled(); expect(esContext.esAdapter.indexDocuments).not.toHaveBeenCalled(); }); diff --git a/x-pack/plugins/event_log/server/plugin.ts b/x-pack/plugins/event_log/server/plugin.ts index 4b0dcbece34b4..b5a6a6bcbe37d 100644 --- a/x-pack/plugins/event_log/server/plugin.ts +++ b/x-pack/plugins/event_log/server/plugin.ts @@ -111,11 +111,18 @@ export class Plugin implements CorePlugin { - if (!success) { - this.systemLogger.error(`initialization failed, events will not be indexed`); - } - }); + this.esContext + .waitTillReady() + .then((success) => { + if (!success) { + this.systemLogger.error(`initialization failed, events will not be indexed`); + } + }) + .catch((error) => { + this.systemLogger.error( + `initialization failed with error: ${error}. Events will not be indexed` + ); + }); // will log the event after initialization this.eventLogger.logEvent({ diff --git a/x-pack/plugins/file_upload/server/telemetry/usage_collector.ts b/x-pack/plugins/file_upload/server/telemetry/usage_collector.ts index d3909a904c26f..b774ac5eb7a97 100644 --- a/x-pack/plugins/file_upload/server/telemetry/usage_collector.ts +++ b/x-pack/plugins/file_upload/server/telemetry/usage_collector.ts @@ -18,7 +18,7 @@ export function initFileUploadTelemetry( ) { coreSetup.savedObjects.registerType(telemetryMappingsType); registerUsageCollector(usageCollection); - coreSetup.getStartServices().then(([core]) => { + void coreSetup.getStartServices().then(([core]) => { setInternalRepository(core.savedObjects.createInternalRepository); }); } diff --git a/x-pack/plugins/fleet/server/plugin.ts b/x-pack/plugins/fleet/server/plugin.ts index aad61fd21c9ae..c24f7859b1189 100644 --- a/x-pack/plugins/fleet/server/plugin.ts +++ b/x-pack/plugins/fleet/server/plugin.ts @@ -613,12 +613,14 @@ export class FleetPlugin uninstallTokenService, }); licenseService.start(plugins.licensing.license$); - this.telemetryEventsSender.start(plugins.telemetry, core); - this.bulkActionsResolver?.start(plugins.taskManager); - this.fleetUsageSender?.start(plugins.taskManager); - this.checkDeletedFilesTask?.start({ taskManager: plugins.taskManager }); - startFleetUsageLogger(plugins.taskManager); - this.fleetMetricsTask?.start(plugins.taskManager, core.elasticsearch.client.asInternalUser); + this.telemetryEventsSender.start(plugins.telemetry, core).catch(() => {}); + this.bulkActionsResolver?.start(plugins.taskManager).catch(() => {}); + this.fleetUsageSender?.start(plugins.taskManager).catch(() => {}); + this.checkDeletedFilesTask?.start({ taskManager: plugins.taskManager }).catch(() => {}); + startFleetUsageLogger(plugins.taskManager).catch(() => {}); + this.fleetMetricsTask + ?.start(plugins.taskManager, core.elasticsearch.client.asInternalUser) + .catch(() => {}); const logger = appContextService.getLogger(); @@ -686,7 +688,7 @@ export class FleetPlugin ); // initialize (generate/encrypt/validate) Uninstall Tokens asynchronously - this.initializeUninstallTokens(); + this.initializeUninstallTokens().catch(() => {}); this.fleetStatus$.next({ level: ServiceStatusLevels.available, diff --git a/x-pack/plugins/fleet/server/routes/index.ts b/x-pack/plugins/fleet/server/routes/index.ts index d03703af22bb7..5177b85d84dea 100644 --- a/x-pack/plugins/fleet/server/routes/index.ts +++ b/x-pack/plugins/fleet/server/routes/index.ts @@ -27,7 +27,7 @@ import { registerRoutes as registerFleetProxiesRoutes } from './fleet_proxies'; import { registerRoutes as registerMessageSigningServiceRoutes } from './message_signing_service'; import { registerRoutes as registerUninstallTokenRoutes } from './uninstall_token'; -export async function registerRoutes(fleetAuthzRouter: FleetAuthzRouter, config: FleetConfigType) { +export function registerRoutes(fleetAuthzRouter: FleetAuthzRouter, config: FleetConfigType) { // Always register app routes for permissions checking registerAppRoutes(fleetAuthzRouter); diff --git a/x-pack/plugins/fleet/server/services/agent_policy_create.test.ts b/x-pack/plugins/fleet/server/services/agent_policy_create.test.ts index f541212a51ab1..1c569270a3c9d 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy_create.test.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy_create.test.ts @@ -192,15 +192,17 @@ describe('createAgentPolicyWithPackages', () => { it('should call deploy policy once when create policy with system package', async () => { mockedAgentPolicyService.deployPolicy.mockClear(); - mockedAgentPolicyService.create.mockImplementation((soClient, esClient, newPolicy, options) => { - if (!options?.skipDeploy) { - mockedAgentPolicyService.deployPolicy(soClientMock, 'new_id'); + mockedAgentPolicyService.create.mockImplementation( + async (soClient, esClient, newPolicy, options) => { + if (!options?.skipDeploy) { + await mockedAgentPolicyService.deployPolicy(soClientMock, 'new_id'); + } + return Promise.resolve({ + ...newPolicy, + id: options?.id || 'new_id', + } as AgentPolicy); } - return Promise.resolve({ - ...newPolicy, - id: options?.id || 'new_id', - } as AgentPolicy); - }); + ); const response = await createAgentPolicyWithPackages({ esClient: esClientMock, soClient: soClientMock, diff --git a/x-pack/plugins/fleet/server/services/agents/action_runner.ts b/x-pack/plugins/fleet/server/services/agents/action_runner.ts index d8834d5306a92..3abe4787e6132 100644 --- a/x-pack/plugins/fleet/server/services/agents/action_runner.ts +++ b/x-pack/plugins/fleet/server/services/agents/action_runner.ts @@ -83,12 +83,12 @@ export abstract class ActionRunner { // create task to check result with some delay, this runs in case of kibana crash too this.checkTaskId = await this.createCheckResultTask(); - withSpan({ name: this.getActionType(), type: 'action' }, () => + await withSpan({ name: this.getActionType(), type: 'action' }, () => this.processAgentsInBatches() - .then(() => { + .then(async () => { if (this.checkTaskId) { // no need for check task, action succeeded - this.bulkActionsResolver!.removeIfExists(this.checkTaskId); + await this.bulkActionsResolver!.removeIfExists(this.checkTaskId); } }) .catch(async (error) => { @@ -233,7 +233,7 @@ export abstract class ActionRunner { allAgentsProcessed += currentAgents.length; if (this.checkTaskId) { // updating check task with latest checkpoint (this.retryParams.searchAfter) - this.bulkActionsResolver?.removeIfExists(this.checkTaskId); + await this.bulkActionsResolver?.removeIfExists(this.checkTaskId); this.checkTaskId = await this.createCheckResultTask(); } } diff --git a/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts b/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts index 782b044a84697..8c711099264f4 100644 --- a/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts +++ b/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts @@ -355,7 +355,7 @@ describe('When using the artifacts services', () => { describe('and calling `deleteArtifact()`', () => { it('should delete the artifact', async () => { - deleteArtifact(esClientMock, '123'); + await deleteArtifact(esClientMock, '123'); expect(esClientMock.delete).toHaveBeenCalledWith({ index: FLEET_SERVER_ARTIFACTS_INDEX, @@ -375,7 +375,7 @@ describe('When using the artifacts services', () => { describe('and calling `bulkDeleteArtifacts()`', () => { it('should delete single artifact', async () => { - bulkDeleteArtifacts(esClientMock, ['123']); + await bulkDeleteArtifacts(esClientMock, ['123']); expect(esClientMock.bulk).toHaveBeenCalledWith({ refresh: 'wait_for', @@ -391,7 +391,7 @@ describe('When using the artifacts services', () => { }); it('should delete all the artifacts', async () => { - bulkDeleteArtifacts(esClientMock, ['123', '231']); + await bulkDeleteArtifacts(esClientMock, ['123', '231']); expect(esClientMock.bulk).toHaveBeenCalledWith({ refresh: 'wait_for', diff --git a/x-pack/plugins/fleet/server/services/download_source.test.ts b/x-pack/plugins/fleet/server/services/download_source.test.ts index e244ec80077b2..1e9c7275c8430 100644 --- a/x-pack/plugins/fleet/server/services/download_source.test.ts +++ b/x-pack/plugins/fleet/server/services/download_source.test.ts @@ -291,12 +291,12 @@ describe('Download Service', () => { }); describe('requireUniqueName', () => { - it('throws an error if the name already exists', () => { + it('throws an error if the name already exists', async () => { const soClient = getMockedSoClient({ defaultDownloadSourceId: 'download-source-test', sameName: true, }); - expect( + await expect( async () => await downloadSourceService.requireUniqueName(soClient, { name: 'Test' }) ).rejects.toThrow(`Download Source 'download-source-test' already exists with name 'Test'`); }); diff --git a/x-pack/plugins/fleet/server/services/epm/archive/extract.ts b/x-pack/plugins/fleet/server/services/epm/archive/extract.ts index 84c2457f4dafe..17118aa06b199 100644 --- a/x-pack/plugins/fleet/server/services/epm/archive/extract.ts +++ b/x-pack/plugins/fleet/server/services/epm/archive/extract.ts @@ -24,9 +24,9 @@ export async function untarBuffer( const inflateStream = tar.list().on('entry', (entry) => { const path = entry.path || ''; if (!filter({ path })) return; - streamToBuffer(entry as unknown as NodeJS.ReadableStream).then((entryBuffer) => - onEntry({ buffer: entryBuffer, path }) - ); + streamToBuffer(entry as unknown as NodeJS.ReadableStream) + .then((entryBuffer) => onEntry({ buffer: entryBuffer, path })) + .catch(() => {}); }); deflatedStream.pipe(inflateStream); diff --git a/x-pack/plugins/fleet/server/services/epm/kibana/assets/install.test.ts b/x-pack/plugins/fleet/server/services/epm/kibana/assets/install.test.ts index 06b09e15951c4..3547fc70daa15 100644 --- a/x-pack/plugins/fleet/server/services/epm/kibana/assets/install.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/kibana/assets/install.test.ts @@ -93,7 +93,7 @@ describe('installKibanaSavedObjects', () => { mockImporter.import.mockResolvedValueOnce(errorResponse).mockResolvedValueOnce(successResponse); - expect( + await expect( installKibanaSavedObjects({ savedObjectsImporter: mockImporter, logger: mockLogger, diff --git a/x-pack/plugins/fleet/server/services/epm/packages/_install_package.test.ts b/x-pack/plugins/fleet/server/services/epm/packages/_install_package.test.ts index 7568dafe248ac..dec78b3be7d5c 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/_install_package.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/_install_package.test.ts @@ -325,7 +325,7 @@ describe('_installPackage', () => { describe('timeout not reached', () => { describe('force flag not provided', () => { it('throws concurrent installation error if force flag is not provided', async () => { - expect( + await expect( _installPackage({ savedObjectsClient: soClient, // @ts-ignore @@ -386,7 +386,7 @@ describe('_installPackage', () => { }); }); - it('surfaces saved object conflicts error', () => { + it('surfaces saved object conflicts error', async () => { appContextService.start( createAppContextStartContractMock({ internal: { @@ -407,7 +407,7 @@ describe('_installPackage', () => { new PackageSavedObjectConflictError('test') ); - expect( + await expect( _installPackage({ savedObjectsClient: soClient, // @ts-ignore diff --git a/x-pack/plugins/fleet/server/services/epm/packages/install.ts b/x-pack/plugins/fleet/server/services/epm/packages/install.ts index c8c2e542bfe8b..c5ce7e5f0eca8 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/install.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/install.ts @@ -1279,7 +1279,7 @@ export const saveKibanaAssetsRefs = async ( // Because Kibana assets are installed in parallel with ES assets with refresh: false, we almost always run into an // issue that causes a conflict error due to this issue: https://github.com/elastic/kibana/issues/126240. This is safe // to retry constantly until it succeeds to optimize this critical user journey path as much as possible. - pRetry( + await pRetry( () => savedObjectsClient.update( PACKAGES_SAVED_OBJECT_TYPE, diff --git a/x-pack/plugins/fleet/server/services/epm/registry/index.test.ts b/x-pack/plugins/fleet/server/services/epm/registry/index.test.ts index 8b129e6fe2f6c..6de0577e33238 100644 --- a/x-pack/plugins/fleet/server/services/epm/registry/index.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/registry/index.test.ts @@ -153,7 +153,7 @@ describe('fetch package', () => { mockGetBundledPackageByName.mockResolvedValue(bundledPackage); - expect(() => fetchFindLatestPackageOrThrow('testpkg')).rejects.toBeInstanceOf( + await expect(() => fetchFindLatestPackageOrThrow('testpkg')).rejects.toBeInstanceOf( PackageNotFoundError ); }); diff --git a/x-pack/plugins/fleet/server/services/epm/registry/requests.test.ts b/x-pack/plugins/fleet/server/services/epm/registry/requests.test.ts index e13ff87bf45e5..e4e34d25671f6 100644 --- a/x-pack/plugins/fleet/server/services/epm/registry/requests.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/registry/requests.test.ts @@ -42,7 +42,7 @@ describe('Registry request', () => { (appContextService.getKibanaVersion as jest.Mock).mockReturnValue('8.0.0'); }); it('should set User-Agent header including kibana version', async () => { - getResponse(''); + await getResponse(''); expect(fetchMock).toHaveBeenCalledWith('', { headers: { @@ -54,7 +54,7 @@ describe('Registry request', () => { it('should set User-Agent header including kibana version with agent', async () => { mockRegistryProxyUrl = 'url'; - getResponse(''); + await getResponse(''); expect(fetchMock).toHaveBeenCalledWith('', { agent: 'proxy agent', diff --git a/x-pack/plugins/fleet/server/services/files/index.test.ts b/x-pack/plugins/fleet/server/services/files/index.test.ts index 551cded5d66b2..2991c1dcbd1a6 100644 --- a/x-pack/plugins/fleet/server/services/files/index.test.ts +++ b/x-pack/plugins/fleet/server/services/files/index.test.ts @@ -165,14 +165,14 @@ describe('files service', () => { }); describe('#updateFilesStatus()', () => { - it('calls esClient.updateByQuery with expected values', () => { + it('calls esClient.updateByQuery with expected values', async () => { const FAKE_INTEGRATION_METADATA_INDEX = getFileMetadataIndexName('someintegration'); const files = { [ENDPOINT_FILE_METADATA_INDEX]: new Set(['delete1', 'delete2']), [FAKE_INTEGRATION_METADATA_INDEX]: new Set(['delete2', 'delete3']), }; const status = 'DELETED'; - updateFilesStatus(esClientMock, abortController, files, status); + await updateFilesStatus(esClientMock, abortController, files, status); expect(esClientMock.updateByQuery).toHaveBeenNthCalledWith( 1, diff --git a/x-pack/plugins/fleet/server/services/fleet_proxies.ts b/x-pack/plugins/fleet/server/services/fleet_proxies.ts index 61aa07b8e0614..4cfc81db50740 100644 --- a/x-pack/plugins/fleet/server/services/fleet_proxies.ts +++ b/x-pack/plugins/fleet/server/services/fleet_proxies.ts @@ -201,32 +201,30 @@ async function updateRelatedSavedObject( ) { await pMap( fleetServerHosts, - (fleetServerHost) => { + (fleetServerHost) => updateFleetServerHost(soClient, fleetServerHost.id, { ...omit(fleetServerHost, 'id'), proxy_id: null, - }); - }, + }), { concurrency: 20 } ); await pMap( outputs, - (output) => { + (output) => outputService.update(soClient, esClient, output.id, { ...omit(output, 'id'), proxy_id: null, - } as Partial); - }, + } as Partial), { concurrency: 20 } ); - await pMap(downloadSources, (downloadSource) => { + await pMap(downloadSources, (downloadSource) => downloadSourceService.update(soClient, downloadSource.id, { ...omit(downloadSource, 'id'), proxy_id: null, - }); - }); + }) + ); } export async function getFleetProxyRelatedSavedObjects( diff --git a/x-pack/plugins/fleet/server/services/fleet_usage_logger.ts b/x-pack/plugins/fleet/server/services/fleet_usage_logger.ts index 92a1dc6da33cf..76c4aba77038c 100644 --- a/x-pack/plugins/fleet/server/services/fleet_usage_logger.ts +++ b/x-pack/plugins/fleet/server/services/fleet_usage_logger.ts @@ -17,7 +17,7 @@ import { appContextService } from './app_context'; const TASK_ID = 'Fleet-Usage-Logger-Task'; const TASK_TYPE = 'Fleet-Usage-Logger'; -export async function registerFleetUsageLogger( +export function registerFleetUsageLogger( taskManager: TaskManagerSetupContract, fetchUsage: () => ReturnType ) { diff --git a/x-pack/plugins/fleet/server/services/output.test.ts b/x-pack/plugins/fleet/server/services/output.test.ts index 13409f7e6f1d4..887a0ac9e0c8f 100644 --- a/x-pack/plugins/fleet/server/services/output.test.ts +++ b/x-pack/plugins/fleet/server/services/output.test.ts @@ -522,7 +522,7 @@ describe('Output Service', () => { it('should throw an error when preset: balanced is provided but config_yaml contains a reserved key', async () => { const soClient = getMockedSoClient({}); - expect( + await expect( outputService.create( soClient, esClientMock, @@ -879,7 +879,7 @@ describe('Output Service', () => { defaultOutputId: 'output-test', }); - expect( + await expect( outputService.create( soClient, esClientMock, @@ -1703,7 +1703,7 @@ describe('Output Service', () => { defaultOutputId: 'output-test', }); - expect( + await expect( outputService.update(soClient, esClientMock, 'output-test', { is_default: true, is_default_monitoring: false, diff --git a/x-pack/plugins/fleet/server/services/package_policy.test.ts b/x-pack/plugins/fleet/server/services/package_policy.test.ts index cc605900c3a58..9d288049f67df 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.test.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.test.ts @@ -2888,7 +2888,7 @@ describe('Package policy service', () => { it('should fail to return the package policy', async () => { const soClient = savedObjectsClientMock.create(); const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; - expect( + await expect( packagePolicyService.runExternalCallbacks( 'packagePolicyCreate', newPackagePolicy, @@ -4905,7 +4905,7 @@ describe('Package policy service', () => { it('should return error if package policy newer than package version', async () => { mockPackage('aws'); - expect( + await expect( packagePolicyService.getUpgradePackagePolicyInfo(savedObjectsClient, 'package-policy-id') ).rejects.toEqual( new PackagePolicyIneligibleForUpgradeError( @@ -4917,7 +4917,7 @@ describe('Package policy service', () => { it('should return error if package not installed', async () => { mockPackage('notinstalled'); - expect( + await expect( packagePolicyService.getUpgradePackagePolicyInfo(savedObjectsClient, 'package-policy-id') ).rejects.toEqual(new FleetError('Package notinstalled is not installed')); }); diff --git a/x-pack/plugins/fleet/server/services/security/message_signing_service.ts b/x-pack/plugins/fleet/server/services/security/message_signing_service.ts index 741b9e33dec88..9e3ec0f0bbc21 100644 --- a/x-pack/plugins/fleet/server/services/security/message_signing_service.ts +++ b/x-pack/plugins/fleet/server/services/security/message_signing_service.ts @@ -234,7 +234,7 @@ export class MessageSigningService implements MessageSigningServiceInterface { soDoc = result.saved_objects[0]; break; } - finder.close(); + await finder.close(); if (soDoc?.error) { throw soDoc.error; diff --git a/x-pack/plugins/fleet/server/services/security/uninstall_token_service/index.ts b/x-pack/plugins/fleet/server/services/security/uninstall_token_service/index.ts index 7b9da34315418..63753401cc417 100644 --- a/x-pack/plugins/fleet/server/services/security/uninstall_token_service/index.ts +++ b/x-pack/plugins/fleet/server/services/security/uninstall_token_service/index.ts @@ -352,7 +352,7 @@ export class UninstallTokenService implements UninstallTokenServiceInterface { tokenObjects = result.saved_objects; break; } - tokensFinder.close(); + await tokensFinder.close(); return tokenObjects; } @@ -497,7 +497,7 @@ export class UninstallTokenService implements UninstallTokenServiceInterface { if (force) { const config = appContextService.getConfig(); const batchSize = config?.setup?.agentPolicySchemaUpgradeBatchSize ?? 100; - asyncForEach( + await asyncForEach( chunk(policyIds, batchSize), async (policyIdsBatch) => await agentPolicyService.deployPolicies(this.soClient, policyIdsBatch) diff --git a/x-pack/plugins/fleet/server/telemetry/sender.test.ts b/x-pack/plugins/fleet/server/telemetry/sender.test.ts index 74e3e1dba1319..0f79cd8464e3e 100644 --- a/x-pack/plugins/fleet/server/telemetry/sender.test.ts +++ b/x-pack/plugins/fleet/server/telemetry/sender.test.ts @@ -29,7 +29,7 @@ describe('TelemetryEventsSender', () => { let logger: ReturnType; let sender: TelemetryEventsSender; - beforeEach(() => { + beforeEach(async () => { logger = loggingSystemMock.createLogger(); sender = new TelemetryEventsSender(logger); sender['fetchClusterInfo'] = jest.fn(async () => { @@ -41,7 +41,7 @@ describe('TelemetryEventsSender', () => { }, } as InfoResponse; }); - sender.start(undefined, { + await sender.start(undefined, { elasticsearch: { client: { asInternalUser: { info: jest.fn(async () => ({})) } } }, } as any); }); diff --git a/x-pack/plugins/fleet/server/telemetry/sender.ts b/x-pack/plugins/fleet/server/telemetry/sender.ts index 7684284165ee1..d50464b1a34e1 100644 --- a/x-pack/plugins/fleet/server/telemetry/sender.ts +++ b/x-pack/plugins/fleet/server/telemetry/sender.ts @@ -14,6 +14,8 @@ import axios from 'axios'; import type { InfoResponse } from '@elastic/elasticsearch/lib/api/types'; +import { exhaustMap, Subject, takeUntil, timer } from 'rxjs'; + import { TelemetryQueue } from './queue'; import type { FleetTelemetryChannel, FleetTelemetryChannelEvents } from './types'; @@ -26,10 +28,10 @@ export class TelemetryEventsSender { private readonly initialCheckDelayMs = 10 * 1000; private readonly checkIntervalMs = 30 * 1000; private readonly logger: Logger; + private readonly stop$ = new Subject(); private telemetryStart?: TelemetryPluginStart; private telemetrySetup?: TelemetryPluginSetup; - private intervalId?: NodeJS.Timeout; private isSending = false; private queuesPerChannel: { [channel: string]: TelemetryQueue } = {}; private isOptedIn?: boolean = true; // Assume true until the first check @@ -50,16 +52,16 @@ export class TelemetryEventsSender { this.clusterInfo = await this.fetchClusterInfo(); this.logger.debug(`Starting local task`); - setTimeout(() => { - this.sendIfDue(); - this.intervalId = setInterval(() => this.sendIfDue(), this.checkIntervalMs); - }, this.initialCheckDelayMs); + timer(this.initialCheckDelayMs, this.checkIntervalMs) + .pipe( + takeUntil(this.stop$), + exhaustMap(() => this.sendIfDue()) + ) + .subscribe(); } public stop() { - if (this.intervalId) { - clearInterval(this.intervalId); - } + this.stop$.next(); } public queueTelemetryEvents( diff --git a/x-pack/plugins/license_api_guard/server/license.test.ts b/x-pack/plugins/license_api_guard/server/license.test.ts index 9f20a3e20e995..8beeddfd1d35c 100644 --- a/x-pack/plugins/license_api_guard/server/license.test.ts +++ b/x-pack/plugins/license_api_guard/server/license.test.ts @@ -58,7 +58,14 @@ describe('License API guard', () => { const forbidden = jest.fn(); const responseMock = httpServerMock.createResponseFactory(); responseMock.forbidden = forbidden; - guardedRoute({} as RequestHandlerContext, {} as KibanaRequest, responseMock); + const maybePromise = guardedRoute( + {} as RequestHandlerContext, + {} as KibanaRequest, + responseMock + ); + if (maybePromise instanceof Promise) { + maybePromise.catch(() => {}); + } return { errorResponse: diff --git a/x-pack/plugins/license_management/server/plugin.ts b/x-pack/plugins/license_management/server/plugin.ts index 6368d973a10eb..e1859f84fd162 100644 --- a/x-pack/plugins/license_management/server/plugin.ts +++ b/x-pack/plugins/license_management/server/plugin.ts @@ -35,7 +35,7 @@ export class LicenseManagementServerPlugin ], }); - getStartServices().then(([, { licensing }]) => { + void getStartServices().then(([, { licensing }]) => { this.apiRoutes.setup({ router, plugins: { diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items_point_in_time_finder.ts b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items_point_in_time_finder.ts index 8bd79eaa7f3a2..0f9188930c44b 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items_point_in_time_finder.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items_point_in_time_finder.ts @@ -118,7 +118,7 @@ export const findExceptionListsItemPointInTimeFinder = async ({ ); executeFunctionOnStream(exceptionListItem); try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal @@ -132,7 +132,7 @@ export const findExceptionListsItemPointInTimeFinder = async ({ } try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_point_in_time_finder.ts b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_point_in_time_finder.ts index 77869f2f847fa..4fc9bf96d2a7d 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_point_in_time_finder.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_point_in_time_finder.ts @@ -96,7 +96,7 @@ export const findExceptionListPointInTimeFinder = async ({ exceptionList.data = exceptionList.data.slice(-exceptionList.data.length, -diff); executeFunctionOnStream(exceptionList); try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal @@ -109,7 +109,7 @@ export const findExceptionListPointInTimeFinder = async ({ } try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items_point_in_time_finder.ts b/x-pack/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items_point_in_time_finder.ts index bc34bb18162f7..b216d02437e2a 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items_point_in_time_finder.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/find_value_list_exception_list_items_point_in_time_finder.ts @@ -95,7 +95,7 @@ export const findValueListExceptionListItemsPointInTimeFinder = async ({ exceptionList.data = exceptionList.data.slice(-exceptionList.data.length, -diff); executeFunctionOnStream(exceptionList); try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal @@ -108,7 +108,7 @@ export const findValueListExceptionListItemsPointInTimeFinder = async ({ } try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal diff --git a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts index 635638d51f303..93218b6370e80 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts @@ -590,7 +590,7 @@ export class DataRecognizer { } } // merge all the save results - this._updateResults(results, saveResults); + await this._updateResults(results, saveResults); return results; } diff --git a/x-pack/plugins/ml/server/models/job_service/model_snapshots.ts b/x-pack/plugins/ml/server/models/job_service/model_snapshots.ts index 8889f6b9572d1..b72ad7d1a4fed 100644 --- a/x-pack/plugins/ml/server/models/job_service/model_snapshots.ts +++ b/x-pack/plugins/ml/server/models/job_service/model_snapshots.ts @@ -94,7 +94,7 @@ export function modelSnapshotProvider(client: IScopedClusterClient, mlClient: Ml await cm.newCalendar(calendar); } - forceStartDatafeeds( + await forceStartDatafeeds( [datafeedId], +snapshot.model_snapshots[0].latest_record_time_stamp!, end diff --git a/x-pack/plugins/ml/server/models/json_schema_service/json_schema_service.ts b/x-pack/plugins/ml/server/models/json_schema_service/json_schema_service.ts index ca6e2a0b18b48..86cfd6a0ff7d2 100644 --- a/x-pack/plugins/ml/server/models/json_schema_service/json_schema_service.ts +++ b/x-pack/plugins/ml/server/models/json_schema_service/json_schema_service.ts @@ -119,10 +119,12 @@ export class JsonSchemaService { Fs.readFileSync(Path.resolve(__dirname, 'openapi_source.json'), 'utf8') ); - supportedEndpoints.forEach((e) => { - // need to extract schema in order to keep required components - this.extractSchema(e.path, e.method, schema); - }); + await Promise.all( + supportedEndpoints.map(async (e) => { + // need to extract schema in order to keep required components + await this.extractSchema(e.path, e.method, schema); + }) + ); for (const pathName in schema.paths) { if (!schema.paths.hasOwnProperty(pathName)) continue; diff --git a/x-pack/plugins/ml/server/plugin.ts b/x-pack/plugins/ml/server/plugin.ts index ee36bd7382843..aa42a3e18143c 100644 --- a/x-pack/plugins/ml/server/plugin.ts +++ b/x-pack/plugins/ml/server/plugin.ts @@ -342,10 +342,16 @@ export class MlServerPlugin this.security, this.spacesPlugin !== undefined ); - initializeJobs().finally(() => { - this.setMlReady(); + initializeJobs() + .catch((err) => { + this.log.debug(`Error initializing jobs`, err); + }) + .finally(() => { + this.setMlReady(); + }); + this.savedObjectsSyncService.scheduleSyncTask(plugins.taskManager, coreStart).catch((err) => { + this.log.debug(`Error scheduling saved objects sync task`, err); }); - this.savedObjectsSyncService.scheduleSyncTask(plugins.taskManager, coreStart); }); } diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.ts index 5228eb488b1f7..f166673258848 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/bulk_uploader.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { Observable, Subscription } from 'rxjs'; +import { exhaustMap, type Observable, Subject, type Subscription, takeUntil, timer } from 'rxjs'; import { firstValueFrom } from 'rxjs'; import moment from 'moment'; import type { @@ -67,7 +67,7 @@ export class BulkUploader implements IBulkUploader { private kibanaStatusSubscription?: Subscription; private readonly opsMetrics$: Observable; private kibanaStatus: ServiceStatusLevel | null; - private _timer: NodeJS.Timeout | null; + private readonly stop$ = new Subject(); private readonly _interval: number; private readonly config: MonitoringConfig; @@ -86,7 +86,6 @@ export class BulkUploader implements IBulkUploader { this.opsMetrics$ = opsMetrics$; this.config = config; - this._timer = null; this._interval = interval; this._log = log; @@ -108,15 +107,12 @@ export class BulkUploader implements IBulkUploader { this.kibanaStatus = nextStatus.level; }); - if (this._timer) { - clearInterval(this._timer); - } else { - this._fetchAndUpload(esClient); // initial fetch - } - - this._timer = setInterval(() => { - this._fetchAndUpload(esClient); - }, this._interval); + timer(0, this._interval) + .pipe( + takeUntil(this.stop$), + exhaustMap(() => this._fetchAndUpload(esClient)) + ) + .subscribe(); } /* @@ -125,8 +121,7 @@ export class BulkUploader implements IBulkUploader { * @param {String} logPrefix help give context to the reason for stopping */ public stop(logPrefix?: string) { - if (this._timer) clearInterval(this._timer); - this._timer = null; + this.stop$.next(); this.kibanaStatusSubscription?.unsubscribe(); diff --git a/x-pack/plugins/monitoring/server/plugin.ts b/x-pack/plugins/monitoring/server/plugin.ts index 99cc38e44c0e4..5219c3441b13e 100644 --- a/x-pack/plugins/monitoring/server/plugin.ts +++ b/x-pack/plugins/monitoring/server/plugin.ts @@ -257,7 +257,7 @@ export class MonitoringPlugin stop() { if (this.cluster && this.cluster.close) { - this.cluster.close(); + this.cluster.close().catch(() => {}); } if (this.licenseService && this.licenseService.stop) { this.licenseService.stop(); diff --git a/x-pack/plugins/notifications/server/services/connectors_email_service.test.ts b/x-pack/plugins/notifications/server/services/connectors_email_service.test.ts index 2f0a505ba1f55..b2dc7248945b6 100644 --- a/x-pack/plugins/notifications/server/services/connectors_email_service.test.ts +++ b/x-pack/plugins/notifications/server/services/connectors_email_service.test.ts @@ -21,7 +21,7 @@ describe('sendPlainTextEmail()', () => { }); describe('calls the provided ActionsClient#bulkEnqueueExecution() with the appropriate params', () => { - it(`omits the 'relatedSavedObjects' field if no context is provided`, () => { + it(`omits the 'relatedSavedObjects' field if no context is provided`, async () => { const actionsClient = unsecuredActionsClientMock.create(); actionsClient.bulkEnqueueExecution.mockResolvedValueOnce({ errors: false, @@ -40,7 +40,7 @@ describe('sendPlainTextEmail()', () => { message: 'With some contents inside.', }; - email.sendPlainTextEmail(payload); + await email.sendPlainTextEmail(payload); expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith(REQUESTER_ID, [ @@ -55,7 +55,7 @@ describe('sendPlainTextEmail()', () => { ]); }); - it(`populates the 'relatedSavedObjects' field if context is provided`, () => { + it(`populates the 'relatedSavedObjects' field if context is provided`, async () => { const actionsClient = unsecuredActionsClientMock.create(); actionsClient.bulkEnqueueExecution.mockResolvedValueOnce({ errors: false, @@ -83,7 +83,7 @@ describe('sendPlainTextEmail()', () => { }, }; - email.sendPlainTextEmail(payload); + await email.sendPlainTextEmail(payload); expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith(REQUESTER_ID, [ @@ -168,7 +168,7 @@ describe('sendHTMLEmail()', () => { }); describe('calls the provided ActionsClient#bulkEnqueueExecution() with the appropriate params', () => { - it(`omits the 'relatedSavedObjects' field if no context is provided`, () => { + it(`omits the 'relatedSavedObjects' field if no context is provided`, async () => { const actionsClient = unsecuredActionsClientMock.create(); actionsClient.bulkEnqueueExecution.mockResolvedValueOnce({ errors: false, @@ -188,7 +188,7 @@ describe('sendHTMLEmail()', () => { messageHTML: 'With some contents inside.', }; - email.sendHTMLEmail(payload); + await email.sendHTMLEmail(payload); expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith(REQUESTER_ID, [ @@ -204,7 +204,7 @@ describe('sendHTMLEmail()', () => { ]); }); - it(`populates the 'relatedSavedObjects' field if context is provided`, () => { + it(`populates the 'relatedSavedObjects' field if context is provided`, async () => { const actionsClient = unsecuredActionsClientMock.create(); actionsClient.bulkEnqueueExecution.mockResolvedValueOnce({ errors: false, @@ -233,7 +233,7 @@ describe('sendHTMLEmail()', () => { }, }; - email.sendHTMLEmail(payload); + await email.sendHTMLEmail(payload); expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledTimes(1); expect(actionsClient.bulkEnqueueExecution).toHaveBeenCalledWith(REQUESTER_ID, [ diff --git a/x-pack/plugins/notifications/server/services/licensed_email_service.test.ts b/x-pack/plugins/notifications/server/services/licensed_email_service.test.ts index 0571285a226c9..d24a151863c06 100644 --- a/x-pack/plugins/notifications/server/services/licensed_email_service.test.ts +++ b/x-pack/plugins/notifications/server/services/licensed_email_service.test.ts @@ -66,7 +66,7 @@ describe('LicensedEmailService', () => { const license$ = new Subject(); const email = new LicensedEmailService(emailServiceMock, license$, 'platinum', logger); - email.sendPlainTextEmail(someEmail); + void email.sendPlainTextEmail(someEmail); expect(emailServiceMock.sendPlainTextEmail).not.toHaveBeenCalled(); license$.next(validLicense); @@ -136,7 +136,7 @@ describe('LicensedEmailService', () => { const license$ = new Subject(); const email = new LicensedEmailService(emailServiceMock, license$, 'platinum', logger); - email.sendHTMLEmail(someHTMLEmail); + void email.sendHTMLEmail(someHTMLEmail); expect(emailServiceMock.sendHTMLEmail).not.toHaveBeenCalled(); license$.next(validLicense); diff --git a/x-pack/plugins/observability_solution/apm/server/lib/apm_telemetry/index.ts b/x-pack/plugins/observability_solution/apm/server/lib/apm_telemetry/index.ts index e63502451f04c..5c976c8a499a7 100644 --- a/x-pack/plugins/observability_solution/apm/server/lib/apm_telemetry/index.ts +++ b/x-pack/plugins/observability_solution/apm/server/lib/apm_telemetry/index.ts @@ -110,37 +110,43 @@ export async function createApmTelemetry({ usageCollector.registerCollector(collector); - core.getStartServices().then(async ([_coreStart, pluginsStart]) => { - const { taskManager: taskManagerStart } = pluginsStart as { - taskManager: TaskManagerStartContract; - }; + core + .getStartServices() + .then(async ([_coreStart, pluginsStart]) => { + const { taskManager: taskManagerStart } = pluginsStart as { + taskManager: TaskManagerStartContract; + }; - taskManagerStart.ensureScheduled({ - id: APM_TELEMETRY_TASK_NAME, - taskType: APM_TELEMETRY_TASK_NAME, - schedule: { - interval: '720m', - }, - scope: ['apm'], - params: {}, - state: {}, - }); + await taskManagerStart.ensureScheduled({ + id: APM_TELEMETRY_TASK_NAME, + taskType: APM_TELEMETRY_TASK_NAME, + schedule: { + interval: '720m', + }, + scope: ['apm'], + params: {}, + state: {}, + }); - try { - const currentData = ( - await savedObjectsClient.get(APM_TELEMETRY_SAVED_OBJECT_TYPE, APM_TELEMETRY_SAVED_OBJECT_ID) - ).attributes as { kibanaVersion?: string }; + try { + const currentData = ( + await savedObjectsClient.get( + APM_TELEMETRY_SAVED_OBJECT_TYPE, + APM_TELEMETRY_SAVED_OBJECT_ID + ) + ).attributes as { kibanaVersion?: string }; - if (currentData.kibanaVersion !== kibanaVersion) { - logger.debug( - `Stored telemetry is out of date. Task will run immediately. Stored: ${currentData.kibanaVersion}, expected: ${kibanaVersion}` - ); - await taskManagerStart.runSoon(APM_TELEMETRY_TASK_NAME); - } - } catch (err) { - if (!SavedObjectsErrorHelpers.isNotFoundError(err)) { - logger.warn('Failed to fetch saved telemetry data.'); + if (currentData.kibanaVersion !== kibanaVersion) { + logger.debug( + `Stored telemetry is out of date. Task will run immediately. Stored: ${currentData.kibanaVersion}, expected: ${kibanaVersion}` + ); + await taskManagerStart.runSoon(APM_TELEMETRY_TASK_NAME); + } + } catch (err) { + if (!SavedObjectsErrorHelpers.isNotFoundError(err)) { + logger.warn('Failed to fetch saved telemetry data.'); + } } - } - }); + }) + .catch(() => {}); } diff --git a/x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts b/x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts index 058897dedd32e..43b31c588f422 100644 --- a/x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts +++ b/x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts @@ -69,7 +69,7 @@ describe('APMEventClient', () => { await new Promise((resolve) => { setTimeout(() => { - incomingRequest.on('abort', () => { + void incomingRequest.on('abort', () => { setTimeout(() => { resolve(undefined); }, 100); diff --git a/x-pack/plugins/observability_solution/apm/server/plugin.ts b/x-pack/plugins/observability_solution/apm/server/plugin.ts index 8c2bbb8695452..415fd90af7daa 100644 --- a/x-pack/plugins/observability_solution/apm/server/plugin.ts +++ b/x-pack/plugins/observability_solution/apm/server/plugin.ts @@ -76,7 +76,7 @@ export class APMPlugin logger: this.logger, kibanaVersion: this.initContext.env.packageInfo.version, isProd: this.initContext.env.mode.prod, - }); + }).catch(() => {}); } plugins.features.registerKibanaFeature(APM_FEATURE); @@ -127,16 +127,18 @@ export class APMPlugin if (currentConfig.serverlessOnboarding && plugins.customIntegrations) { plugins.customIntegrations?.registerCustomIntegration(apmTutorialCustomIntegration); } else { - apmIndicesPromise.then((apmIndices) => { - plugins.home?.tutorials.registerTutorial( - tutorialProvider({ - apmConfig: currentConfig, - apmIndices, - cloud: plugins.cloud, - isFleetPluginEnabled: !isEmpty(resourcePlugins.fleet), - }) - ); - }); + apmIndicesPromise + .then((apmIndices) => { + plugins.home?.tutorials.registerTutorial( + tutorialProvider({ + apmConfig: currentConfig, + apmIndices, + cloud: plugins.cloud, + isFleetPluginEnabled: !isEmpty(resourcePlugins.fleet), + }) + ); + }) + .catch(() => {}); } const telemetryUsageCounter = diff --git a/x-pack/plugins/observability_solution/apm/server/routes/settings/agent_configuration/route.ts b/x-pack/plugins/observability_solution/apm/server/routes/settings/agent_configuration/route.ts index 800dbb4455103..08bc47c44822a 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/settings/agent_configuration/route.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/settings/agent_configuration/route.ts @@ -265,7 +265,7 @@ const agentConfigurationSearchRoute = createApmServerRoute({ ); if (willMarkAsApplied) { - markAppliedByAgent({ + await markAppliedByAgent({ id: configuration._id, body: configuration._source, internalESClient, diff --git a/x-pack/plugins/observability_solution/apm/server/routes/settings/custom_link/create_or_update_custom_link.test.ts b/x-pack/plugins/observability_solution/apm/server/routes/settings/custom_link/create_or_update_custom_link.test.ts index 97f75f2092710..3b5bf5b3f15a6 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/settings/custom_link/create_or_update_custom_link.test.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/settings/custom_link/create_or_update_custom_link.test.ts @@ -33,8 +33,8 @@ describe('Create or Update Custom link', () => { mockNow(1570737000000); }); - it('creates a new custom link', () => { - createOrUpdateCustomLink({ + it('creates a new custom link', async () => { + await createOrUpdateCustomLink({ customLink, internalESClient: mockInternalESClient, }); @@ -50,8 +50,8 @@ describe('Create or Update Custom link', () => { }, }); }); - it('update a new custom link', () => { - createOrUpdateCustomLink({ + it('update a new custom link', async () => { + await createOrUpdateCustomLink({ customLinkId: 'bar', customLink, internalESClient: mockInternalESClient, diff --git a/x-pack/plugins/observability_solution/apm_data_access/server/saved_objects/migrations/migrate_legacy_apm_indices_to_space_aware.test.ts b/x-pack/plugins/observability_solution/apm_data_access/server/saved_objects/migrations/migrate_legacy_apm_indices_to_space_aware.test.ts index 8b87b52dee166..9b6e34dac783a 100644 --- a/x-pack/plugins/observability_solution/apm_data_access/server/saved_objects/migrations/migrate_legacy_apm_indices_to_space_aware.test.ts +++ b/x-pack/plugins/observability_solution/apm_data_access/server/saved_objects/migrations/migrate_legacy_apm_indices_to_space_aware.test.ts @@ -35,8 +35,8 @@ describe('migrateLegacyAPMIndicesToSpaceAware', () => { }, } as unknown as CoreStart; - it('does not save any new saved object', () => { - migrateLegacyAPMIndicesToSpaceAware({ + it('does not save any new saved object', async () => { + await migrateLegacyAPMIndicesToSpaceAware({ coreStart: core, logger: loggerMock, }); diff --git a/x-pack/plugins/observability_solution/asset_manager/server/plugin.ts b/x-pack/plugins/observability_solution/asset_manager/server/plugin.ts index 6ea93a4302f49..73b2cbe87c138 100644 --- a/x-pack/plugins/observability_solution/asset_manager/server/plugin.ts +++ b/x-pack/plugins/observability_solution/asset_manager/server/plugin.ts @@ -80,7 +80,7 @@ export class AssetManagerServerPlugin esClient: core.elasticsearch.client.asInternalUser, template: assetsIndexTemplateConfig, logger: this.logger, - }); + }).catch(() => {}); // it shouldn't reject, but just in case return {}; } diff --git a/x-pack/plugins/observability_solution/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_rule_type.ts b/x-pack/plugins/observability_solution/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_rule_type.ts index d1fbef7a7095e..b3ba3c5b184a9 100644 --- a/x-pack/plugins/observability_solution/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_rule_type.ts +++ b/x-pack/plugins/observability_solution/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_rule_type.ts @@ -82,7 +82,7 @@ const groupActionVariableDescription = i18n.translate( } ); -export async function registerInventoryThresholdRuleType( +export function registerInventoryThresholdRuleType( alertingPlugin: PluginSetupContract, libs: InfraBackendLibs, { featureFlags }: InfraConfig diff --git a/x-pack/plugins/observability_solution/infra/server/lib/alerting/log_threshold/register_log_threshold_rule_type.ts b/x-pack/plugins/observability_solution/infra/server/lib/alerting/log_threshold/register_log_threshold_rule_type.ts index f16e7dfd284d2..fa90cc6bf50fd 100644 --- a/x-pack/plugins/observability_solution/infra/server/lib/alerting/log_threshold/register_log_threshold_rule_type.ts +++ b/x-pack/plugins/observability_solution/infra/server/lib/alerting/log_threshold/register_log_threshold_rule_type.ts @@ -102,7 +102,7 @@ const viewInAppUrlActionVariableDescription = i18n.translate( } ); -export async function registerLogThresholdRuleType( +export function registerLogThresholdRuleType( alertingPlugin: PluginSetupContract, libs: InfraBackendLibs, { featureFlags }: InfraConfig diff --git a/x-pack/plugins/observability_solution/infra/server/lib/alerting/metric_threshold/register_metric_threshold_rule_type.ts b/x-pack/plugins/observability_solution/infra/server/lib/alerting/metric_threshold/register_metric_threshold_rule_type.ts index e7ea693a0e74d..1adcd58f42592 100644 --- a/x-pack/plugins/observability_solution/infra/server/lib/alerting/metric_threshold/register_metric_threshold_rule_type.ts +++ b/x-pack/plugins/observability_solution/infra/server/lib/alerting/metric_threshold/register_metric_threshold_rule_type.ts @@ -55,7 +55,7 @@ export type MetricThresholdAlertType = Omit & { ActionGroupIdsOf: MetricThresholdAllowedActionGroups; }; -export async function registerMetricThresholdRuleType( +export function registerMetricThresholdRuleType( alertingPlugin: PluginSetupContract, libs: InfraBackendLibs, { featureFlags }: InfraConfig diff --git a/x-pack/plugins/observability_solution/logs_shared/server/services/log_entries/log_entries_service.ts b/x-pack/plugins/observability_solution/logs_shared/server/services/log_entries/log_entries_service.ts index b9270f5ab38ae..61810c47ff8d2 100644 --- a/x-pack/plugins/observability_solution/logs_shared/server/services/log_entries/log_entries_service.ts +++ b/x-pack/plugins/observability_solution/logs_shared/server/services/log_entries/log_entries_service.ts @@ -21,7 +21,7 @@ export class LogEntriesService { core: CoreSetup, setupDeps: LogEntriesServiceSetupDeps ) { - core.getStartServices().then(([, startDeps, selfStartDeps]) => { + void core.getStartServices().then(([, startDeps, selfStartDeps]) => { setupDeps.data.search.registerSearchStrategy( LOG_ENTRIES_SEARCH_STRATEGY, logEntriesSearchStrategyProvider({ ...setupDeps, ...startDeps, ...selfStartDeps }) diff --git a/x-pack/plugins/observability_solution/observability/server/plugin.ts b/x-pack/plugins/observability_solution/observability/server/plugin.ts index 7b2f36d27fe4a..a9ae78ee146ae 100644 --- a/x-pack/plugins/observability_solution/observability/server/plugin.ts +++ b/x-pack/plugins/observability_solution/observability/server/plugin.ts @@ -282,7 +282,7 @@ export class ObservabilityPlugin implements Plugin { logsExplorerLocator, }); - core.getStartServices().then(([coreStart, pluginStart]) => { + void core.getStartServices().then(([coreStart, pluginStart]) => { registerRoutes({ core, config, diff --git a/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/client/adapters/bedrock/process_bedrock_stream.ts b/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/client/adapters/bedrock/process_bedrock_stream.ts index 969bc5add78b1..0f520102aac2d 100644 --- a/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/client/adapters/bedrock/process_bedrock_stream.ts +++ b/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/client/adapters/bedrock/process_bedrock_stream.ts @@ -74,7 +74,7 @@ export function processBedrockStream() { subscriber.error(err); }, complete: () => { - nextPromise.then(() => subscriber.complete()); + nextPromise.then(() => subscriber.complete()).catch(() => {}); }, }); }); diff --git a/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/client/index.test.ts b/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/client/index.test.ts index e22f63cf92eb2..7bd31f0ef7689 100644 --- a/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/client/index.test.ts +++ b/x-pack/plugins/observability_solution/observability_ai_assistant/server/service/client/index.test.ts @@ -236,7 +236,8 @@ describe('Observability AI Assistant client', () => { status: 'ok', data: titleLlmSimulator.stream, }); - }); + }) + .catch(reject); }; titleLlmPromiseReject = (error: Error) => { reject(error); diff --git a/x-pack/plugins/observability_solution/profiling/server/plugin.ts b/x-pack/plugins/observability_solution/profiling/server/plugin.ts index 5bb7cfe978cc0..27fbc4f958da1 100644 --- a/x-pack/plugins/observability_solution/profiling/server/plugin.ts +++ b/x-pack/plugins/observability_solution/profiling/server/plugin.ts @@ -46,41 +46,44 @@ export class ProfilingPlugin PROFILING_SERVER_FEATURE_ID ); - core.getStartServices().then(([coreStart, depsStart]) => { - const profilingSpecificEsClient = config.elasticsearch - ? coreStart.elasticsearch.createClient('profiling', { - hosts: [config.elasticsearch.hosts], - username: config.elasticsearch.username, - password: config.elasticsearch.password, - }) - : undefined; + core + .getStartServices() + .then(([coreStart, depsStart]) => { + const profilingSpecificEsClient = config.elasticsearch + ? coreStart.elasticsearch.createClient('profiling', { + hosts: [config.elasticsearch.hosts], + username: config.elasticsearch.username, + password: config.elasticsearch.password, + }) + : undefined; - registerRoutes({ - router, - logger: this.logger!, - dependencies: { - start: depsStart, - setup: deps, - config, - stackVersion, - telemetryUsageCounter, - }, - services: { - createProfilingEsClient: ({ - request, - esClient: defaultEsClient, - useDefaultAuth = false, - }) => { - const esClient = - profilingSpecificEsClient && !useDefaultAuth - ? profilingSpecificEsClient.asScoped(request).asInternalUser - : defaultEsClient; + registerRoutes({ + router, + logger: this.logger!, + dependencies: { + start: depsStart, + setup: deps, + config, + stackVersion, + telemetryUsageCounter, + }, + services: { + createProfilingEsClient: ({ + request, + esClient: defaultEsClient, + useDefaultAuth = false, + }) => { + const esClient = + profilingSpecificEsClient && !useDefaultAuth + ? profilingSpecificEsClient.asScoped(request).asInternalUser + : defaultEsClient; - return createProfilingEsClient({ request, esClient }); + return createProfilingEsClient({ request, esClient }); + }, }, - }, - }); - }); + }); + }) + .catch(() => {}); return {}; } diff --git a/x-pack/plugins/observability_solution/slo/server/plugin.ts b/x-pack/plugins/observability_solution/slo/server/plugin.ts index 668d7cc6a51be..6fe07b89bf342 100644 --- a/x-pack/plugins/observability_solution/slo/server/plugin.ts +++ b/x-pack/plugins/observability_solution/slo/server/plugin.ts @@ -29,7 +29,6 @@ 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 { ServerlessPluginStart } from '@kbn/serverless/server'; import { registerSloUsageCollector } from './lib/collectors/register'; import { SloOrphanSummaryCleanupTask } from './services/tasks/orphan_summary_cleanup_task'; import { slo, SO_SLO_TYPE } from './saved_objects'; @@ -57,7 +56,6 @@ export interface PluginStart { alerting: PluginStartContract; taskManager: TaskManagerStartContract; spaces?: SpacesPluginStart; - serverless: ServerlessPluginStart; } const sloRuleTypes = [SLO_BURN_RATE_RULE_TYPE_ID]; @@ -138,32 +136,42 @@ export class SloPlugin implements Plugin { registerSloUsageCollector(plugins.usageCollection); - core.getStartServices().then(([coreStart, pluginStart]) => { - registerRoutes({ - core, - config, - dependencies: { - pluginsSetup: { - ...plugins, - core, - }, - spaces: pluginStart.spaces, - ruleDataService, - getRulesClientWithRequest: pluginStart.alerting.getRulesClientWithRequest, + registerRoutes({ + core, + config, + dependencies: { + pluginsSetup: { + ...plugins, + core, }, - logger: this.logger, - repository: getSloServerRouteRepository({ - isServerless: !!pluginStart.serverless, - }), - }); - - const esInternalClient = coreStart.elasticsearch.client.asInternalUser; - - const sloResourceInstaller = new DefaultResourceInstaller(esInternalClient, this.logger); - const sloInstaller = new DefaultSLOInstaller(sloResourceInstaller, this.logger); - sloInstaller.install(); + getSpacesStart: async () => { + const [, pluginStart] = await core.getStartServices(); + return pluginStart.spaces; + }, + ruleDataService, + getRulesClientWithRequest: async (request) => { + const [, pluginStart] = await core.getStartServices(); + return pluginStart.alerting.getRulesClientWithRequest(request); + }, + }, + logger: this.logger, + repository: getSloServerRouteRepository({ + isServerless: this.initContext.env.packageInfo.buildFlavor === 'serverless', + }), }); + core + .getStartServices() + .then(async ([coreStart, pluginStart]) => { + const esInternalClient = coreStart.elasticsearch.client.asInternalUser; + const sloResourceInstaller = new DefaultResourceInstaller(esInternalClient, this.logger); + const sloInstaller = new DefaultSLOInstaller(sloResourceInstaller, this.logger); + await sloInstaller.install(); + }) + .catch((error) => { + this.logger.error(`Failed to install the default SLOs: ${error}`); + }); + this.sloOrphanCleanupTask = new SloOrphanSummaryCleanupTask( plugins.taskManager, this.logger, @@ -175,7 +183,9 @@ export class SloPlugin implements Plugin { const internalSoClient = new SavedObjectsClient(core.savedObjects.createInternalRepository()); const internalEsClient = core.elasticsearch.client.asInternalUser; - this.sloOrphanCleanupTask?.start(plugins.taskManager, internalSoClient, internalEsClient); + this.sloOrphanCleanupTask + ?.start(plugins.taskManager, internalSoClient, internalEsClient) + .catch(() => {}); } public stop() {} 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 66f255a2397b7..83f5ce796e70d 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 @@ -34,9 +34,9 @@ export interface RegisterRoutesDependencies { pluginsSetup: { core: CoreSetup; }; - spaces?: SpacesPluginStart; + getSpacesStart: () => Promise; ruleDataService: RuleDataPluginService; - getRulesClientWithRequest: (request: KibanaRequest) => RulesClientApi; + getRulesClientWithRequest: (request: KibanaRequest) => Promise; } export function registerRoutes({ config, repository, core, logger, dependencies }: RegisterRoutes) { 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 1853d09c81f54..d71a65e95013a 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 @@ -98,8 +98,8 @@ const createSLORoute = createSloServerRoute({ handler: async ({ context, params, logger, dependencies, request }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const basePath = dependencies.pluginsSetup.core.http.basePath; @@ -143,8 +143,8 @@ const inspectSLORoute = createSloServerRoute({ handler: async ({ context, params, logger, dependencies, request }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const basePath = dependencies.pluginsSetup.core.http.basePath; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const soClient = (await context.core).savedObjects.client; @@ -185,8 +185,8 @@ const updateSLORoute = createSloServerRoute({ handler: async ({ context, request, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const basePath = dependencies.pluginsSetup.core.http.basePath; const esClient = (await context.core).elasticsearch.client.asCurrentUser; @@ -231,12 +231,12 @@ const deleteSLORoute = createSloServerRoute({ handler: async ({ request, context, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const soClient = (await context.core).savedObjects.client; - const rulesClient = dependencies.getRulesClientWithRequest(request); + const rulesClient = await dependencies.getRulesClientWithRequest(request); const repository = new KibanaSavedObjectsSLORepository(soClient, logger); const transformManager = new DefaultTransformManager( @@ -274,8 +274,8 @@ const getSLORoute = createSloServerRoute({ handler: async ({ request, context, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; @@ -298,8 +298,8 @@ const enableSLORoute = createSloServerRoute({ handler: async ({ request, context, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; @@ -335,8 +335,8 @@ const disableSLORoute = createSloServerRoute({ handler: async ({ request, context, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; @@ -372,8 +372,8 @@ const resetSLORoute = createSloServerRoute({ handler: async ({ context, request, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const basePath = dependencies.pluginsSetup.core.http.basePath; @@ -417,8 +417,8 @@ const findSLORoute = createSloServerRoute({ handler: async ({ context, request, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const soClient = (await context.core).savedObjects.client; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const repository = new KibanaSavedObjectsSLORepository(soClient, logger); @@ -439,8 +439,8 @@ const findSLOGroupsRoute = createSloServerRoute({ params: findSLOGroupsParamsSchema, handler: async ({ context, request, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService.getActiveSpace(request))?.id ?? 'default'; const soClient = (await context.core).savedObjects.client; const coreContext = context.core; const esClient = (await coreContext).elasticsearch.client.asCurrentUser; @@ -592,8 +592,8 @@ const getSloBurnRates = createSloServerRoute({ handler: async ({ request, context, params, logger, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService.getActiveSpace(request))?.id ?? 'default'; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const soClient = (await context.core).savedObjects.client; @@ -624,8 +624,8 @@ const getPreviewData = createSloServerRoute({ handler: async ({ request, context, params, dependencies }) => { await assertPlatinumLicense(context); - const spaceId = - (await dependencies.spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; + const spaces = await dependencies.getSpacesStart(); + const spaceId = (await spaces?.spacesService?.getActiveSpace(request))?.id ?? 'default'; const esClient = (await context.core).elasticsearch.client.asCurrentUser; const service = new GetPreviewData(esClient, spaceId); 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 1d9a968dc1ff4..bdbb955050358 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 @@ -232,7 +232,7 @@ export class SloOrphanSummaryCleanupTask { } if (this.config.sloOrphanSummaryCleanUpTaskEnabled) { - this.taskManager.ensureScheduled({ + await this.taskManager.ensureScheduled({ id: this.taskId, taskType: TASK_TYPE, schedule: { @@ -243,7 +243,7 @@ export class SloOrphanSummaryCleanupTask { params: {}, }); } else { - this.taskManager.removeIfExists(this.taskId); + await this.taskManager.removeIfExists(this.taskId); } } } diff --git a/x-pack/plugins/observability_solution/synthetics/server/lib.ts b/x-pack/plugins/observability_solution/synthetics/server/lib.ts index 6ee70f5282e83..78d88ff6bf51b 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/lib.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/lib.ts @@ -65,7 +65,7 @@ export class UptimeEsClient { this.heartbeatIndices = heartbeatIndices; this.isDev = isDev; this.inspectableEsQueries = []; - this.getInspectEnabled(); + this.getInspectEnabled().catch(() => {}); } async initSettings() { @@ -176,15 +176,14 @@ export class UptimeEsClient { return {}; } async getInspectEnabled() { - if (this.isInspectorEnabled !== undefined) { - return this.isInspectorEnabled; - } - if (!this.uiSettings) { return false; } - this.isInspectorEnabled = this.uiSettings.client.get(enableInspectEsQueries); + if (this.isInspectorEnabled === undefined) { + this.isInspectorEnabled = this.uiSettings.client.get(enableInspectEsQueries); + } + return this.isInspectorEnabled; } async getIndices() { diff --git a/x-pack/plugins/observability_solution/synthetics/server/plugin.ts b/x-pack/plugins/observability_solution/synthetics/server/plugin.ts index 76ac2afcf102b..91331dd124cf1 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/plugin.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/plugin.ts @@ -79,7 +79,7 @@ export class Plugin implements PluginType { this.syntheticsService = new SyntheticsService(this.server); - this.syntheticsService.setup(plugins.taskManager); + this.syntheticsService.setup(plugins.taskManager).catch(() => {}); this.syntheticsMonitorClient = new SyntheticsMonitorClient(this.syntheticsService, this.server); @@ -112,7 +112,7 @@ export class Plugin implements PluginType { this.syntheticsService?.start(pluginsStart.taskManager); - this.telemetryEventsSender.start(pluginsStart.telemetry, coreStart); + this.telemetryEventsSender.start(pluginsStart.telemetry, coreStart).catch(() => {}); } public stop() {} diff --git a/x-pack/plugins/observability_solution/synthetics/server/routes/monitor_cruds/add_monitor/add_monitor_api.ts b/x-pack/plugins/observability_solution/synthetics/server/routes/monitor_cruds/add_monitor/add_monitor_api.ts index 7093b83dab82f..cd105bd0fd831 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/routes/monitor_cruds/add_monitor/add_monitor_api.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/routes/monitor_cruds/add_monitor/add_monitor_api.ts @@ -259,9 +259,14 @@ export class AddEditMonitorAPI { try { // we do this async, so we don't block the user, error handling will be done on the UI via separate api const defaultAlertService = new DefaultAlertService(context, server, savedObjectsClient); - defaultAlertService.setupDefaultAlerts().then(() => { - server.logger.debug(`Successfully created default alert for monitor: ${name}`); - }); + defaultAlertService + .setupDefaultAlerts() + .then(() => { + server.logger.debug(`Successfully created default alert for monitor: ${name}`); + }) + .catch((error) => { + server.logger.error(`Error creating default alert: ${error} for monitor: ${name}`); + }); } catch (e) { server.logger.error(`Error creating default alert: ${e} for monitor: ${name}`); } diff --git a/x-pack/plugins/observability_solution/synthetics/server/saved_objects/synthetics_monitor/get_all_monitors.ts b/x-pack/plugins/observability_solution/synthetics/server/saved_objects/synthetics_monitor/get_all_monitors.ts index b8e9a08bf3dd1..c742bf26176ad 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/saved_objects/synthetics_monitor/get_all_monitors.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/saved_objects/synthetics_monitor/get_all_monitors.ts @@ -50,8 +50,7 @@ export const getAllMonitors = async ({ hits.push(...result.saved_objects); } - // no need to wait for it - finder.close(); + finder.close().catch(() => {}); return hits; }; diff --git a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/private_location/synthetics_private_location.ts b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/private_location/synthetics_private_location.ts index 418fbde0d31db..29b65def487dc 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/private_location/synthetics_private_location.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/private_location/synthetics_private_location.ts @@ -201,7 +201,7 @@ export class SyntheticsPrivateLocation { const result = await this.createPolicyBulk(newPolicies); if (result?.created && result?.created?.length > 0 && testRunId) { // ignore await here, we don't want to wait for this to finish - scheduleCleanUpTask(this.server); + void scheduleCleanUpTask(this.server); } return result; } catch (e) { diff --git a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/project_monitor/project_monitor_formatter.ts b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/project_monitor/project_monitor_formatter.ts index 3707b0b9be746..108facf7076a1 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/project_monitor/project_monitor_formatter.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/project_monitor/project_monitor_formatter.ts @@ -258,8 +258,7 @@ export class ProjectMonitorFormatter { ); } - // no need to wait for it - finder.close(); + finder.close().catch(() => {}); return hits; }; diff --git a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_monitor/synthetics_monitor_client.ts b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_monitor/synthetics_monitor_client.ts index f3b006f3bd241..e9fbe8f0ef3b4 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_monitor/synthetics_monitor_client.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_monitor/synthetics_monitor_client.ts @@ -354,8 +354,7 @@ export class SyntheticsMonitorClient { }); } - // no need to wait here - finder.close(); + finder.close().catch(() => {}); return monitors; } diff --git a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_service.test.ts b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_service.test.ts index 60bc4ab9007e0..e7fcff93c8018 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_service.test.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_service.test.ts @@ -154,9 +154,12 @@ describe('SyntheticsService', () => { it('setup properly', async () => { const service = new SyntheticsService(serverMock); - service.setup(taskManagerSetup); expect(service.isAllowed).toEqual(false); + + await service.setup(taskManagerSetup); + + expect(service.isAllowed).toEqual(true); expect(service.locations).toEqual([]); expect(service.signupUrl).toEqual(null); }); diff --git a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_service.ts b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_service.ts index fd37aa678ce63..a9e36289b1698 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_service.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/synthetics_service.ts @@ -100,9 +100,9 @@ export class SyntheticsService { public start(taskManager: TaskManagerStartContract) { if (this.config?.manifestUrl) { - this.scheduleSyncTask(taskManager); + void this.scheduleSyncTask(taskManager); } - this.setupIndexTemplates(); + void this.setupIndexTemplates(); } public async setupIndexTemplates() { @@ -178,7 +178,7 @@ export class SyntheticsService { service.signupUrl = signupUrl; if (service.isAllowed && service.config.manifestUrl) { - service.setupIndexTemplates(); + void service.setupIndexTemplates(); await service.pushConfigs(); } } catch (e) { @@ -588,7 +588,7 @@ export class SyntheticsService { } // no need to wait here - finder.close(); + finder.close().catch(() => {}); if (paramsBySpace[ALL_SPACES_ID]) { Object.keys(paramsBySpace).forEach((space) => { diff --git a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/utils/mocks.ts b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/utils/mocks.ts index b9d6b54961f59..796e92ddbc5b2 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/utils/mocks.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/synthetics_service/utils/mocks.ts @@ -24,7 +24,7 @@ export const mockEncryptedSO = ({ createPointInTimeFinderDecryptedAsInternalUser: jest .fn() .mockImplementation(({ perPage, type: soType }) => ({ - close: jest.fn(), + close: jest.fn(async () => {}), find: jest.fn().mockReturnValue({ async *[Symbol.asyncIterator]() { if (soType === syntheticsParamType) { diff --git a/x-pack/plugins/observability_solution/synthetics/server/telemetry/sender.test.ts b/x-pack/plugins/observability_solution/synthetics/server/telemetry/sender.test.ts index ab599ae0d0ea8..91f859545600b 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/telemetry/sender.test.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/telemetry/sender.test.ts @@ -57,7 +57,7 @@ describe('TelemetryEventsSender', () => { revision: 1, }; - beforeEach(() => { + beforeEach(async () => { logger = loggingSystemMock.createLogger(); sender = new TelemetryEventsSender(logger); sender['fetchLicenseInfo'] = jest.fn(async () => { @@ -73,7 +73,7 @@ describe('TelemetryEventsSender', () => { }, } as InfoResponse; }); - sender.start(undefined, { + await sender.start(undefined, { elasticsearch: { client: { asInternalUser: { info: jest.fn(async () => ({})) } } }, } as any); }); diff --git a/x-pack/plugins/observability_solution/synthetics/server/telemetry/sender.ts b/x-pack/plugins/observability_solution/synthetics/server/telemetry/sender.ts index 610f43aa9cfd9..e495181781fe0 100644 --- a/x-pack/plugins/observability_solution/synthetics/server/telemetry/sender.ts +++ b/x-pack/plugins/observability_solution/synthetics/server/telemetry/sender.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { exhaustMap, Subject, takeUntil, timer } from 'rxjs'; import type { CoreStart, ElasticsearchClient, Logger } from '@kbn/core/server'; import type { TelemetryPluginStart, TelemetryPluginSetup } from '@kbn/telemetry-plugin/server'; @@ -26,10 +27,10 @@ export class TelemetryEventsSender { private readonly initialCheckDelayMs = 10 * 1000; private readonly checkIntervalMs = 30 * 1000; private readonly logger: Logger; + private readonly stop$ = new Subject(); private telemetryStart?: TelemetryPluginStart; private telemetrySetup?: TelemetryPluginSetup; - private intervalId?: NodeJS.Timeout; private isSending = false; private queuesPerChannel: { [channel: string]: TelemetryQueue } = {}; private isOptedIn?: boolean = true; // Assume true until the first check @@ -52,16 +53,16 @@ export class TelemetryEventsSender { this.licenseInfo = await this.fetchLicenseInfo(); this.logger.debug(`Starting local task`); - setTimeout(() => { - this.sendIfDue(); - this.intervalId = setInterval(() => this.sendIfDue(), this.checkIntervalMs); - }, this.initialCheckDelayMs); + timer(this.initialCheckDelayMs, this.checkIntervalMs) + .pipe( + takeUntil(this.stop$), + exhaustMap(() => this.sendIfDue()) + ) + .subscribe(); } public stop() { - if (this.intervalId) { - clearInterval(this.intervalId); - } + this.stop$.next(); } public queueTelemetryEvents( diff --git a/x-pack/plugins/observability_solution/uptime/server/legacy_uptime/lib/lib.ts b/x-pack/plugins/observability_solution/uptime/server/legacy_uptime/lib/lib.ts index 15f2530667d7d..5b1326bf7a065 100644 --- a/x-pack/plugins/observability_solution/uptime/server/legacy_uptime/lib/lib.ts +++ b/x-pack/plugins/observability_solution/uptime/server/legacy_uptime/lib/lib.ts @@ -80,7 +80,7 @@ export class UptimeEsClient { this.heartbeatIndices = heartbeatIndices; this.isDev = isDev; this.inspectableEsQueries = []; - this.getInspectEnabled(); + this.getInspectEnabled().catch(() => {}); } async initSettings() { diff --git a/x-pack/plugins/osquery/server/create_transforms/create_transforms.ts b/x-pack/plugins/osquery/server/create_transforms/create_transforms.ts index b3c1b74967721..b365449c75121 100644 --- a/x-pack/plugins/osquery/server/create_transforms/create_transforms.ts +++ b/x-pack/plugins/osquery/server/create_transforms/create_transforms.ts @@ -21,12 +21,12 @@ export const initializeTransform = async ( esClient: ElasticsearchClient, transform: TransformPutTransformRequest, logger: Logger -) => - createTransformIfNotExists(esClient, transform, logger).then((succeeded) => { - if (succeeded) { - startTransformIfNotStarted(esClient, transform.transform_id, logger); - } - }); +) => { + const succeeded = await createTransformIfNotExists(esClient, transform, logger); + if (succeeded) { + await startTransformIfNotStarted(esClient, transform.transform_id, logger); + } +}; /** * Checks if a transform exists, And if not creates it diff --git a/x-pack/plugins/osquery/server/lib/telemetry/receiver.ts b/x-pack/plugins/osquery/server/lib/telemetry/receiver.ts index 0053cd9523135..4749d36522569 100644 --- a/x-pack/plugins/osquery/server/lib/telemetry/receiver.ts +++ b/x-pack/plugins/osquery/server/lib/telemetry/receiver.ts @@ -40,7 +40,7 @@ export class TelemetryReceiver { this.logger = logger.get('telemetry_events'); } - public async start(core: CoreStart, osqueryContextService?: OsqueryAppContextService) { + public start(core: CoreStart, osqueryContextService?: OsqueryAppContextService) { this.agentClient = osqueryContextService?.getAgentService()?.asInternalUser; this.agentPolicyService = osqueryContextService?.getAgentPolicyService(); this.packageService = osqueryContextService?.getPackageService(); diff --git a/x-pack/plugins/osquery/server/lib/update_global_packs.ts b/x-pack/plugins/osquery/server/lib/update_global_packs.ts index 8a3e048532202..2cf48bf59013c 100644 --- a/x-pack/plugins/osquery/server/lib/update_global_packs.ts +++ b/x-pack/plugins/osquery/server/lib/update_global_packs.ts @@ -46,7 +46,7 @@ export const updateGlobalPacksCreateCallback = async ( if (packsContainingShardForPolicy.length) { await Promise.all( - map(packsContainingShardForPolicy, (pack) => { + map(packsContainingShardForPolicy, (pack) => packsClient.update( packSavedObjectType, pack.saved_object_id, @@ -61,8 +61,8 @@ export const updateGlobalPacksCreateCallback = async ( }, ], } - ); - }) + ) + ) ); return produce(packagePolicy, (draft) => { diff --git a/x-pack/plugins/osquery/server/plugin.ts b/x-pack/plugins/osquery/server/plugin.ts index 117feb69fa4b9..9a0772708d133 100644 --- a/x-pack/plugins/osquery/server/plugin.ts +++ b/x-pack/plugins/osquery/server/plugin.ts @@ -80,15 +80,20 @@ export class OsqueryPlugin implements Plugin { - const osquerySearchStrategy = osquerySearchStrategyProvider( - depsStart.data, - elasticsearch.client - ); - - plugins.data.search.registerSearchStrategy('osquerySearchStrategy', osquerySearchStrategy); - defineRoutes(router, osqueryContext); - }); + core + .getStartServices() + .then(([{ elasticsearch }, depsStart]) => { + const osquerySearchStrategy = osquerySearchStrategyProvider( + depsStart.data, + elasticsearch.client + ); + + plugins.data.search.registerSearchStrategy('osquerySearchStrategy', osquerySearchStrategy); + defineRoutes(router, osqueryContext); + }) + .catch(() => { + // it shouldn't reject, but just in case + }); this.telemetryEventsSender.setup(this.telemetryReceiver, plugins.taskManager, core.analytics); @@ -117,64 +122,71 @@ export class OsqueryPlugin implements Plugin { - const packageInfo = await plugins.fleet?.packageService.asInternalUser.getInstallation( - OSQUERY_INTEGRATION_NAME - ); - const client = new SavedObjectsClient(core.savedObjects.createInternalRepository()); - - const esClient = core.elasticsearch.client.asInternalUser; - const dataViewsService = await plugins.dataViews.dataViewsServiceFactory( - client, - esClient, - undefined, - true - ); - - // If package is installed we want to make sure all needed assets are installed - if (packageInfo) { - await this.initialize(core, dataViewsService); - } - - // Upgrade integration into 1.6.0 and rollover if found 'generic' dataset - we do not want to wait for it - upgradeIntegration({ packageInfo, client, esClient, logger: this.logger }); - - if (registerIngestCallback) { - registerIngestCallback( - 'packagePolicyCreate', - async (newPackagePolicy: NewPackagePolicy): Promise => { - if (newPackagePolicy.package?.name === OSQUERY_INTEGRATION_NAME) { - await this.initialize(core, dataViewsService); - - const allPacks = await client - .find({ - type: packSavedObjectType, - }) - .then((data) => ({ - ...data, - saved_objects: data.saved_objects.map((pack) => ({ - ...pack.attributes, - saved_object_id: pack.id, - })), - })); - - if (allPacks.saved_objects) { - return updateGlobalPacksCreateCallback( - newPackagePolicy, - client, - allPacks.saved_objects, - this.osqueryAppContextService - ); - } - } - - return newPackagePolicy; - } + plugins.fleet + ?.fleetSetupCompleted() + .then(async () => { + const packageInfo = await plugins.fleet?.packageService.asInternalUser.getInstallation( + OSQUERY_INTEGRATION_NAME + ); + const client = new SavedObjectsClient(core.savedObjects.createInternalRepository()); + + const esClient = core.elasticsearch.client.asInternalUser; + const dataViewsService = await plugins.dataViews.dataViewsServiceFactory( + client, + esClient, + undefined, + true ); - registerIngestCallback('packagePolicyPostDelete', getPackagePolicyDeleteCallback(client)); - } - }); + // If package is installed we want to make sure all needed assets are installed + if (packageInfo) { + await this.initialize(core, dataViewsService); + } + + // Upgrade integration into 1.6.0 and rollover if found 'generic' dataset - we do not want to wait for it + upgradeIntegration({ packageInfo, client, esClient, logger: this.logger }).catch(() => { + // we do not want to wait for it + }); + + if (registerIngestCallback) { + registerIngestCallback( + 'packagePolicyCreate', + async (newPackagePolicy: NewPackagePolicy): Promise => { + if (newPackagePolicy.package?.name === OSQUERY_INTEGRATION_NAME) { + await this.initialize(core, dataViewsService); + + const allPacks = await client + .find({ + type: packSavedObjectType, + }) + .then((data) => ({ + ...data, + saved_objects: data.saved_objects.map((pack) => ({ + ...pack.attributes, + saved_object_id: pack.id, + })), + })); + + if (allPacks.saved_objects) { + return updateGlobalPacksCreateCallback( + newPackagePolicy, + client, + allPacks.saved_objects, + this.osqueryAppContextService + ); + } + } + + return newPackagePolicy; + } + ); + + registerIngestCallback('packagePolicyPostDelete', getPackagePolicyDeleteCallback(client)); + } + }) + .catch(() => { + // it shouldn't reject, but just in case + }); return {}; } diff --git a/x-pack/plugins/reporting/server/lib/store/store.test.ts b/x-pack/plugins/reporting/server/lib/store/store.test.ts index eef04ad477c45..946ceb4f105b0 100644 --- a/x-pack/plugins/reporting/server/lib/store/store.test.ts +++ b/x-pack/plugins/reporting/server/lib/store/store.test.ts @@ -75,7 +75,7 @@ describe('ReportingStore', () => { payload: {}, meta: {}, } as any); - expect(store.addReport(mockReport)).rejects.toMatchInlineSnapshot( + await expect(store.addReport(mockReport)).rejects.toMatchInlineSnapshot( `[Error: Report object from ES has missing fields!]` ); }); diff --git a/x-pack/plugins/rule_registry/server/plugin.ts b/x-pack/plugins/rule_registry/server/plugin.ts index 8cb6df23ae766..2a430c45b54d8 100644 --- a/x-pack/plugins/rule_registry/server/plugin.ts +++ b/x-pack/plugins/rule_registry/server/plugin.ts @@ -119,20 +119,23 @@ export class RuleRegistryPlugin this.ruleDataService.initializeService(); - core.getStartServices().then(([_, depsStart]) => { - const ruleRegistrySearchStrategy = ruleRegistrySearchStrategyProvider( - depsStart.data, - depsStart.alerting, - logger, - plugins.security, - depsStart.spaces - ); - - plugins.data.search.registerSearchStrategy( - RULE_SEARCH_STRATEGY_NAME, - ruleRegistrySearchStrategy - ); - }); + core + .getStartServices() + .then(([_, depsStart]) => { + const ruleRegistrySearchStrategy = ruleRegistrySearchStrategyProvider( + depsStart.data, + depsStart.alerting, + logger, + plugins.security, + depsStart.spaces + ); + + plugins.data.search.registerSearchStrategy( + RULE_SEARCH_STRATEGY_NAME, + ruleRegistrySearchStrategy + ); + }) + .catch(() => {}); // ALERTS ROUTES const router = core.http.createRouter(); diff --git a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/resource_installer.test.ts b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/resource_installer.test.ts index defaed0a7500b..f2cbe8ef5aeb7 100644 --- a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/resource_installer.test.ts +++ b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/resource_installer.test.ts @@ -88,11 +88,11 @@ describe('resourceInstaller', () => { pluginStop$, dataStreamAdapter, }); - installer.installCommonResources(); + await installer.installCommonResources(); expect(getClusterClient).not.toHaveBeenCalled(); }); - it('should not install index level resources', () => { + it('should not install index level resources', async () => { const mockClusterClient = elasticsearchServiceMock.createElasticsearchClient(); const getClusterClient = jest.fn(() => Promise.resolve(mockClusterClient)); @@ -119,7 +119,7 @@ describe('resourceInstaller', () => { }; const indexInfo = new IndexInfo({ indexOptions, kibanaVersion: '8.1.0' }); - installer.installIndexLevelResources(indexInfo); + await installer.installIndexLevelResources(indexInfo); expect(mockClusterClient.cluster.putComponentTemplate).not.toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts b/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts index 99454bfe30946..49e7d706b3117 100644 --- a/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts +++ b/x-pack/plugins/rule_registry/server/search_strategy/search_strategy.ts @@ -199,8 +199,8 @@ export const ruleRegistrySearchStrategyProvider = ( ); }, cancel: async (id, options, deps) => { - if (internalUserEs.cancel) internalUserEs.cancel(id, options, deps); - if (requestUserEs.cancel) requestUserEs.cancel(id, options, deps); + if (internalUserEs.cancel) internalUserEs.cancel(id, options, deps).catch(() => {}); + if (requestUserEs.cancel) requestUserEs.cancel(id, options, deps).catch(() => {}); }, }; }; diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver.ts b/x-pack/plugins/screenshotting/server/browsers/chromium/driver.ts index 5727a854ac3ca..fbe118280fe85 100644 --- a/x-pack/plugins/screenshotting/server/browsers/chromium/driver.ts +++ b/x-pack/plugins/screenshotting/server/browsers/chromium/driver.ts @@ -386,7 +386,7 @@ export class HeadlessChromiumDriver { errorReason: 'Aborted', requestId, }); - this.page.browser().close(); + void this.page.browser().close(); const error = getDisallowedOutgoingUrlError(interceptedUrl); this.screenshottingErrorSubject.next(error); logger.error(error); @@ -438,7 +438,7 @@ export class HeadlessChromiumDriver { } if (!allowed || !this.allowRequest(interceptedUrl)) { - this.page.browser().close(); + void this.page.browser().close(); const error = getDisallowedOutgoingUrlError(interceptedUrl); this.screenshottingErrorSubject.next(error); logger.error(error); @@ -464,7 +464,7 @@ export class HeadlessChromiumDriver { const wsEndpoint = this.page.browser().wsEndpoint(); const { port } = parseUrl(wsEndpoint); - open( + await open( `http://localhost:${port}/devtools/inspector.html?ws=localhost:${port}/devtools/page/${targetId}` ); } diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.test.ts b/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.test.ts index 317614e7733d1..13b9070edb7fb 100644 --- a/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.test.ts +++ b/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.test.ts @@ -82,7 +82,7 @@ describe('HeadlessChromiumDriverFactory', () => { it('rejects if Puppeteer launch fails', async () => { jest.spyOn(puppeteer, 'launch').mockRejectedValue(`Puppeteer Launch mock fail.`); - expect(() => + await expect(() => factory .createPage({ openUrlTimeout: 0, defaultViewport: DEFAULT_VIEWPORT }) .pipe(take(1)) diff --git a/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.ts b/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.ts index 1c562a481790e..66a4dac0c37a2 100644 --- a/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.ts +++ b/x-pack/plugins/screenshotting/server/browsers/chromium/driver_factory/index.ts @@ -226,7 +226,7 @@ export class HeadlessChromiumDriverFactory { observer.add(() => { if (page.isClosed()) return; // avoid emitting a log unnecessarily logger.debug(`It looks like the browser is no longer being used. Closing the browser...`); - childProcess.kill(); // ignore async + void childProcess.kill(); // ignore async }); // make the observer subscribe to terminate$ @@ -272,7 +272,7 @@ export class HeadlessChromiumDriverFactory { logger.error(error); }); }); - })(); + })().catch(() => {}); }); } diff --git a/x-pack/plugins/screenshotting/server/formats/pdf/index.ts b/x-pack/plugins/screenshotting/server/formats/pdf/index.ts index 8a4571c128f9c..ff58fbf6d8bc5 100644 --- a/x-pack/plugins/screenshotting/server/formats/pdf/index.ts +++ b/x-pack/plugins/screenshotting/server/formats/pdf/index.ts @@ -130,9 +130,9 @@ export async function toPdf( } } else { buffer = results[0].screenshots[0].data; // This buffer is already the PDF - pages = await PDFJS.getDocument({ data: buffer }).promise.then((doc) => { + pages = await PDFJS.getDocument({ data: buffer }).promise.then(async (doc) => { const numPages = doc.numPages; - doc.destroy(); + await doc.destroy(); return numPages; }); } diff --git a/x-pack/plugins/search_notebooks/server/lib/notebook_catalog.test.ts b/x-pack/plugins/search_notebooks/server/lib/notebook_catalog.test.ts index 13e79c4ed3422..0c6e4874b4bf1 100644 --- a/x-pack/plugins/search_notebooks/server/lib/notebook_catalog.test.ts +++ b/x-pack/plugins/search_notebooks/server/lib/notebook_catalog.test.ts @@ -25,24 +25,24 @@ describe('getNotebook', () => { jest.clearAllMocks(); }); - it('throws an error if given an unknown notebook id', () => { - expect(getNotebook('some-fake-id', options)).rejects.toThrow('Unknown Notebook ID'); + it('throws an error if given an unknown notebook id', async () => { + await expect(getNotebook('some-fake-id', options)).rejects.toThrow('Unknown Notebook ID'); expect(mockLogger.warn).toHaveBeenCalledTimes(1); }); - it('throws an error if the file is not found', () => { + it('throws an error if the file is not found', async () => { const notebookId = DEFAULT_NOTEBOOKS.notebooks[0].id; jest.mocked(fs.access).mockReset().mockRejectedValue(new Error('Boom')); - expect(getNotebook(notebookId, options)).rejects.toThrow('Failed to fetch notebook.'); + await expect(getNotebook(notebookId, options)).rejects.toThrow('Failed to fetch notebook.'); }); - it('Reads notebook', () => { + it('Reads notebook', async () => { const notebookId = DEFAULT_NOTEBOOKS.notebooks[0].id; jest.mocked(fs.access).mockReset().mockResolvedValue(undefined); - expect(getNotebook(notebookId, options)).resolves.toMatchObject({ + await expect(getNotebook(notebookId, options)).resolves.toMatchObject({ cells: expect.anything(), metadata: expect.anything(), }); diff --git a/x-pack/plugins/search_playground/server/lib/conversational_chain.test.ts b/x-pack/plugins/search_playground/server/lib/conversational_chain.test.ts index bb65f55928bcd..58ce10a3b8051 100644 --- a/x-pack/plugins/search_playground/server/lib/conversational_chain.test.ts +++ b/x-pack/plugins/search_playground/server/lib/conversational_chain.test.ts @@ -76,7 +76,7 @@ describe('conversational chain', () => { const stream = await conversationalChain.stream(aiClient, chat); - const streamToValue: string[] = await new Promise((resolve) => { + const streamToValue: string[] = await new Promise((resolve, reject) => { const reader = stream.getReader(); const textDecoder = new TextDecoder(); const chunks: string[] = []; @@ -89,7 +89,7 @@ describe('conversational chain', () => { chunks.push(textDecoder.decode(value)); read(); } - }); + }, reject); }; read(); }); diff --git a/x-pack/plugins/search_playground/server/lib/conversational_chain.ts b/x-pack/plugins/search_playground/server/lib/conversational_chain.ts index 0844fe3b64c42..b18faa06780e8 100644 --- a/x-pack/plugins/search_playground/server/lib/conversational_chain.ts +++ b/x-pack/plugins/search_playground/server/lib/conversational_chain.ts @@ -167,7 +167,7 @@ class ConversationalChainFn { // check that main chain (without parent) is finished: if (parentRunId == null) { - data.close(); + data.close().catch(() => {}); } }, }, diff --git a/x-pack/plugins/search_playground/server/routes.ts b/x-pack/plugins/search_playground/server/routes.ts index e9f40d89d18fe..d2081dade0474 100644 --- a/x-pack/plugins/search_playground/server/routes.ts +++ b/x-pack/plugins/search_playground/server/routes.ts @@ -147,15 +147,18 @@ export function defineRoutes({ const reader = (stream as ReadableStream).getReader(); const textDecoder = new TextDecoder(); - async function pushStreamUpdate() { - reader.read().then(({ done, value }: { done: boolean; value?: Uint8Array }) => { - if (done) { - end(); - return; - } - push(textDecoder.decode(value)); - pushStreamUpdate(); - }); + function pushStreamUpdate() { + reader + .read() + .then(({ done, value }: { done: boolean; value?: Uint8Array }) => { + if (done) { + end(); + return; + } + push(textDecoder.decode(value)); + pushStreamUpdate(); + }) + .catch(() => {}); } pushStreamUpdate(); diff --git a/x-pack/plugins/security/server/saved_objects/ensure_authorized.test.ts b/x-pack/plugins/security/server/saved_objects/ensure_authorized.test.ts index 22c219a5668ab..821a90dbdeb22 100644 --- a/x-pack/plugins/security/server/saved_objects/ensure_authorized.test.ts +++ b/x-pack/plugins/security/server/saved_objects/ensure_authorized.test.ts @@ -79,7 +79,7 @@ describe('ensureAuthorized', () => { test('throws an error when privilege check fails', async () => { const deps = setupDependencies(); deps.checkSavedObjectsPrivilegesAsCurrentUser.mockRejectedValue(new Error('Oh no!')); - expect(ensureAuthorized(deps, [], [], [])).rejects.toThrowError('Oh no!'); + await expect(ensureAuthorized(deps, [], [], [])).rejects.toThrowError('Oh no!'); }); describe('fully authorized', () => { @@ -149,7 +149,7 @@ describe('ensureAuthorized', () => { test('with default options', async () => { const deps = setupDependencies(); deps.checkSavedObjectsPrivilegesAsCurrentUser.mockResolvedValue(resolvedPrivileges); - expect( + await expect( ensureAuthorized(deps, types, actions, namespaces) ).rejects.toThrowErrorMatchingInlineSnapshot(`"Unable to (bar a),(bar b),(bar c),(foo c)"`); }); @@ -199,7 +199,7 @@ describe('ensureAuthorized', () => { test('with default options', async () => { const deps = setupDependencies(); deps.checkSavedObjectsPrivilegesAsCurrentUser.mockResolvedValue(resolvedPrivileges); - expect( + await expect( ensureAuthorized(deps, types, actions, namespaces) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Unable to (bar a),(bar b),(bar c),(foo a),(foo b),(foo c)"` diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.test.ts index a1988cb7a13ae..332b5778d67f7 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.test.ts @@ -89,7 +89,7 @@ describe('Endpoint artifact packager task', () => { endpointAppContext: mockContext, taskManager: mockTaskManager, }); - manifestTaskInstance.start({ taskManager: taskManagerMock.createStart() }); + void manifestTaskInstance.start({ taskManager: taskManagerMock.createStart() }); mockContext.service.getManifestManager = jest.fn().mockReturnValue(manifestManager); diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/response_actions/complete_external_actions_task.ts b/x-pack/plugins/security_solution/server/endpoint/lib/response_actions/complete_external_actions_task.ts index a9c81fbd69e2c..8d77ddecbcf56 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/response_actions/complete_external_actions_task.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/response_actions/complete_external_actions_task.ts @@ -40,7 +40,7 @@ export class CompleteExternalResponseActionsTask { private wasStarted = false; private log: Logger; private esClient: ElasticsearchClient | undefined = undefined; - private cleanup: (() => void | Promise) | undefined; + private cleanup: (() => void) | undefined; private taskTimeout = '20m'; // Default. Real value comes from server config private taskInterval = '60s'; // Default. Real value comes from server config @@ -54,7 +54,7 @@ export class CompleteExternalResponseActionsTask { return `${COMPLETE_EXTERNAL_RESPONSE_ACTIONS_TASK_TYPE}-${COMPLETE_EXTERNAL_RESPONSE_ACTIONS_TASK_VERSION}`; } - public async setup({ taskManager }: CompleteExternalResponseActionsTaskSetupOptions) { + public setup({ taskManager }: CompleteExternalResponseActionsTaskSetupOptions) { if (this.wasSetup) { throw new Error(`Task has already been setup!`); } @@ -143,7 +143,7 @@ export class CompleteExternalResponseActionsTask { this.log.info( `Un-registering task definition [${COMPLETE_EXTERNAL_RESPONSE_ACTIONS_TASK_TYPE}] (if it exists)` ); - taskManager.removeIfExists(COMPLETE_EXTERNAL_RESPONSE_ACTIONS_TASK_TYPE); + taskManager.removeIfExists(COMPLETE_EXTERNAL_RESPONSE_ACTIONS_TASK_TYPE).catch(() => {}); this.cleanup = undefined; }; } diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/response_actions/complete_external_actions_task_runner.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/response_actions/complete_external_actions_task_runner.test.ts index 14d93a292a573..9497f24c8fc42 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/response_actions/complete_external_actions_task_runner.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/response_actions/complete_external_actions_task_runner.test.ts @@ -140,13 +140,13 @@ describe('CompleteExternalTaskRunner class', () => { return clientMock; } ); - runnerInstance.run(); + void runnerInstance.run(); await waitFor(() => { expect(endpointContextServicesMock.getInternalResponseActionsClient).toHaveBeenCalled(); }); - runnerInstance.cancel(); + await runnerInstance.cancel(); expect(processPendingActionsAbortSignal!.aborted).toBe(true); }); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver.ts index 01d3ad006405f..13145db5e3e8e 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver.ts @@ -17,19 +17,28 @@ import { handleTree } from './resolver/tree/handler'; import { handleEntities } from './resolver/entity/handler'; import { handleEvents } from './resolver/events'; -export const registerResolverRoutes = async ( +export const registerResolverRoutes = ( router: SecuritySolutionPluginRouter, startServices: StartServicesAccessor, config: ConfigType ) => { - const [, { ruleRegistry, licensing }] = await startServices(); + const getRuleRegistry = async () => { + const [, { ruleRegistry }] = await startServices(); + return ruleRegistry; + }; + + const getLicensing = async () => { + const [, { licensing }] = await startServices(); + return licensing; + }; + router.post( { path: '/api/endpoint/resolver/tree', validate: validateTree, options: { authRequired: true }, }, - handleTree(ruleRegistry, config, licensing) + handleTree(getRuleRegistry, config, getLicensing) ); router.post( @@ -38,7 +47,7 @@ export const registerResolverRoutes = async ( validate: validateEvents, options: { authRequired: true }, }, - handleEvents(ruleRegistry) + handleEvents(getRuleRegistry) ); /** diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/events.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/events.ts index ddc961e369168..7d6e4865c9160 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/events.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/events.ts @@ -32,7 +32,7 @@ function createEvents( * requested. */ export function handleEvents( - ruleRegistry: RuleRegistryPluginStartContract + getRuleRegistry: () => Promise ): RequestHandler< unknown, TypeOf, @@ -44,6 +44,7 @@ export function handleEvents( body, } = req; const eventsClient = (await context.core).elasticsearch.client; + const ruleRegistry = await getRuleRegistry(); const alertsClient = await ruleRegistry.getRacClientWithRequest(req); const shouldExcludeColdAndFrozenTiers = await ( await context.core diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/handler.ts b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/handler.ts index 48c99cd8ed112..3a3fb1d17816a 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/handler.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/resolver/tree/handler.ts @@ -19,15 +19,16 @@ import { featureUsageService } from '../../../services/feature_usage'; import { Fetcher } from './utils/fetch'; export function handleTree( - ruleRegistry: RuleRegistryPluginStartContract, + getRuleRegistry: () => Promise, config: ConfigType, - licensing: LicensingPluginStart + getLicensing: () => Promise ): RequestHandler> { return async (context, req, res) => { const client = (await context.core).elasticsearch.client; const { experimentalFeatures: { insightsRelatedAlertsByProcessAncestry }, } = config; + const licensing = await getLicensing(); const license = await firstValueFrom(licensing.license$); const hasAccessToInsightsRelatedByProcessAncestry = insightsRelatedAlertsByProcessAncestry && license.hasAtLeast('platinum'); @@ -40,7 +41,7 @@ export function handleTree( } const alertsClient = hasAccessToInsightsRelatedByProcessAncestry - ? await ruleRegistry.getRacClientWithRequest(req) + ? await (await getRuleRegistry()).getRacClientWithRequest(req) : undefined; const fetcher = new Fetcher(client, alertsClient); const body = await fetcher.tree({ ...req.body, shouldExcludeColdAndFrozenTiers }); diff --git a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/unified_manifest_client.ts b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/unified_manifest_client.ts index ae1acdbd8e4cf..db47c43b68607 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/unified_manifest_client.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/unified_manifest_client.ts @@ -98,11 +98,7 @@ export class UnifiedManifestClient { const unifiedManifestsFetcher = this.fetchAllUnifiedManifests(this.savedObjectsClient, options); for await (const unifiedManifests of unifiedManifestsFetcher) { - if (cb.constructor.name === 'AsyncFunction') { - await cb(unifiedManifests); - } else { - cb(unifiedManifests); - } + await cb(unifiedManifests); } } diff --git a/x-pack/plugins/security_solution/server/endpoint/utils/queue_processor.ts b/x-pack/plugins/security_solution/server/endpoint/utils/queue_processor.ts index 05bd638956f89..202683c8d4c97 100644 --- a/x-pack/plugins/security_solution/server/endpoint/utils/queue_processor.ts +++ b/x-pack/plugins/security_solution/server/endpoint/utils/queue_processor.ts @@ -135,7 +135,7 @@ export class QueueProcessor { public addToQueue(...data: T[]) { if (data.length > 0) { this.queue.push(...data); - this.processQueue(); + this.processQueue().catch(() => {}); } } diff --git a/x-pack/plugins/security_solution/server/fleet_integration/fleet_integration.test.ts b/x-pack/plugins/security_solution/server/fleet_integration/fleet_integration.test.ts index 34a3b44b551d6..7dddfa32a1967 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/fleet_integration.test.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/fleet_integration.test.ts @@ -572,7 +572,7 @@ describe('ingest_integration tests ', () => { const validDateYesterday = moment.utc().subtract(1, 'day'); - it('should throw if endpointProtectionUpdates productFeature is disabled and user modifies global_manifest_version', () => { + it('should throw if endpointProtectionUpdates productFeature is disabled and user modifies global_manifest_version', async () => { productFeaturesService = createProductFeaturesServiceMock( ALL_PRODUCT_FEATURE_KEYS.filter((key) => key !== 'endpoint_protection_updates') ); @@ -587,7 +587,7 @@ describe('ingest_integration tests ', () => { ); const policyConfig = generator.generatePolicyPackagePolicy(); policyConfig.inputs[0]!.config!.policy.value.global_manifest_version = '2023-01-01'; - expect(() => + await expect(() => callback(policyConfig, soClient, esClient, requestContextMock.convertContext(ctx), req) ).rejects.toThrow( 'To modify protection updates, you must add at least Endpoint Complete to your project.' diff --git a/x-pack/plugins/security_solution/server/fleet_integration/fleet_integration.ts b/x-pack/plugins/security_solution/server/fleet_integration/fleet_integration.ts index 99035d3b66a88..4e5a1e2f44ff2 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/fleet_integration.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/fleet_integration.ts @@ -223,7 +223,7 @@ export const getPackagePolicyUpdateCallback = ( validateEndpointPackagePolicy(endpointIntegrationData.inputs); - notifyProtectionFeatureUsage( + await notifyProtectionFeatureUsage( endpointIntegrationData, featureUsageService, endpointMetadataService @@ -294,7 +294,9 @@ export const getPackagePolicyPostCreateCallback = ( exceptionsClient, integrationConfig.value.eventFilters, packagePolicy - ); + ).catch((error) => { + logger.error(`Failed to create event filters: ${error}`); + }); } return packagePolicy; }; diff --git a/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_event_filters.ts b/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_event_filters.ts index d9bab942de2ae..5e5cefd5d2a90 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_event_filters.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/handlers/create_event_filters.ts @@ -55,19 +55,19 @@ export const createEventFilters = async ( } } - createNonInteractiveSessionEventFilter(logger, exceptionsClient, packagePolicy); + await createNonInteractiveSessionEventFilter(logger, exceptionsClient, packagePolicy); }; /** * Create an Event Filter for non-interactive sessions and attach it to the policy */ -export const createNonInteractiveSessionEventFilter = ( +export const createNonInteractiveSessionEventFilter = async ( logger: Logger, exceptionsClient: ExceptionListClient, packagePolicy: PackagePolicy -): void => { +): Promise => { try { - exceptionsClient.createExceptionListItem({ + await exceptionsClient.createExceptionListItem({ listId: ENDPOINT_EVENT_FILTERS_LIST_ID, description: i18n.translate( 'xpack.securitySolution.fleetIntegration.elasticDefend.eventFilter.nonInteractiveSessions.description', diff --git a/x-pack/plugins/security_solution/server/fleet_integration/handlers/remove_protection_updates_note.ts b/x-pack/plugins/security_solution/server/fleet_integration/handlers/remove_protection_updates_note.ts index 9106eba06e780..13ddda419ff90 100644 --- a/x-pack/plugins/security_solution/server/fleet_integration/handlers/remove_protection_updates_note.ts +++ b/x-pack/plugins/security_solution/server/fleet_integration/handlers/remove_protection_updates_note.ts @@ -23,11 +23,8 @@ export const removeProtectionUpdatesNote = async ( id: policy.id, }, }); - await pMap( - foundProtectionUpdatesNotes.saved_objects, - (protectionUpdatesNote: { id: string }) => { - soClient.delete(protectionUpdatesNoteSavedObjectType, protectionUpdatesNote.id); - } + await pMap(foundProtectionUpdatesNotes.saved_objects, (protectionUpdatesNote: { id: string }) => + soClient.delete(protectionUpdatesNoteSavedObjectType, protectionUpdatesNote.id) ); } }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/rule_actions/legacy_create_rule_actions_saved_object.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/rule_actions/legacy_create_rule_actions_saved_object.test.ts index 61bea17db1156..2a8705d03b877 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/rule_actions/legacy_create_rule_actions_saved_object.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/rule_actions/legacy_create_rule_actions_saved_object.test.ts @@ -19,8 +19,8 @@ describe('legacy_create_rule_actions_saved_object', () => { savedObjectsClient = savedObjectsClientMock.create(); }); - test('it creates a rule actions saved object with empty actions array', () => { - legacyCreateRuleActionsSavedObject({ + test('it creates a rule actions saved object with empty actions array', async () => { + await legacyCreateRuleActionsSavedObject({ ruleAlertId: '123', savedObjectsClient, actions: [], @@ -43,8 +43,8 @@ describe('legacy_create_rule_actions_saved_object', () => { }); }); - test('it creates a rule actions saved object with 1 single action', () => { - legacyCreateRuleActionsSavedObject({ + test('it creates a rule actions saved object with 1 single action', async () => { + await legacyCreateRuleActionsSavedObject({ ruleAlertId: '123', savedObjectsClient, actions: [ @@ -90,8 +90,8 @@ describe('legacy_create_rule_actions_saved_object', () => { }); }); - test('it creates a rule actions saved object with 2 actions', () => { - legacyCreateRuleActionsSavedObject({ + test('it creates a rule actions saved object with 2 actions', async () => { + await legacyCreateRuleActionsSavedObject({ ruleAlertId: '123', savedObjectsClient, actions: [ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/rule_actions/legacy_get_rule_actions_saved_object.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/rule_actions/legacy_get_rule_actions_saved_object.test.ts index 1f598f0ccf78b..ae3e21881d7af 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/rule_actions/legacy_get_rule_actions_saved_object.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_actions_legacy/logic/rule_actions/legacy_get_rule_actions_saved_object.test.ts @@ -33,8 +33,8 @@ describe('legacy_get_rule_actions_saved_object', () => { }); }); - test('calls "savedObjectsClient.find" with the expected "hasReferences"', () => { - legacyGetRuleActionsSavedObject({ ruleAlertId: '123', savedObjectsClient, logger }); + test('calls "savedObjectsClient.find" with the expected "hasReferences"', async () => { + await legacyGetRuleActionsSavedObject({ ruleAlertId: '123', savedObjectsClient, logger }); const [[arg1]] = savedObjectsClient.find.mock.calls; expect(arg1).toEqual({ hasReference: { id: '123', type: 'alert' }, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/route.ts index 7a3fd49dcd2d1..5cbaa44834302 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_preview/api/preview_rules/route.ts @@ -69,7 +69,7 @@ import { wrapSearchSourceClient } from './wrap_search_source_client'; const PREVIEW_TIMEOUT_SECONDS = 60; const MAX_ROUTE_CONCURRENCY = 10; -export const previewRulesRoute = async ( +export const previewRulesRoute = ( router: SecuritySolutionPluginRouter, config: ConfigType, ml: SetupPlugins['ml'], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_response_actions/schedule_notification_response_actions.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_response_actions/schedule_notification_response_actions.test.ts index 67457b1574000..6fac2725754d5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_response_actions/schedule_notification_response_actions.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_response_actions/schedule_notification_response_actions.test.ts @@ -96,7 +96,7 @@ describe('ScheduleNotificationResponseActions', () => { }, }, ]; - scheduleNotificationResponseActions({ signals, responseActions }); + await scheduleNotificationResponseActions({ signals, responseActions }); expect(osqueryActionMock.create).toHaveBeenCalledWith({ ...defaultQueryResultParams, @@ -123,7 +123,7 @@ describe('ScheduleNotificationResponseActions', () => { }, }, ]; - scheduleNotificationResponseActions({ signals, responseActions }); + await scheduleNotificationResponseActions({ signals, responseActions }); expect(osqueryActionMock.create).toHaveBeenCalledWith({ ...defaultPackResultParams, @@ -149,7 +149,7 @@ describe('ScheduleNotificationResponseActions', () => { }, }, ]; - scheduleNotificationResponseActions({ signals, responseActions }); + await scheduleNotificationResponseActions({ signals, responseActions }); expect(endpointActionMock.getInternalResponseActionsClient).toHaveBeenCalledTimes(1); expect(endpointActionMock.getInternalResponseActionsClient).toHaveBeenCalledWith({ @@ -188,7 +188,7 @@ describe('ScheduleNotificationResponseActions', () => { }, }, ]; - scheduleNotificationResponseActions({ + await scheduleNotificationResponseActions({ signals, responseActions, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_response_actions/schedule_notification_response_actions.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_response_actions/schedule_notification_response_actions.ts index 93c8e22ac2316..d20995291b5f1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_response_actions/schedule_notification_response_actions.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rule_response_actions/schedule_notification_response_actions.ts @@ -5,7 +5,6 @@ * 2.0. */ -import { each } from 'lodash'; import type { EndpointAppContextService } from '../../../endpoint/endpoint_app_context_services'; import type { SetupPlugins } from '../../../plugin_contract'; import { ResponseActionTypesEnum } from '../../../../common/api/detection_engine/model/rule_response_actions'; @@ -24,22 +23,24 @@ export const getScheduleNotificationResponseActionsService = osqueryCreateActionService, endpointAppContextService, }: ScheduleNotificationResponseActionsService) => - ({ signals, responseActions }: ScheduleNotificationActions) => { + async ({ signals, responseActions }: ScheduleNotificationActions) => { const alerts = (signals as Alert[]).filter((alert) => alert.agent?.id) as AlertWithAgent[]; - each(responseActions, (responseAction) => { - if ( - responseAction.actionTypeId === ResponseActionTypesEnum['.osquery'] && - osqueryCreateActionService - ) { - osqueryResponseAction(responseAction, osqueryCreateActionService, { - alerts, - }); - } - if (responseAction.actionTypeId === ResponseActionTypesEnum['.endpoint']) { - endpointResponseAction(responseAction, endpointAppContextService, { - alerts, - }); - } - }); + await Promise.all( + responseActions.map(async (responseAction) => { + if ( + responseAction.actionTypeId === ResponseActionTypesEnum['.osquery'] && + osqueryCreateActionService + ) { + await osqueryResponseAction(responseAction, osqueryCreateActionService, { + alerts, + }); + } + if (responseAction.actionTypeId === ResponseActionTypesEnum['.endpoint']) { + await endpointResponseAction(responseAction, endpointAppContextService, { + alerts, + }); + } + }) + ); }; diff --git a/x-pack/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.test.ts b/x-pack/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.test.ts index b77ea7742077d..9cbb6ee9ce2e5 100644 --- a/x-pack/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.test.ts +++ b/x-pack/plugins/security_solution/server/lib/entity_analytics/asset_criticality/asset_criticality_data_client.test.ts @@ -81,7 +81,7 @@ describe('AssetCriticalityDataClient', () => { }); it('searches in the asset criticality index', async () => { - subject.search({ query: { match_all: {} } }); + await subject.search({ query: { match_all: {} } }); expect(esClientMock.search).toHaveBeenCalledWith( expect.objectContaining({ index: '.asset-criticality.asset-criticality-default' }) @@ -89,7 +89,7 @@ describe('AssetCriticalityDataClient', () => { }); it('requires a query parameter', async () => { - subject.search({ query: { match_all: {} } }); + await subject.search({ query: { match_all: {} } }); expect(esClientMock.search).toHaveBeenCalledWith( expect.objectContaining({ body: { query: { match_all: {} } } }) @@ -97,13 +97,13 @@ describe('AssetCriticalityDataClient', () => { }); it('accepts a size parameter', async () => { - subject.search({ query: { match_all: {} }, size: 100 }); + await subject.search({ query: { match_all: {} }, size: 100 }); expect(esClientMock.search).toHaveBeenCalledWith(expect.objectContaining({ size: 100 })); }); it('defaults to the default query size', async () => { - subject.search({ query: { match_all: {} } }); + await subject.search({ query: { match_all: {} } }); const defaultSize = 1_000; expect(esClientMock.search).toHaveBeenCalledWith( @@ -112,14 +112,14 @@ describe('AssetCriticalityDataClient', () => { }); it('caps the size to the maximum query size', async () => { - subject.search({ query: { match_all: {} }, size: 999999 }); + await subject.search({ query: { match_all: {} }, size: 999999 }); const maxSize = 100_000; expect(esClientMock.search).toHaveBeenCalledWith(expect.objectContaining({ size: maxSize })); }); it('ignores an index_not_found_exception if the criticality index does not exist', async () => { - subject.search({ query: { match_all: {} } }); + await subject.search({ query: { match_all: {} } }); expect(esClientMock.search).toHaveBeenCalledWith( expect.objectContaining({ ignore_unavailable: true }) diff --git a/x-pack/plugins/security_solution/server/lib/entity_analytics/risk_score/tasks/risk_scoring_task.ts b/x-pack/plugins/security_solution/server/lib/entity_analytics/risk_score/tasks/risk_scoring_task.ts index f936ca6a83c76..b3d25855ba427 100644 --- a/x-pack/plugins/security_solution/server/lib/entity_analytics/risk_score/tasks/risk_scoring_task.ts +++ b/x-pack/plugins/security_solution/server/lib/entity_analytics/risk_score/tasks/risk_scoring_task.ts @@ -310,7 +310,7 @@ export const runTask = async ({ }; telemetry.reportEvent(RISK_SCORE_EXECUTION_SUCCESS_EVENT.eventType, telemetryEvent); - riskScoreService.scheduleLatestTransformNow(); + await riskScoreService.scheduleLatestTransformNow(); if (isCancelled()) { log('task was cancelled'); diff --git a/x-pack/plugins/security_solution/server/lib/product_features_service/product_features_service.test.ts b/x-pack/plugins/security_solution/server/lib/product_features_service/product_features_service.test.ts index 3597a109adbfe..b59dafb2f0eb7 100644 --- a/x-pack/plugins/security_solution/server/lib/product_features_service/product_features_service.test.ts +++ b/x-pack/plugins/security_solution/server/lib/product_features_service/product_features_service.test.ts @@ -192,7 +192,7 @@ describe('ProductFeaturesService', () => { expect(mockHttpSetup.registerOnPostAuth).toHaveBeenCalledTimes(1); }); - it('should authorize when no tag matches', () => { + it('should authorize when no tag matches', async () => { const experimentalFeatures = {} as ExperimentalFeatures; const productFeaturesService = new ProductFeaturesService( loggerMock.create(), @@ -200,14 +200,14 @@ describe('ProductFeaturesService', () => { ); productFeaturesService.registerApiAccessControl(mockHttpSetup); - lastRegisteredFn(getReq(['access:something', 'access:securitySolution']), res, toolkit); + await lastRegisteredFn(getReq(['access:something', 'access:securitySolution']), res, toolkit); expect(MockedProductFeatures.mock.instances[0].isActionRegistered).not.toHaveBeenCalled(); expect(res.notFound).not.toHaveBeenCalled(); expect(toolkit.next).toHaveBeenCalledTimes(1); }); - it('should check when tag matches and return not found when not action registered', () => { + it('should check when tag matches and return not found when not action registered', async () => { const experimentalFeatures = {} as ExperimentalFeatures; const productFeaturesService = new ProductFeaturesService( loggerMock.create(), @@ -218,7 +218,7 @@ describe('ProductFeaturesService', () => { (MockedProductFeatures.mock.instances[0].isActionRegistered as jest.Mock).mockReturnValueOnce( false ); - lastRegisteredFn(getReq(['access:securitySolution-foo']), res, toolkit); + await lastRegisteredFn(getReq(['access:securitySolution-foo']), res, toolkit); expect(MockedProductFeatures.mock.instances[0].isActionRegistered).toHaveBeenCalledWith( 'api:securitySolution-foo' @@ -227,7 +227,7 @@ describe('ProductFeaturesService', () => { expect(toolkit.next).not.toHaveBeenCalled(); }); - it('should check when tag matches and continue when action registered', () => { + it('should check when tag matches and continue when action registered', async () => { const experimentalFeatures = {} as ExperimentalFeatures; const productFeaturesService = new ProductFeaturesService( loggerMock.create(), @@ -238,7 +238,7 @@ describe('ProductFeaturesService', () => { (MockedProductFeatures.mock.instances[0].isActionRegistered as jest.Mock).mockReturnValueOnce( true ); - lastRegisteredFn(getReq(['access:securitySolution-foo']), res, toolkit); + await lastRegisteredFn(getReq(['access:securitySolution-foo']), res, toolkit); expect(MockedProductFeatures.mock.instances[0].isActionRegistered).toHaveBeenCalledWith( 'api:securitySolution-foo' @@ -247,7 +247,7 @@ describe('ProductFeaturesService', () => { expect(toolkit.next).toHaveBeenCalledTimes(1); }); - it('should check when productFeature tag when it matches and return not found when not enabled', () => { + it('should check when productFeature tag when it matches and return not found when not enabled', async () => { const experimentalFeatures = {} as ExperimentalFeatures; const productFeaturesService = new ProductFeaturesService( loggerMock.create(), @@ -257,14 +257,14 @@ describe('ProductFeaturesService', () => { productFeaturesService.isEnabled = jest.fn().mockReturnValueOnce(false); - lastRegisteredFn(getReq(['securitySolutionProductFeature:foo']), res, toolkit); + await lastRegisteredFn(getReq(['securitySolutionProductFeature:foo']), res, toolkit); expect(productFeaturesService.isEnabled).toHaveBeenCalledWith('foo'); expect(res.notFound).toHaveBeenCalledTimes(1); expect(toolkit.next).not.toHaveBeenCalled(); }); - it('should check when productFeature tag when it matches and continue when enabled', () => { + it('should check when productFeature tag when it matches and continue when enabled', async () => { const experimentalFeatures = {} as ExperimentalFeatures; const productFeaturesService = new ProductFeaturesService( loggerMock.create(), @@ -274,7 +274,7 @@ describe('ProductFeaturesService', () => { productFeaturesService.isEnabled = jest.fn().mockReturnValueOnce(true); - lastRegisteredFn(getReq(['securitySolutionProductFeature:foo']), res, toolkit); + await lastRegisteredFn(getReq(['securitySolutionProductFeature:foo']), res, toolkit); expect(productFeaturesService.isEnabled).toHaveBeenCalledWith('foo'); expect(res.notFound).not.toHaveBeenCalled(); diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/receiver.ts b/x-pack/plugins/security_solution/server/lib/telemetry/receiver.ts index eff642239da3a..5b59282a320ea 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/receiver.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/receiver.ts @@ -596,7 +596,7 @@ export class TelemetryReceiver implements ITelemetryReceiver { yield alerts; } - this.closePointInTime(pitId); + await this.closePointInTime(pitId); } public async fetchPolicyConfigs(id: string) { diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/sender.ts b/x-pack/plugins/security_solution/server/lib/telemetry/sender.ts index a788a59b63b71..0f21cb58824f6 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/sender.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/sender.ts @@ -18,6 +18,7 @@ import type { TaskManagerSetupContract, TaskManagerStartContract, } from '@kbn/task-manager-plugin/server'; +import { exhaustMap, Subject, takeUntil, timer } from 'rxjs'; import type { ITelemetryReceiver } from './receiver'; import { copyAllowlistedFields, filterList } from './filterlists'; import { createTelemetryTaskConfigs } from './tasks'; @@ -92,10 +93,10 @@ export class TelemetryEventsSender implements ITelemetryEventsSender { private readonly initialCheckDelayMs = 10 * 1000; private readonly checkIntervalMs = 60 * 1000; private readonly logger: Logger; + private readonly stop$ = new Subject(); private maxQueueSize = telemetryConfiguration.telemetry_max_buffer_size; private telemetryStart?: TelemetryPluginStart; private telemetrySetup?: TelemetryPluginSetup; - private intervalId?: NodeJS.Timeout; private isSending = false; private receiver: ITelemetryReceiver | undefined; private queue: TelemetryEvent[] = []; @@ -162,16 +163,16 @@ export class TelemetryEventsSender implements ITelemetryEventsSender { } tlog(this.logger, `Starting local task`); - setTimeout(() => { - this.sendIfDue(); - this.intervalId = setInterval(() => this.sendIfDue(), this.checkIntervalMs); - }, this.initialCheckDelayMs); + timer(this.initialCheckDelayMs, this.checkIntervalMs) + .pipe( + takeUntil(this.stop$), + exhaustMap(() => this.sendIfDue()) + ) + .subscribe(); } public stop() { - if (this.intervalId) { - clearInterval(this.intervalId); - } + this.stop$.next(); } public queueTelemetryEvents(events: TelemetryEvent[]) { diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/task_metrics.test.ts b/x-pack/plugins/security_solution/server/lib/telemetry/task_metrics.test.ts index 784c34bf11d7d..866bd7cd1ba0c 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/task_metrics.test.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/task_metrics.test.ts @@ -35,7 +35,7 @@ describe('task metrics', () => { }); it('should record passed task metrics', async () => { - const metric = sendMetric('test'); + const metric = await sendMetric('test'); expect(metric.name).toEqual('test'); expect(metric.passed).toBeTruthy(); @@ -49,7 +49,7 @@ describe('task metrics', () => { jest.spyOn(telemetryConfiguration, 'use_async_sender', 'get').mockReturnValue(false); const trace = taskMetricsService.start('test'); - taskMetricsService.end(trace); + await taskMetricsService.end(trace); expect(mockTelemetryEventsSender.sendAsync).toHaveBeenCalledTimes(0); expect(mockTelemetryEventsSender.sendAsync).toHaveBeenCalledTimes(0); @@ -57,7 +57,7 @@ describe('task metrics', () => { }); it('should record failed task metrics', async () => { - const metric = sendMetric('test', Error('Boom!')); + const metric = await sendMetric('test', Error('Boom!')); expect(metric.name).toEqual('test'); expect(metric.passed).toBeFalsy(); @@ -67,9 +67,9 @@ describe('task metrics', () => { expect(metric.end_time).toBeGreaterThan(0); }); - function sendMetric(name: string, error?: Error): TaskMetric { + async function sendMetric(name: string, error?: Error): Promise { const trace = taskMetricsService.start(name); - taskMetricsService.end(trace, error); + await taskMetricsService.end(trace, error); expect(mockTelemetryEventsSender.sendAsync).toHaveBeenCalledTimes(1); const events = mockTelemetryEventsSender.sendAsync.mock.calls[0][1]; diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/configuration.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/configuration.ts index 701f42a89f4c0..0c95ccf651013 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/configuration.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/configuration.ts @@ -45,7 +45,7 @@ export function createTelemetryConfigurationTaskConfig() { if (manifest.notModified) { log.l('No new configuration artifact found, skipping...'); - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return 0; } @@ -106,14 +106,14 @@ export function createTelemetryConfigurationTaskConfig() { _receiver.setNumDocsToSample(configArtifact.pagination_config.num_docs_to_sample); } - taskMetricsService.end(trace); + await taskMetricsService.end(trace); log.l(`Updated TelemetryConfiguration: ${JSON.stringify(telemetryConfiguration)}`); return 0; } catch (err) { log.l(`Failed to set telemetry configuration due to ${err.message}`); telemetryConfiguration.resetAllToDefault(); - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/detection_rule.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/detection_rule.ts index f7616830716f1..91a2bf2a5b85a 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/detection_rule.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/detection_rule.ts @@ -62,7 +62,7 @@ export function createTelemetryDetectionRuleListsTaskConfig(maxTelemetryBatch: n if (!prebuiltRules) { log.l('no prebuilt rules found'); - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return 0; } @@ -118,7 +118,7 @@ export function createTelemetryDetectionRuleListsTaskConfig(maxTelemetryBatch: n for (const batch of batches) { await sender.sendOnDemand(TELEMETRY_CHANNEL_LISTS, batch); } - taskMetricsService.end(trace); + await taskMetricsService.end(trace); log.l( `Task: ${taskId} executed. Processed ${detectionRuleExceptionsJson.length} exceptions` @@ -126,7 +126,7 @@ export function createTelemetryDetectionRuleListsTaskConfig(maxTelemetryBatch: n return detectionRuleExceptionsJson.length; } catch (err) { - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/diagnostic.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/diagnostic.ts index 85ac4d744feae..1c691aea4155f 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/diagnostic.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/diagnostic.ts @@ -58,7 +58,7 @@ export function createTelemetryDiagnosticsTaskConfig() { if (alerts.length === 0) { log.l('no diagnostic alerts retrieved'); - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return alertCount; } @@ -67,10 +67,10 @@ export function createTelemetryDiagnosticsTaskConfig() { await sender.sendOnDemand(TELEMETRY_CHANNEL_ENDPOINT_ALERTS, processedAlerts); } - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return alertCount; } catch (err) { - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/endpoint.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/endpoint.ts index a55cbb4eda19a..aceb3ebf98926 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/endpoint.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/endpoint.ts @@ -94,14 +94,14 @@ export function createTelemetryEndpointTaskConfig(maxTelemetryBatch: number) { await sender.sendOnDemand(TELEMETRY_CHANNEL_ENDPOINT_META, batch); } } - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return documents.length; } catch (err) { log.l(`Error running endpoint alert telemetry task`, { error: JSON.stringify(err), }); - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/filterlists.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/filterlists.ts index 5a869ecade992..69a3ee646f0cf 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/filterlists.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/filterlists.ts @@ -44,7 +44,7 @@ export function createTelemetryFilterListArtifactTaskConfig() { const manifest = await artifactService.getArtifact(artifactName); if (manifest.notModified) { log.l('No new filterlist artifact found, skipping...'); - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return 0; } @@ -53,12 +53,12 @@ export function createTelemetryFilterListArtifactTaskConfig() { filterList.endpointAlerts = artifact.endpoint_alerts; filterList.exceptionLists = artifact.exception_lists; filterList.prebuiltRulesAlerts = artifact.prebuilt_rules_alerts; - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return 0; } catch (err) { log.l(`Failed to set telemetry filterlist artifact due to ${err.message}`); filterList.resetAllToDefault(); - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/prebuilt_rule_alerts.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/prebuilt_rule_alerts.ts index 921ff422bded5..3fda2878d4566 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/prebuilt_rule_alerts.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/prebuilt_rule_alerts.ts @@ -62,7 +62,7 @@ export function createTelemetryPrebuiltRuleAlertsTaskConfig(maxTelemetryBatch: n if (index === undefined) { log.l(`alerts index is not ready yet, skipping telemetry task`); - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return 0; } @@ -71,7 +71,7 @@ export function createTelemetryPrebuiltRuleAlertsTaskConfig(maxTelemetryBatch: n taskExecutionPeriod.current )) { if (alerts.length === 0) { - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return 0; } @@ -100,17 +100,17 @@ export function createTelemetryPrebuiltRuleAlertsTaskConfig(maxTelemetryBatch: n const batches = batchTelemetryRecords(enrichedAlerts, maxTelemetryBatch); const promises = batches.map(async (batch) => { - sender.sendOnDemand(TELEMETRY_CHANNEL_DETECTION_ALERTS, batch); + await sender.sendOnDemand(TELEMETRY_CHANNEL_DETECTION_ALERTS, batch); }); await Promise.all(promises); } - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return 0; } catch (err) { logger.error('could not complete prebuilt alerts telemetry task'); - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/security_lists.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/security_lists.ts index cc51fa7ba6d5b..09e1d14558c54 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/security_lists.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/security_lists.ts @@ -158,10 +158,10 @@ export function createTelemetrySecurityListTaskConfig(maxTelemetryBatch: number) if (valueListMetaData?.total_list_count) { await sender.sendOnDemand(TELEMETRY_CHANNEL_LISTS, [valueListMetaData]); } - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return trustedApplicationsCount + endpointExceptionsCount + endpointEventFiltersCount; } catch (err) { - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/timelines.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/timelines.ts index fa0a280fb7026..c016f029fa2a5 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/timelines.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/timelines.ts @@ -67,7 +67,7 @@ export function createTelemetryTimelineTaskConfig() { }); if (result.timeline) { - sender.sendOnDemand(TELEMETRY_CHANNEL_TIMELINE, [result.timeline]); + await sender.sendOnDemand(TELEMETRY_CHANNEL_TIMELINE, [result.timeline]); counter += 1; } else { log.l('no events in timeline'); @@ -76,11 +76,11 @@ export function createTelemetryTimelineTaskConfig() { log.l(`sent ${counter} timelines. Concluding timeline task.`); - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return counter; } catch (err) { - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/timelines_diagnostic.ts b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/timelines_diagnostic.ts index 9207adf7ae748..31718ec47b1e6 100644 --- a/x-pack/plugins/security_solution/server/lib/telemetry/tasks/timelines_diagnostic.ts +++ b/x-pack/plugins/security_solution/server/lib/telemetry/tasks/timelines_diagnostic.ts @@ -67,7 +67,7 @@ export function createTelemetryDiagnosticTimelineTaskConfig() { }); if (result.timeline) { - sender.sendOnDemand(TELEMETRY_CHANNEL_TIMELINE, [result.timeline]); + await sender.sendOnDemand(TELEMETRY_CHANNEL_TIMELINE, [result.timeline]); counter += 1; } else { log.l('no events in timeline'); @@ -76,11 +76,11 @@ export function createTelemetryDiagnosticTimelineTaskConfig() { log.l(`sent ${counter} timelines. Concluding timeline task.`); - taskMetricsService.end(trace); + await taskMetricsService.end(trace); return counter; } catch (err) { - taskMetricsService.end(trace, err); + await taskMetricsService.end(trace, err); return 0; } }, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/copy_timeline/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/copy_timeline/index.ts index 3a55b4fef8086..0e288e0099596 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/copy_timeline/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/timelines/copy_timeline/index.ts @@ -17,7 +17,7 @@ import { buildSiemResponse } from '../../../../detection_engine/routes/utils'; import { buildFrameworkRequest } from '../../../utils/common'; -export const copyTimelineRoute = async ( +export const copyTimelineRoute = ( router: SecuritySolutionPluginRouter, _: ConfigType, security: SetupPlugins['security'] diff --git a/x-pack/plugins/security_solution/server/plugin.ts b/x-pack/plugins/security_solution/server/plugin.ts index 998e02aba56ad..b0eb25bd3c18f 100644 --- a/x-pack/plugins/security_solution/server/plugin.ts +++ b/x-pack/plugins/security_solution/server/plugin.ts @@ -409,74 +409,80 @@ export class Plugin implements ISecuritySolutionPlugin { this.completeExternalResponseActionsTask.setup({ taskManager: plugins.taskManager }); } - core.getStartServices().then(([_, depsStart]) => { - appClientFactory.setup({ - getSpaceId: depsStart.spaces?.spacesService?.getSpaceId, - config, - kibanaVersion: pluginContext.env.packageInfo.version, - kibanaBranch: pluginContext.env.packageInfo.branch, - }); + core + .getStartServices() + .then(async ([_, depsStart]) => { + appClientFactory.setup({ + getSpaceId: depsStart.spaces?.spacesService?.getSpaceId, + config, + kibanaVersion: pluginContext.env.packageInfo.version, + kibanaBranch: pluginContext.env.packageInfo.branch, + }); + + const endpointFieldsStrategy = endpointFieldsProvider( + this.endpointAppContextService, + depsStart.data.indexPatterns + ); + plugins.data.search.registerSearchStrategy( + ENDPOINT_FIELDS_SEARCH_STRATEGY, + endpointFieldsStrategy + ); - const endpointFieldsStrategy = endpointFieldsProvider( - this.endpointAppContextService, - depsStart.data.indexPatterns - ); - plugins.data.search.registerSearchStrategy( - ENDPOINT_FIELDS_SEARCH_STRATEGY, - endpointFieldsStrategy - ); + const endpointPackagePoliciesStatsStrategy = + endpointPackagePoliciesStatsSearchStrategyProvider(this.endpointAppContextService); + plugins.data.search.registerSearchStrategy( + ENDPOINT_PACKAGE_POLICIES_STATS_STRATEGY, + endpointPackagePoliciesStatsStrategy + ); - const endpointPackagePoliciesStatsStrategy = - endpointPackagePoliciesStatsSearchStrategyProvider(this.endpointAppContextService); - plugins.data.search.registerSearchStrategy( - ENDPOINT_PACKAGE_POLICIES_STATS_STRATEGY, - endpointPackagePoliciesStatsStrategy - ); + const securitySolutionSearchStrategy = securitySolutionSearchStrategyProvider( + depsStart.data, + this.endpointContext, + depsStart.spaces?.spacesService?.getSpaceId, + ruleDataClient + ); - const securitySolutionSearchStrategy = securitySolutionSearchStrategyProvider( - depsStart.data, - this.endpointContext, - depsStart.spaces?.spacesService?.getSpaceId, - ruleDataClient - ); + plugins.data.search.registerSearchStrategy( + 'securitySolutionSearchStrategy', + securitySolutionSearchStrategy + ); + const endpointSearchStrategy = endpointSearchStrategyProvider( + depsStart.data, + this.endpointContext + ); - plugins.data.search.registerSearchStrategy( - 'securitySolutionSearchStrategy', - securitySolutionSearchStrategy - ); - const endpointSearchStrategy = endpointSearchStrategyProvider( - depsStart.data, - this.endpointContext - ); + plugins.data.search.registerSearchStrategy( + ENDPOINT_SEARCH_STRATEGY, + endpointSearchStrategy + ); - plugins.data.search.registerSearchStrategy(ENDPOINT_SEARCH_STRATEGY, endpointSearchStrategy); - - /** - * Register a config for the security guide - */ - if (depsStart.cloudExperiments && i18n.getLocale() === 'en') { - try { - depsStart.cloudExperiments - .getVariation('security-solutions.guided-onboarding-content', defaultGuideTranslations) - .then((variation) => { - plugins.guidedOnboarding?.registerGuideConfig( - siemGuideId, - getSiemGuideConfig(variation) - ); - }); - } catch { + /** + * Register a config for the security guide + */ + if (depsStart.cloudExperiments && i18n.getLocale() === 'en') { + try { + const variation = await depsStart.cloudExperiments.getVariation( + 'security-solutions.guided-onboarding-content', + defaultGuideTranslations + ); + plugins.guidedOnboarding?.registerGuideConfig( + siemGuideId, + getSiemGuideConfig(variation) + ); + } catch { + plugins.guidedOnboarding?.registerGuideConfig( + siemGuideId, + getSiemGuideConfig(defaultGuideTranslations) + ); + } + } else { plugins.guidedOnboarding?.registerGuideConfig( siemGuideId, getSiemGuideConfig(defaultGuideTranslations) ); } - } else { - plugins.guidedOnboarding?.registerGuideConfig( - siemGuideId, - getSiemGuideConfig(defaultGuideTranslations) - ); - } - }); + }) + .catch(() => {}); // it shouldn't reject, but just in case setIsElasticCloudDeployment(plugins.cloud.isCloudEnabled ?? false); @@ -586,29 +592,32 @@ export class Plugin implements ISecuritySolutionPlugin { }); // Migrate artifacts to fleet and then start the manifest task after that is done - plugins.fleet.fleetSetupCompleted().then(() => { - if (this.manifestTask) { - logger.info('Dependent plugin setup complete - Starting ManifestTask'); - this.manifestTask.start({ - taskManager, - }); - } else { - logger.error(new Error('User artifacts task not available.')); - } + plugins.fleet + .fleetSetupCompleted() + .then(async () => { + if (this.manifestTask) { + logger.info('Dependent plugin setup complete - Starting ManifestTask'); + await this.manifestTask.start({ + taskManager, + }); + } else { + logger.error(new Error('User artifacts task not available.')); + } - turnOffPolicyProtectionsIfNotSupported( - core.elasticsearch.client.asInternalUser, - endpointFleetServicesFactory.asInternalUser(), - productFeaturesService, - logger - ); + await turnOffPolicyProtectionsIfNotSupported( + core.elasticsearch.client.asInternalUser, + endpointFleetServicesFactory.asInternalUser(), + productFeaturesService, + logger + ); - turnOffAgentPolicyFeatures( - endpointFleetServicesFactory.asInternalUser(), - productFeaturesService, - logger - ); - }); + await turnOffAgentPolicyFeatures( + endpointFleetServicesFactory.asInternalUser(), + productFeaturesService, + logger + ); + }) + .catch(() => {}); // License related start licenseService.start(this.licensing$); @@ -653,22 +662,26 @@ export class Plugin implements ISecuritySolutionPlugin { }); if (plugins.taskManager) { - this.completeExternalResponseActionsTask.start({ - taskManager: plugins.taskManager, - esClient: core.elasticsearch.client.asInternalUser, - }); + this.completeExternalResponseActionsTask + .start({ + taskManager: plugins.taskManager, + esClient: core.elasticsearch.client.asInternalUser, + }) + .catch(() => {}); // it shouldn't refuse, but just in case } - this.telemetryReceiver.start( - core, - (type: string) => core.savedObjects.getIndexForType(type), - DEFAULT_ALERTS_INDEX, - this.endpointAppContextService, - exceptionListClient, - packageService - ); + this.telemetryReceiver + .start( + core, + (type: string) => core.savedObjects.getIndexForType(type), + DEFAULT_ALERTS_INDEX, + this.endpointAppContextService, + exceptionListClient, + packageService + ) + .catch(() => {}); - artifactService.start(this.telemetryReceiver); + artifactService.start(this.telemetryReceiver).catch(() => {}); this.asyncTelemetryEventsSender.start(plugins.telemetry); @@ -681,8 +694,8 @@ export class Plugin implements ISecuritySolutionPlugin { const endpointPkgInstallationPromise = this.endpointContext.service .getInternalFleetServices() .packages.getInstallation(FLEET_ENDPOINT_PACKAGE); - Promise.all([endpointPkgInstallationPromise, plugins.fleet?.fleetSetupCompleted()]).then( - ([endpointPkgInstallation]) => { + Promise.all([endpointPkgInstallationPromise, plugins.fleet?.fleetSetupCompleted()]) + .then(async ([endpointPkgInstallation]) => { if (plugins.taskManager) { if ( endpointPkgInstallation?.version && @@ -691,10 +704,10 @@ export class Plugin implements ISecuritySolutionPlugin { return; } - this.checkMetadataTransformsTask?.start({ taskManager: plugins.taskManager }); + await this.checkMetadataTransformsTask?.start({ taskManager: plugins.taskManager }); } - } - ); + }) + .catch(() => {}); // it shouldn't reject, but just in case if (registerIngestCallback) { registerIngestCallback( @@ -727,11 +740,11 @@ export class Plugin implements ISecuritySolutionPlugin { public stop() { this.logger.debug('Stopping plugin'); - this.asyncTelemetryEventsSender.stop(); + this.asyncTelemetryEventsSender.stop().catch(() => {}); this.telemetryEventsSender.stop(); this.endpointAppContextService.stop(); this.policyWatcher?.stop(); - this.completeExternalResponseActionsTask.stop(); + this.completeExternalResponseActionsTask.stop().catch(() => {}); licenseService.stop(); } } diff --git a/x-pack/plugins/security_solution/server/usage/queries/get_case_comments.ts b/x-pack/plugins/security_solution/server/usage/queries/get_case_comments.ts index 43acb1db00c1b..f74642507de34 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/get_case_comments.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/get_case_comments.ts @@ -50,7 +50,7 @@ export const getCaseComments = async ({ } try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal diff --git a/x-pack/plugins/security_solution/server/usage/queries/get_detection_rules.ts b/x-pack/plugins/security_solution/server/usage/queries/get_detection_rules.ts index 3452a364503ce..ae0cb67e02423 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/get_detection_rules.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/get_detection_rules.ts @@ -74,7 +74,7 @@ export const getDetectionRules = async ({ } try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal diff --git a/x-pack/plugins/security_solution/server/usage/queries/legacy_get_rule_actions.ts b/x-pack/plugins/security_solution/server/usage/queries/legacy_get_rule_actions.ts index 9b7140d734d16..c4b795b608466 100644 --- a/x-pack/plugins/security_solution/server/usage/queries/legacy_get_rule_actions.ts +++ b/x-pack/plugins/security_solution/server/usage/queries/legacy_get_rule_actions.ts @@ -61,7 +61,7 @@ export const legacyGetRuleActions = async ({ } try { - finder.close(); + await finder.close(); } catch (exception) { // This is just a pre-caution in case the finder does a throw we don't want to blow up // the response. We have seen this within e2e test containers but nothing happen in normal diff --git a/x-pack/plugins/security_solution_serverless/server/plugin.ts b/x-pack/plugins/security_solution_serverless/server/plugin.ts index cc89c3ce76e09..2bf9e901a4a24 100644 --- a/x-pack/plugins/security_solution_serverless/server/plugin.ts +++ b/x-pack/plugins/security_solution_serverless/server/plugin.ts @@ -125,23 +125,27 @@ export class SecuritySolutionServerlessPlugin const internalESClient = coreStart.elasticsearch.client.asInternalUser; const internalSOClient = coreStart.savedObjects.createInternalRepository(); - this.cloudSecurityUsageReportingTask?.start({ - taskManager: pluginsSetup.taskManager, - interval: cloudSecurityMetringTaskProperties.interval, - }); - - this.endpointUsageReportingTask?.start({ - taskManager: pluginsSetup.taskManager, - interval: ENDPOINT_METERING_TASK.INTERVAL, - }); - - this.nlpCleanupTask?.start({ taskManager: pluginsSetup.taskManager }); + this.cloudSecurityUsageReportingTask + ?.start({ + taskManager: pluginsSetup.taskManager, + interval: cloudSecurityMetringTaskProperties.interval, + }) + .catch(() => {}); + + this.endpointUsageReportingTask + ?.start({ + taskManager: pluginsSetup.taskManager, + interval: ENDPOINT_METERING_TASK.INTERVAL, + }) + .catch(() => {}); + + this.nlpCleanupTask?.start({ taskManager: pluginsSetup.taskManager }).catch(() => {}); setEndpointPackagePolicyServerlessFlag( internalSOClient, internalESClient, pluginsSetup.fleet.packagePolicyService - ); + ).catch(() => {}); return {}; } diff --git a/x-pack/plugins/serverless_search/server/lib/indices/fetch_index.test.ts b/x-pack/plugins/serverless_search/server/lib/indices/fetch_index.test.ts index 88edecd4cfd9d..75bc95365bb04 100644 --- a/x-pack/plugins/serverless_search/server/lib/indices/fetch_index.test.ts +++ b/x-pack/plugins/serverless_search/server/lib/indices/fetch_index.test.ts @@ -61,13 +61,13 @@ describe('fetch index lib function', () => { jest.clearAllMocks(); }); - it('should return index if all client calls succeed', () => { + it('should return index if all client calls succeed', async () => { mockClient.indices.get.mockResolvedValue({ ...regularIndexResponse }); mockClient.indices.stats.mockResolvedValue(regularIndexStatsResponse); mockClient.count.mockResolvedValue(indexCountResponse); (fetchConnectorByIndexName as unknown as jest.Mock).mockResolvedValue(indexConnector); - expect(fetchIndex(client(), indexName)).resolves.toMatchObject({ + await expect(fetchIndex(client(), indexName)).resolves.toMatchObject({ index: { aliases: {}, count: 100, @@ -77,7 +77,7 @@ describe('fetch index lib function', () => { }); }); - it('should throw an error if get index rejects', () => { + it('should throw an error if get index rejects', async () => { const expectedError = new Error('Boom!'); mockClient.indices.get.mockRejectedValue(expectedError); @@ -85,10 +85,10 @@ describe('fetch index lib function', () => { mockClient.count.mockResolvedValue(indexCountResponse); (fetchConnectorByIndexName as unknown as jest.Mock).mockResolvedValue(indexConnector); - expect(fetchIndex(client(), indexName)).rejects.toEqual(expectedError); + await expect(fetchIndex(client(), indexName)).rejects.toEqual(expectedError); }); - it('should return partial data if index stats rejects', () => { + it('should return partial data if index stats rejects', async () => { const expectedError = new Error('Boom!'); mockClient.indices.get.mockResolvedValue({ ...regularIndexResponse }); @@ -96,7 +96,7 @@ describe('fetch index lib function', () => { mockClient.count.mockResolvedValue(indexCountResponse); (fetchConnectorByIndexName as unknown as jest.Mock).mockResolvedValue(indexConnector); - expect(fetchIndex(client(), indexName)).resolves.toMatchObject({ + await expect(fetchIndex(client(), indexName)).resolves.toMatchObject({ index: { aliases: {}, count: 100, @@ -105,7 +105,7 @@ describe('fetch index lib function', () => { }); }); - it('should return partial data if index count rejects', () => { + it('should return partial data if index count rejects', async () => { const expectedError = new Error('Boom!'); mockClient.indices.get.mockResolvedValue({ ...regularIndexResponse }); @@ -113,7 +113,7 @@ describe('fetch index lib function', () => { mockClient.count.mockRejectedValue(expectedError); (fetchConnectorByIndexName as unknown as jest.Mock).mockResolvedValue(indexConnector); - expect(fetchIndex(client(), indexName)).resolves.toMatchObject({ + await expect(fetchIndex(client(), indexName)).resolves.toMatchObject({ index: { aliases: {}, count: 0, @@ -123,7 +123,7 @@ describe('fetch index lib function', () => { }); }); - it('should return partial data if fetch connector rejects', () => { + it('should return partial data if fetch connector rejects', async () => { const expectedError = new Error('Boom!'); mockClient.indices.get.mockResolvedValue({ ...regularIndexResponse }); @@ -131,7 +131,7 @@ describe('fetch index lib function', () => { mockClient.count.mockResolvedValue(indexCountResponse); (fetchConnectorByIndexName as unknown as jest.Mock).mockRejectedValue(expectedError); - expect(fetchIndex(client(), indexName)).resolves.toMatchObject({ + await expect(fetchIndex(client(), indexName)).resolves.toMatchObject({ index: { aliases: {}, count: 100, diff --git a/x-pack/plugins/serverless_search/server/plugin.ts b/x-pack/plugins/serverless_search/server/plugin.ts index a7b779a1239c7..0601b099d8a0d 100644 --- a/x-pack/plugins/serverless_search/server/plugin.ts +++ b/x-pack/plugins/serverless_search/server/plugin.ts @@ -34,7 +34,7 @@ export interface RouteDependencies { http: CoreSetup['http']; logger: Logger; router: IRouter; - security: SecurityPluginStart; + getSecurity: () => Promise; } export class ServerlessSearchPlugin @@ -49,7 +49,6 @@ export class ServerlessSearchPlugin // @ts-ignore config is not used for now private readonly config: ServerlessSearchConfig; private readonly logger: Logger; - private security?: SecurityPluginStart; constructor(initializerContext: PluginInitializerContext) { this.config = initializerContext.config.get(); @@ -82,25 +81,23 @@ export class ServerlessSearchPlugin { serverless, usageCollection }: SetupDependencies ) { const router = http.createRouter(); - getStartServices().then(([, { security }]) => { - this.security = security; - const dependencies = { - http, - logger: this.logger, - router, - security: this.security, - }; + const dependencies = { + http, + logger: this.logger, + router, + getSecurity: async () => { + const [, { security }] = await getStartServices(); + return security; + }, + }; - registerApiKeyRoutes(dependencies); - registerConnectorsRoutes(dependencies); - registerIndicesRoutes(dependencies); - registerMappingRoutes(dependencies); - }); + registerApiKeyRoutes(dependencies); + registerConnectorsRoutes(dependencies); + registerIndicesRoutes(dependencies); + registerMappingRoutes(dependencies); if (usageCollection) { - getStartServices().then(() => { - registerTelemetryUsageCollector(usageCollection, this.logger); - }); + registerTelemetryUsageCollector(usageCollection, this.logger); } serverless.setupProjectSettings(SEARCH_PROJECT_SETTINGS); @@ -108,7 +105,7 @@ export class ServerlessSearchPlugin } public start(core: CoreStart, { dataViews }: StartDependencies) { - this.createDefaultDataView(core, dataViews); + this.createDefaultDataView(core, dataViews).catch(() => {}); return {}; } diff --git a/x-pack/plugins/serverless_search/server/routes/api_key_routes.ts b/x-pack/plugins/serverless_search/server/routes/api_key_routes.ts index 9753420234208..397145ac647b2 100644 --- a/x-pack/plugins/serverless_search/server/routes/api_key_routes.ts +++ b/x-pack/plugins/serverless_search/server/routes/api_key_routes.ts @@ -8,7 +8,7 @@ import { schema } from '@kbn/config-schema'; import { RouteDependencies } from '../plugin'; -export const registerApiKeyRoutes = ({ logger, router, security }: RouteDependencies) => { +export const registerApiKeyRoutes = ({ logger, router, getSecurity }: RouteDependencies) => { router.get( { path: '/internal/serverless_search/api_keys', @@ -16,6 +16,7 @@ export const registerApiKeyRoutes = ({ logger, router, security }: RouteDependen }, async (context, request, response) => { const { client } = (await context.core).elasticsearch; + const security = await getSecurity(); const user = security.authc.getCurrentUser(request); if (user) { const apiKeys = await client.asCurrentUser.security.getApiKey({ username: user.username }); @@ -37,6 +38,7 @@ export const registerApiKeyRoutes = ({ logger, router, security }: RouteDependen }, }, async (context, request, response) => { + const security = await getSecurity(); const result = await security.authc.apiKeys.create(request, request.body); if (result) { const apiKey = { ...result, beats_logstash_format: `${result.id}:${result.api_key}` }; diff --git a/x-pack/plugins/serverless_search/server/routes/indices_routes.ts b/x-pack/plugins/serverless_search/server/routes/indices_routes.ts index 1e54a64642115..0cf303b677454 100644 --- a/x-pack/plugins/serverless_search/server/routes/indices_routes.ts +++ b/x-pack/plugins/serverless_search/server/routes/indices_routes.ts @@ -14,7 +14,7 @@ import { fetchIndices } from '../lib/indices/fetch_indices'; import { fetchIndex } from '../lib/indices/fetch_index'; import { RouteDependencies } from '../plugin'; -export const registerIndicesRoutes = ({ router, security }: RouteDependencies) => { +export const registerIndicesRoutes = ({ router, getSecurity }: RouteDependencies) => { router.get( { path: '/internal/serverless_search/indices', @@ -28,6 +28,7 @@ export const registerIndicesRoutes = ({ router, security }: RouteDependencies) = }, async (context, request, response) => { const client = (await context.core).elasticsearch.client.asCurrentUser; + const security = await getSecurity(); const user = security.authc.getCurrentUser(request); if (!user) { diff --git a/x-pack/plugins/spaces/server/default_space/create_default_space.test.ts b/x-pack/plugins/spaces/server/default_space/create_default_space.test.ts index 25a98d09a2bb8..e7a7b51b278d1 100644 --- a/x-pack/plugins/spaces/server/default_space/create_default_space.test.ts +++ b/x-pack/plugins/spaces/server/default_space/create_default_space.test.ts @@ -106,7 +106,7 @@ test(`it throws all other errors from the saved objects client when checking for simulateGetErrorCondition: true, }); - expect(createDefaultSpace(deps)).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(createDefaultSpace(deps)).rejects.toThrowErrorMatchingInlineSnapshot( `"unit test: unexpected exception condition"` ); }); @@ -131,7 +131,7 @@ test(`it throws other errors if there is an error creating the default space`, a simulateCreateErrorCondition: true, }); - expect(createDefaultSpace(deps)).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(createDefaultSpace(deps)).rejects.toThrowErrorMatchingInlineSnapshot( `"unit test: some other unexpected error"` ); }); diff --git a/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.ts b/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.ts index 0c866de5bde66..e772ad389e8f9 100644 --- a/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.ts +++ b/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.ts @@ -24,7 +24,7 @@ const areObjectsUnique = (objects: SavedObjectIdentifier[]) => _.uniqBy(objects, (o: SavedObjectIdentifier) => `${o.type}:${o.id}`).length === objects.length; export function initCopyToSpacesApi(deps: ExternalRouteDeps) { - const { router, getSpacesService, usageStatsServicePromise, getStartServices } = deps; + const { router, getSpacesService, usageStatsServicePromise, getStartServices, log } = deps; const usageStatsClientPromise = usageStatsServicePromise.then(({ getClient }) => getClient()); router.post( @@ -96,14 +96,20 @@ export function initCopyToSpacesApi(deps: ExternalRouteDeps) { } = request.body; const { headers } = request; - usageStatsClientPromise.then((usageStatsClient) => - usageStatsClient.incrementCopySavedObjects({ - headers, - createNewCopies, - overwrite, - compatibilityMode, - }) - ); + usageStatsClientPromise + .then((usageStatsClient) => + usageStatsClient.incrementCopySavedObjects({ + headers, + createNewCopies, + overwrite, + compatibilityMode, + }) + ) + .catch((err) => { + log.error( + `Failed to report usage statistics for the copy saved objects route: ${err.message}` + ); + }); try { const copySavedObjectsToSpaces = copySavedObjectsToSpacesFactory( @@ -198,13 +204,19 @@ export function initCopyToSpacesApi(deps: ExternalRouteDeps) { request.body; const { headers } = request; - usageStatsClientPromise.then((usageStatsClient) => - usageStatsClient.incrementResolveCopySavedObjectsErrors({ - headers, - createNewCopies, - compatibilityMode, - }) - ); + usageStatsClientPromise + .then((usageStatsClient) => + usageStatsClient.incrementResolveCopySavedObjectsErrors({ + headers, + createNewCopies, + compatibilityMode, + }) + ) + .catch((err) => { + log.error( + `Failed to report usage statistics for the resolve copy saved objects errors route: ${err.message}` + ); + }); const resolveCopySavedObjectsToSpacesConflicts = resolveCopySavedObjectsToSpacesConflictsFactory(startServices.savedObjects, request); diff --git a/x-pack/plugins/spaces/server/routes/api/external/disable_legacy_url_aliases.ts b/x-pack/plugins/spaces/server/routes/api/external/disable_legacy_url_aliases.ts index 725d0c87612fb..d708618f43870 100644 --- a/x-pack/plugins/spaces/server/routes/api/external/disable_legacy_url_aliases.ts +++ b/x-pack/plugins/spaces/server/routes/api/external/disable_legacy_url_aliases.ts @@ -12,7 +12,7 @@ import { wrapError } from '../../../lib/errors'; import { createLicensedRouteHandler } from '../../lib'; export function initDisableLegacyUrlAliasesApi(deps: ExternalRouteDeps) { - const { router, getSpacesService, usageStatsServicePromise } = deps; + const { router, getSpacesService, usageStatsServicePromise, log } = deps; const usageStatsClientPromise = usageStatsServicePromise.then(({ getClient }) => getClient()); router.post( @@ -35,9 +35,13 @@ export function initDisableLegacyUrlAliasesApi(deps: ExternalRouteDeps) { const { aliases } = request.body; - usageStatsClientPromise.then((usageStatsClient) => - usageStatsClient.incrementDisableLegacyUrlAliases() - ); + usageStatsClientPromise + .then((usageStatsClient) => usageStatsClient.incrementDisableLegacyUrlAliases()) + .catch((err) => { + log.error( + `Failed to report usage statistics for the disable legacy URL aliases route: ${err.message}` + ); + }); try { await spacesClient.disableLegacyUrlAliases(aliases); diff --git a/x-pack/plugins/spaces/server/spaces_client/spaces_client.test.ts b/x-pack/plugins/spaces/server/spaces_client/spaces_client.test.ts index 67c926229601b..0f689cd492e11 100644 --- a/x-pack/plugins/spaces/server/spaces_client/spaces_client.test.ts +++ b/x-pack/plugins/spaces/server/spaces_client/spaces_client.test.ts @@ -251,7 +251,7 @@ describe('#create', () => { const client = new SpacesClient(mockDebugLogger, mockConfig, mockCallWithRequestRepository, []); - expect(client.create(spaceToCreate)).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(client.create(spaceToCreate)).rejects.toThrowErrorMatchingInlineSnapshot( `"Unable to create Space, this exceeds the maximum number of spaces set by the xpack.spaces.maxSpaces setting"` ); @@ -321,7 +321,7 @@ describe('#create', () => { [] ); - expect( + await expect( client.create({ ...spaceToCreate, disabledFeatures: ['some-feature'] }) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Unable to create Space, the disabledFeatures array must be empty when xpack.spaces.allowFeatureVisibility setting is disabled"` @@ -429,7 +429,7 @@ describe('#update', () => { ); const id = savedObject.id; - expect( + await expect( client.update(id, { ...spaceToUpdate, disabledFeatures: ['some-feature'] }) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Unable to update Space, the disabledFeatures array must be empty when xpack.spaces.allowFeatureVisibility setting is disabled"` @@ -475,7 +475,7 @@ describe('#delete', () => { const client = new SpacesClient(mockDebugLogger, mockConfig, mockCallWithRequestRepository, []); - expect(client.delete(id)).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(client.delete(id)).rejects.toThrowErrorMatchingInlineSnapshot( `"The foo space cannot be deleted because it is reserved."` ); diff --git a/x-pack/plugins/stack_alerts/server/rule_types/geo_containment/lib/get_shape_filters.test.ts b/x-pack/plugins/stack_alerts/server/rule_types/geo_containment/lib/get_shape_filters.test.ts index a133d65d871aa..5b48bd6512e9d 100644 --- a/x-pack/plugins/stack_alerts/server/rule_types/geo_containment/lib/get_shape_filters.test.ts +++ b/x-pack/plugins/stack_alerts/server/rule_types/geo_containment/lib/get_shape_filters.test.ts @@ -129,7 +129,7 @@ describe('getShapeFilters', () => { throw new Error('Simulated elasticsearch search error'); }, } as unknown as ElasticsearchClient; - expect(async () => { + await expect(async () => { await getShapeFilters(boundariesRequestMeta, mockEsClient); }).rejects.toThrow(); }); @@ -144,7 +144,7 @@ describe('getShapeFilters', () => { }; }, } as unknown as ElasticsearchClient; - expect(async () => { + await expect(async () => { await getShapeFilters(boundariesRequestMeta, mockEsClient); }).rejects.toThrow(); }); diff --git a/x-pack/plugins/stack_connectors/server/connector_types/servicenow_sir/service.ts b/x-pack/plugins/stack_connectors/server/connector_types/servicenow_sir/service.ts index 1c3972dd680b2..69836a5b95e29 100644 --- a/x-pack/plugins/stack_connectors/server/connector_types/servicenow_sir/service.ts +++ b/x-pack/plugins/stack_connectors/server/connector_types/servicenow_sir/service.ts @@ -38,7 +38,7 @@ export const createExternalService: ServiceFactory = ({ }); const _addObservable = async (data: Observable | Observable[], url: string) => { - snService.checkIfApplicationIsInstalled(); + await snService.checkIfApplicationIsInstalled(); const res = await request({ axios: axiosInstance, diff --git a/x-pack/plugins/task_manager/server/buffered_task_store.test.ts b/x-pack/plugins/task_manager/server/buffered_task_store.test.ts index 458b9d4c4bd2a..fa7a59478728d 100644 --- a/x-pack/plugins/task_manager/server/buffered_task_store.test.ts +++ b/x-pack/plugins/task_manager/server/buffered_task_store.test.ts @@ -135,7 +135,7 @@ describe('Buffered Task Store', () => { bufferedStore.update(tasks[2], { validate: true }), ]; expect(await results[0]).toMatchObject(tasks[0]); - expect(results[1]).rejects.toMatchInlineSnapshot(` + await expect(results[1]).rejects.toMatchInlineSnapshot(` Object { "error": Object { "error": "Oh no, something went terribly wrong", diff --git a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts index 99bb7c5b84274..00dd7e00d27e2 100644 --- a/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts +++ b/x-pack/plugins/task_manager/server/lib/bulk_operation_buffer.test.ts @@ -69,28 +69,21 @@ describe('Bulk Operation Buffer', () => { const task3 = createTask(); const task4 = createTask(); - return new Promise((resolve) => { - Promise.all([bufferedUpdate(task1), bufferedUpdate(task2)]).then((_) => { - expect(bulkUpdate).toHaveBeenCalledTimes(1); - expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); - expect(bulkUpdate).not.toHaveBeenCalledWith([task3, task4]); - }); - - setTimeout(() => { - // on next tick - expect(bulkUpdate).toHaveBeenCalledTimes(1); - Promise.all([bufferedUpdate(task3), bufferedUpdate(task4)]).then((_) => { - expect(bulkUpdate).toHaveBeenCalledTimes(2); - expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); - }); - - setTimeout(() => { - // on next tick - expect(bulkUpdate).toHaveBeenCalledTimes(2); - resolve(); - }, bufferMaxDuration * 1.1); - }, bufferMaxDuration * 1.1); - }); + await Promise.all([bufferedUpdate(task1), bufferedUpdate(task2)]); + expect(bulkUpdate).toHaveBeenCalledTimes(1); + expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); + expect(bulkUpdate).not.toHaveBeenCalledWith([task3, task4]); + + await new Promise((resolve) => setTimeout(resolve, bufferMaxDuration * 1.1)); + // on next tick + expect(bulkUpdate).toHaveBeenCalledTimes(1); + await Promise.all([bufferedUpdate(task3), bufferedUpdate(task4)]); + expect(bulkUpdate).toHaveBeenCalledTimes(2); + expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); + + await new Promise((resolve) => setTimeout(resolve, bufferMaxDuration * 1.1)); + // on next tick + expect(bulkUpdate).toHaveBeenCalledTimes(2); }); test('batch updates are executed once queue hits a certain bound', async () => { @@ -110,20 +103,19 @@ describe('Bulk Operation Buffer', () => { const task4 = createTask(); const task5 = createTask(); - return Promise.all([ + await Promise.all([ bufferedUpdate(task1), bufferedUpdate(task2), bufferedUpdate(task3), bufferedUpdate(task4), - ]).then(() => { - expect(bulkUpdate).toHaveBeenCalledTimes(2); - expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); - expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); - return bufferedUpdate(task5).then((_) => { - expect(bulkUpdate).toHaveBeenCalledTimes(3); - expect(bulkUpdate).toHaveBeenCalledWith([task5]); - }); - }); + ]); + expect(bulkUpdate).toHaveBeenCalledTimes(2); + expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); + expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); + + await bufferedUpdate(task5); + expect(bulkUpdate).toHaveBeenCalledTimes(3); + expect(bulkUpdate).toHaveBeenCalledWith([task5]); }); test('queue upper bound is reset after each flush', async () => { @@ -142,24 +134,17 @@ describe('Bulk Operation Buffer', () => { const task3 = createTask(); const task4 = createTask(); - return Promise.all([bufferedUpdate(task1), bufferedUpdate(task2)]).then(() => { - expect(bulkUpdate).toHaveBeenCalledTimes(1); - expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); - - return new Promise((resolve) => { - const futureUpdates = Promise.all([bufferedUpdate(task3), bufferedUpdate(task4)]); + await Promise.all([bufferedUpdate(task1), bufferedUpdate(task2)]); + expect(bulkUpdate).toHaveBeenCalledTimes(1); + expect(bulkUpdate).toHaveBeenCalledWith([task1, task2]); - setTimeout(() => { - expect(bulkUpdate).toHaveBeenCalledTimes(1); + const futureUpdates = Promise.all([bufferedUpdate(task3), bufferedUpdate(task4)]); + await new Promise((resolve) => setTimeout(resolve, bufferMaxDuration / 2)); + expect(bulkUpdate).toHaveBeenCalledTimes(1); - futureUpdates.then(() => { - expect(bulkUpdate).toHaveBeenCalledTimes(2); - expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); - resolve(); - }); - }, bufferMaxDuration / 2); - }); - }); + await futureUpdates; + expect(bulkUpdate).toHaveBeenCalledTimes(2); + expect(bulkUpdate).toHaveBeenCalledWith([task3, task4]); }); test('handles both resolutions and rejections at individual task level', async () => { diff --git a/x-pack/plugins/task_manager/server/lib/remove_if_exists.test.ts b/x-pack/plugins/task_manager/server/lib/remove_if_exists.test.ts index 748e529ef1446..1270f1aedae6f 100644 --- a/x-pack/plugins/task_manager/server/lib/remove_if_exists.test.ts +++ b/x-pack/plugins/task_manager/server/lib/remove_if_exists.test.ts @@ -38,7 +38,7 @@ describe('removeIfExists', () => { const error = SavedObjectsErrorHelpers.createInvalidVersionError(uuidv4()); ts.remove.mockRejectedValue(error); - expect(removeIfExists(ts, id)).rejects.toBe(error); + await expect(removeIfExists(ts, id)).rejects.toBe(error); expect(ts.remove).toHaveBeenCalledWith(id); }); diff --git a/x-pack/plugins/task_manager/server/lib/result_type.test.ts b/x-pack/plugins/task_manager/server/lib/result_type.test.ts index d35f00d30920c..4dc2f5f071278 100644 --- a/x-pack/plugins/task_manager/server/lib/result_type.test.ts +++ b/x-pack/plugins/task_manager/server/lib/result_type.test.ts @@ -17,12 +17,12 @@ describe(`Result`, () => { test(`unwraps Errs from the result`, async () => { const uniqueId = uuidv4(); - expect(unwrapPromise(Promise.resolve(asErr(uniqueId)))).rejects.toEqual(uniqueId); + await expect(unwrapPromise(Promise.resolve(asErr(uniqueId)))).rejects.toEqual(uniqueId); }); test(`unwraps Errs from the result when promise rejects`, async () => { const uniqueId = uuidv4(); - expect(unwrapPromise(Promise.reject(asErr(uniqueId)))).rejects.toEqual(uniqueId); + await expect(unwrapPromise(Promise.reject(asErr(uniqueId)))).rejects.toEqual(uniqueId); }); }); }); diff --git a/x-pack/plugins/task_manager/server/metrics/task_metrics_collector.ts b/x-pack/plugins/task_manager/server/metrics/task_metrics_collector.ts index d588a001693b9..2d87f789128cd 100644 --- a/x-pack/plugins/task_manager/server/metrics/task_metrics_collector.ts +++ b/x-pack/plugins/task_manager/server/metrics/task_metrics_collector.ts @@ -64,7 +64,7 @@ export class TaskManagerMetricsCollector implements ITaskEventEmitter {}); } } diff --git a/x-pack/plugins/task_manager/server/mocks.ts b/x-pack/plugins/task_manager/server/mocks.ts index 45a2f117167ca..71638bc883681 100644 --- a/x-pack/plugins/task_manager/server/mocks.ts +++ b/x-pack/plugins/task_manager/server/mocks.ts @@ -29,7 +29,7 @@ const createStartMock = () => { runSoon: jest.fn(), ephemeralRunNow: jest.fn(), ensureScheduled: jest.fn(), - removeIfExists: jest.fn(), + removeIfExists: jest.fn().mockResolvedValue(Promise.resolve()), // it's a promise and there are some places where it's followed by `.catch()` supportsEphemeralTasks: jest.fn(), bulkUpdateSchedules: jest.fn(), bulkSchedule: jest.fn(), diff --git a/x-pack/plugins/task_manager/server/polling/task_poller.ts b/x-pack/plugins/task_manager/server/polling/task_poller.ts index ff984a44f1aa0..570ecc8686693 100644 --- a/x-pack/plugins/task_manager/server/polling/task_poller.ts +++ b/x-pack/plugins/task_manager/server/polling/task_poller.ts @@ -72,7 +72,7 @@ export function createTaskPoller({ if (running) { // Set the next runCycle call timeoutId = setTimeout( - runCycle, + () => runCycle().catch(() => {}), Math.max(pollInterval - (Date.now() - start) + (pollIntervalDelay % pollInterval), 0) ); // Reset delay, it's designed to shuffle only once @@ -111,7 +111,7 @@ export function createTaskPoller({ start: () => { if (!running) { running = true; - runCycle(); + runCycle().catch(() => {}); // We need to subscribe shortly after start. Otherwise, the observables start emiting events // too soon for the task run statistics module to capture. setTimeout(() => subscribe(), 0); diff --git a/x-pack/plugins/task_manager/server/task_pool.ts b/x-pack/plugins/task_manager/server/task_pool.ts index a3a047cd735c9..c0784f0458f72 100644 --- a/x-pack/plugins/task_manager/server/task_pool.ts +++ b/x-pack/plugins/task_manager/server/task_pool.ts @@ -198,7 +198,8 @@ export class TaskPool { }) .then(() => { this.tasksInPool.delete(taskRunner.taskExecutionId); - }); + }) + .catch(() => {}); } private handleFailureOfMarkAsRunning(task: TaskRunner, err: Error) { @@ -227,14 +228,17 @@ export class TaskPool { } } - private async cancelTask(task: TaskRunner) { - try { - this.logger.debug(`Cancelling task ${task.toString()}.`); - this.tasksInPool.delete(task.taskExecutionId); - await task.cancel(); - } catch (err) { - this.logger.error(`Failed to cancel task ${task.toString()}: ${err}`); - } + private cancelTask(task: TaskRunner) { + // internally async (without rejections), but public-facing is synchronous + (async () => { + try { + this.logger.debug(`Cancelling task ${task.toString()}.`); + this.tasksInPool.delete(task.taskExecutionId); + await task.cancel(); + } catch (err) { + this.logger.error(`Failed to cancel task ${task.toString()}: ${err}`); + } + })().catch(() => {}); } } diff --git a/x-pack/plugins/task_manager/server/task_scheduling.test.ts b/x-pack/plugins/task_manager/server/task_scheduling.test.ts index f4c8c0d6b0880..36de95416e1ca 100644 --- a/x-pack/plugins/task_manager/server/task_scheduling.test.ts +++ b/x-pack/plugins/task_manager/server/task_scheduling.test.ts @@ -836,7 +836,8 @@ describe('TaskScheduling', () => { }); describe('ephemeralRunNow', () => { - test('runs a task ephemerally', async () => { + // https://github.com/elastic/kibana/issues/181847 + test.skip('runs a task ephemerally', async () => { const ephemeralEvents$ = new Subject(); const ephemeralTask = taskManagerMock.createTask({ state: { @@ -880,7 +881,7 @@ describe('TaskScheduling', () => { ) ); - expect(result).resolves.toEqual({ id: 'v4uuid', state: { foo: 'bar' } }); + await expect(result).resolves.toEqual({ id: 'v4uuid', state: { foo: 'bar' } }); }); test('rejects ephemeral task if lifecycle returns an error', async () => { @@ -924,7 +925,7 @@ describe('TaskScheduling', () => { ) ); - expect(result).rejects.toMatchInlineSnapshot( + await expect(result).rejects.toMatchInlineSnapshot( `[Error: Ephemeral Task of type foo was rejected]` ); }); @@ -946,7 +947,7 @@ describe('TaskScheduling', () => { }); const result = taskScheduling.ephemeralRunNow(ephemeralTask); - expect(result).rejects.toMatchInlineSnapshot( + await expect(result).rejects.toMatchInlineSnapshot( `[Error: Ephemeral Task of type foo was rejected because ephemeral tasks are not supported]` ); }); diff --git a/x-pack/plugins/task_manager/server/task_scheduling.ts b/x-pack/plugins/task_manager/server/task_scheduling.ts index 7cb13182820b7..c57e54c76a98d 100644 --- a/x-pack/plugins/task_manager/server/task_scheduling.ts +++ b/x-pack/plugins/task_manager/server/task_scheduling.ts @@ -414,9 +414,11 @@ export class TaskScheduling { }); if (cancel) { - cancel.then(() => { - subscription.unsubscribe(); - }); + cancel + .then(() => { + subscription.unsubscribe(); + }) + .catch(() => {}); } }); } diff --git a/x-pack/plugins/threat_intelligence/server/plugin.ts b/x-pack/plugins/threat_intelligence/server/plugin.ts index d6fb0cb20aeee..91690b266d564 100644 --- a/x-pack/plugins/threat_intelligence/server/plugin.ts +++ b/x-pack/plugins/threat_intelligence/server/plugin.ts @@ -30,7 +30,7 @@ export class ThreatIntelligencePlugin implements IThreatIntelligencePlugin { ) { this.logger.debug('setup'); - core.getStartServices().then(([_, { data: dataStartService }]) => { + void core.getStartServices().then(([_, { data: dataStartService }]) => { const threatIntelligenceSearchStrategy = threatIntelligenceSearchStrategyProvider(dataStartService); diff --git a/x-pack/plugins/timelines/server/plugin.ts b/x-pack/plugins/timelines/server/plugin.ts index 2f8406b2b5646..619c66a05ee30 100644 --- a/x-pack/plugins/timelines/server/plugin.ts +++ b/x-pack/plugins/timelines/server/plugin.ts @@ -29,7 +29,7 @@ export class TimelinesPlugin const IndexFields = indexFieldsProvider(core.getStartServices); // Register search strategy - core.getStartServices().then(([_, depsStart]) => { + void core.getStartServices().then(([_, depsStart]) => { const TimelineSearchStrategy = timelineSearchStrategyProvider( depsStart.data, this.logger, diff --git a/x-pack/plugins/transform/server/plugin.ts b/x-pack/plugins/transform/server/plugin.ts index 6188a809c910c..6ca3eb92388f3 100644 --- a/x-pack/plugins/transform/server/plugin.ts +++ b/x-pack/plugins/transform/server/plugin.ts @@ -71,32 +71,41 @@ export class TransformServerPlugin implements Plugin<{}, void, any, any> { ], }); - getStartServices().then(([coreStart, { dataViews, security: securityStart }]) => { - const license = new License({ - pluginId: PLUGIN.id, - minimumLicenseType: PLUGIN.minimumLicenseType, - defaultErrorMessage: i18n.translate('xpack.transform.licenseCheckErrorMessage', { - defaultMessage: 'License check failed', - }), - licensing, - logger: this.logger, - coreStart, - }); + registerRoutes({ + router: http.createRouter(), + getLicense: async () => { + const [coreStart] = await getStartServices(); + return new License({ + pluginId: PLUGIN.id, + minimumLicenseType: PLUGIN.minimumLicenseType, + defaultErrorMessage: i18n.translate('xpack.transform.licenseCheckErrorMessage', { + defaultMessage: 'License check failed', + }), + licensing, + logger: this.logger, + coreStart, + }); + }, + getDataViewsStart: async () => { + const [, { dataViews }] = await getStartServices(); + return dataViews; + }, + getCoreStart: async () => { + const [coreStart] = await getStartServices(); + return coreStart; + }, + getSecurity: async () => { + const [, { security }] = await getStartServices(); + return security; + }, + }); - registerRoutes({ - router: http.createRouter(), - license, - dataViews, - coreStart, - security: securityStart, + if (usageCollection) { + registerCollector(usageCollection, async () => { + const [coreStart] = await getStartServices(); + return coreStart.savedObjects.getIndexForType('alert'); }); - - const alertIndex = coreStart.savedObjects.getIndexForType('alert'); - - if (usageCollection) { - registerCollector(usageCollection, alertIndex); - } - }); + } if (alerting) { registerTransformHealthRuleType({ diff --git a/x-pack/plugins/transform/server/routes/api/audit_messages/register_route.ts b/x-pack/plugins/transform/server/routes/api/audit_messages/register_route.ts index e5357034a1cbd..be1c0ef34ccae 100644 --- a/x-pack/plugins/transform/server/routes/api/audit_messages/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/audit_messages/register_route.ts @@ -17,7 +17,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms Audit Messages * @@ -42,10 +42,13 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute< - TransformIdParamSchema, - GetTransformAuditMessagesQuerySchema, - undefined - >(routeHandler) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute< + TransformIdParamSchema, + GetTransformAuditMessagesQuerySchema, + undefined + >(routeHandler)(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/delete_transforms/register_route.ts b/x-pack/plugins/transform/server/routes/api/delete_transforms/register_route.ts index cdb58c02d9664..3646889f2c005 100644 --- a/x-pack/plugins/transform/server/routes/api/delete_transforms/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/delete_transforms/register_route.ts @@ -16,7 +16,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandlerFactory } from './route_handler_factory'; export function registerRoute(routeDependencies: RouteDependencies) { - const { router, license } = routeDependencies; + const { router, getLicense } = routeDependencies; /** * @apiGroup Transforms * @@ -40,8 +40,11 @@ export function registerRoute(routeDependencies: RouteDependencies) { }, }, }, - license.guardApiRoute( - routeHandlerFactory(routeDependencies) - ) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandlerFactory(routeDependencies) + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/delete_transforms/route_handler_factory.ts b/x-pack/plugins/transform/server/routes/api/delete_transforms/route_handler_factory.ts index c20dee6c68b98..c55fa798d24eb 100644 --- a/x-pack/plugins/transform/server/routes/api/delete_transforms/route_handler_factory.ts +++ b/x-pack/plugins/transform/server/routes/api/delete_transforms/route_handler_factory.ts @@ -24,13 +24,14 @@ export const routeHandlerFactory: ( DeleteTransformsRequestSchema, TransformRequestHandlerContext > = - ({ coreStart, dataViews }) => + ({ getCoreStart, getDataViewsStart }) => async (ctx, req, res) => { try { - const { savedObjects, elasticsearch } = coreStart; + const { savedObjects, elasticsearch } = await getCoreStart(); const savedObjectsClient = savedObjects.getScopedClient(req); const esClient = elasticsearch.client.asScoped(req).asCurrentUser; + const dataViews = await getDataViewsStart(); const dataViewsService = await dataViews.dataViewsServiceFactory( savedObjectsClient, esClient, diff --git a/x-pack/plugins/transform/server/routes/api/field_histograms/register_route.ts b/x-pack/plugins/transform/server/routes/api/field_histograms/register_route.ts index 4f8819b865f86..d1949f06e1ca5 100644 --- a/x-pack/plugins/transform/server/routes/api/field_histograms/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/field_histograms/register_route.ts @@ -15,7 +15,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { router.versioned .post({ path: addInternalBasePath('field_histograms/{dataViewTitle}'), @@ -31,8 +31,11 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute( - routeHandler - ) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandler + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/reauthorize_transforms/register_route.ts b/x-pack/plugins/transform/server/routes/api/reauthorize_transforms/register_route.ts index 017aa98e76304..fc5128e0971b6 100644 --- a/x-pack/plugins/transform/server/routes/api/reauthorize_transforms/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/reauthorize_transforms/register_route.ts @@ -14,7 +14,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandlerFactory } from './route_handler_factory'; export function registerRoute(routeDependencies: RouteDependencies) { - const { router, license } = routeDependencies; + const { router, getLicense } = routeDependencies; /** * @apiGroup Reauthorize transforms with API key generated from currently logged in user * @api {post} /internal/transform/reauthorize_transforms Post reauthorize transforms @@ -38,8 +38,11 @@ export function registerRoute(routeDependencies: RouteDependencies) { }, }, }, - license.guardApiRoute( - routeHandlerFactory(routeDependencies) - ) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandlerFactory(routeDependencies) + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/reauthorize_transforms/route_handler_factory.ts b/x-pack/plugins/transform/server/routes/api/reauthorize_transforms/route_handler_factory.ts index acefdec0257a9..aa63936a3f6e7 100644 --- a/x-pack/plugins/transform/server/routes/api/reauthorize_transforms/route_handler_factory.ts +++ b/x-pack/plugins/transform/server/routes/api/reauthorize_transforms/route_handler_factory.ts @@ -26,7 +26,9 @@ export const routeHandlerFactory: ( StartTransformsRequestSchema, TransformRequestHandlerContext > = (routeDependencies) => async (ctx, req, res) => { - const { coreStart, security: securityStart } = routeDependencies; + const { getCoreStart, getSecurity } = routeDependencies; + const coreStart = await getCoreStart(); + const securityStart = await getSecurity(); try { const transformsInfo = req.body; diff --git a/x-pack/plugins/transform/server/routes/api/reset_transforms/register_route.ts b/x-pack/plugins/transform/server/routes/api/reset_transforms/register_route.ts index cae6245455810..adbe55b8e828d 100644 --- a/x-pack/plugins/transform/server/routes/api/reset_transforms/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/reset_transforms/register_route.ts @@ -15,7 +15,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -39,6 +39,11 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute(routeHandler) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandler + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/schedule_now_transforms/register_route.ts b/x-pack/plugins/transform/server/routes/api/schedule_now_transforms/register_route.ts index cf19b56c316f1..0ec8808ae2ecf 100644 --- a/x-pack/plugins/transform/server/routes/api/schedule_now_transforms/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/schedule_now_transforms/register_route.ts @@ -15,7 +15,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -39,6 +39,11 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute(routeHandler) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandler + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/start_transforms/register_route.ts b/x-pack/plugins/transform/server/routes/api/start_transforms/register_route.ts index 5cba3a5a01d70..5ce3de48e63a3 100644 --- a/x-pack/plugins/transform/server/routes/api/start_transforms/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/start_transforms/register_route.ts @@ -15,7 +15,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -39,6 +39,11 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute(routeHandler) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandler + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/stop_transforms/register_route.ts b/x-pack/plugins/transform/server/routes/api/stop_transforms/register_route.ts index df9498f9ae033..b859ee4743c40 100644 --- a/x-pack/plugins/transform/server/routes/api/stop_transforms/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/stop_transforms/register_route.ts @@ -15,7 +15,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -39,6 +39,11 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute(routeHandler) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandler + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/transforms_all/register_route.ts b/x-pack/plugins/transform/server/routes/api/transforms_all/register_route.ts index e808e0e8fafc2..29cbd34bffd68 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_all/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_all/register_route.ts @@ -13,7 +13,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -29,13 +29,16 @@ export function registerRoute({ router, license }: RouteDependencies) { path: addInternalBasePath('transforms'), access: 'internal', }) - .addVersion( + .addVersion( { version: '1', validate: false, }, - license.guardApiRoute( - routeHandler - ) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandler + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/transforms_create/register_route.ts b/x-pack/plugins/transform/server/routes/api/transforms_create/register_route.ts index f6be9e18893f2..9237977118d05 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_create/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_create/register_route.ts @@ -25,7 +25,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandlerFactory } from './route_handler_factory'; export function registerRoute(routeDependencies: RouteDependencies) { - const { router, license } = routeDependencies; + const { router, getLicense } = routeDependencies; /** * @apiGroup Transforms @@ -54,10 +54,13 @@ export function registerRoute(routeDependencies: RouteDependencies) { }, }, }, - license.guardApiRoute< - TransformIdParamSchema, - DataViewCreateQuerySchema, - PutTransformsRequestSchema - >(routeHandlerFactory(routeDependencies)) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute< + TransformIdParamSchema, + DataViewCreateQuerySchema, + PutTransformsRequestSchema + >(routeHandlerFactory(routeDependencies))(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/transforms_create/route_handler_factory.ts b/x-pack/plugins/transform/server/routes/api/transforms_create/route_handler_factory.ts index 8ca98efe3cb54..0baa019808e8b 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_create/route_handler_factory.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_create/route_handler_factory.ts @@ -31,7 +31,9 @@ export const routeHandlerFactory: ( PutTransformsRequestSchema, TransformRequestHandlerContext > = (routeDependencies) => async (ctx, req, res) => { - const { coreStart, dataViews } = routeDependencies; + const { getCoreStart, getDataViewsStart } = routeDependencies; + const coreStart = await getCoreStart(); + const dataViews = await getDataViewsStart(); const { transformId } = req.params; const { createDataView, timeFieldName } = req.query; diff --git a/x-pack/plugins/transform/server/routes/api/transforms_nodes/register_route.ts b/x-pack/plugins/transform/server/routes/api/transforms_nodes/register_route.ts index f1a75d9f9ef28..701306ff6481c 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_nodes/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_nodes/register_route.ts @@ -11,7 +11,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandlerFactory } from './route_handler_factory'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transform Nodes * @@ -29,6 +29,13 @@ export function registerRoute({ router, license }: RouteDependencies) { version: '1', validate: false, }, - license.guardApiRoute(routeHandlerFactory(license)) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute(routeHandlerFactory(license))( + ctx, + request, + response + ); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/transforms_nodes/route_handler_factory.ts b/x-pack/plugins/transform/server/routes/api/transforms_nodes/route_handler_factory.ts index c512bfd58594a..10171f948c2ad 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_nodes/route_handler_factory.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_nodes/route_handler_factory.ts @@ -9,10 +9,9 @@ import Boom from '@hapi/boom'; import type { RequestHandler } from '@kbn/core/server'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; +import type { License } from '../../../services'; import { NODES_INFO_PRIVILEGES } from '../../../../common/constants'; -import type { RouteDependencies } from '../../../types'; - import { wrapError, wrapEsError } from '../../utils/error_utils'; const NODE_ROLES = 'roles'; @@ -33,7 +32,7 @@ export const isNodes = (arg: unknown): arg is Nodes => { }; export const routeHandlerFactory: ( - license: RouteDependencies['license'] + license: License ) => RequestHandler = (license) => async (ctx, req, res) => { try { const esClient = (await ctx.core).elasticsearch.client; diff --git a/x-pack/plugins/transform/server/routes/api/transforms_preview/register_route.ts b/x-pack/plugins/transform/server/routes/api/transforms_preview/register_route.ts index 646f92271243b..55e1446dfe5aa 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_preview/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_preview/register_route.ts @@ -13,7 +13,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -37,6 +37,11 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute(routeHandler) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute( + routeHandler + )(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/transforms_single/register_route.ts b/x-pack/plugins/transform/server/routes/api/transforms_single/register_route.ts index e79446d3962c0..c13c2b996dc7f 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_single/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_single/register_route.ts @@ -15,7 +15,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -39,6 +39,13 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute(routeHandler) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute(routeHandler)( + ctx, + request, + response + ); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/transforms_stats_all/register_route.ts b/x-pack/plugins/transform/server/routes/api/transforms_stats_all/register_route.ts index ef0bf70ec96d1..8aa59649af1d4 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_stats_all/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_stats_all/register_route.ts @@ -17,7 +17,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -43,10 +43,13 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute< - estypes.TransformGetTransformStatsResponse, - GetTransformStatsQuerySchema, - undefined - >(routeHandler) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute< + estypes.TransformGetTransformStatsResponse, + GetTransformStatsQuerySchema, + undefined + >(routeHandler)(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/transforms_stats_single/register_route.ts b/x-pack/plugins/transform/server/routes/api/transforms_stats_single/register_route.ts index a0e86fe7bf01c..9f7424cd62acf 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_stats_single/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_stats_single/register_route.ts @@ -19,7 +19,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -44,8 +44,13 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute( - routeHandler - ) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute< + TransformIdParamSchema, + GetTransformStatsQuerySchema, + undefined + >(routeHandler)(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/routes/api/transforms_update/register_route.ts b/x-pack/plugins/transform/server/routes/api/transforms_update/register_route.ts index 366b4ea32fc92..a90ce9395bfce 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms_update/register_route.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms_update/register_route.ts @@ -19,7 +19,7 @@ import type { RouteDependencies } from '../../../types'; import { routeHandler } from './route_handler'; -export function registerRoute({ router, license }: RouteDependencies) { +export function registerRoute({ router, getLicense }: RouteDependencies) { /** * @apiGroup Transforms * @@ -45,8 +45,13 @@ export function registerRoute({ router, license }: RouteDependencies) { }, }, }, - license.guardApiRoute( - routeHandler - ) + async (ctx, request, response) => { + const license = await getLicense(); + return license.guardApiRoute< + TransformIdParamSchema, + undefined, + PostTransformsUpdateRequestSchema + >(routeHandler)(ctx, request, response); + } ); } diff --git a/x-pack/plugins/transform/server/types.ts b/x-pack/plugins/transform/server/types.ts index d32f295fdf679..e5c44aafe163a 100644 --- a/x-pack/plugins/transform/server/types.ts +++ b/x-pack/plugins/transform/server/types.ts @@ -32,8 +32,8 @@ export interface PluginStartDependencies { export interface RouteDependencies { router: IRouter; - license: License; - coreStart: CoreStart; - dataViews: DataViewsServerPluginStart; - security?: SecurityPluginStart; + getLicense: () => Promise; + getCoreStart: () => Promise; + getDataViewsStart: () => Promise; + getSecurity: () => Promise; } diff --git a/x-pack/plugins/transform/server/usage/collector.ts b/x-pack/plugins/transform/server/usage/collector.ts index c2ee09ad983c1..98979375d4d49 100644 --- a/x-pack/plugins/transform/server/usage/collector.ts +++ b/x-pack/plugins/transform/server/usage/collector.ts @@ -22,7 +22,10 @@ export interface TransformAlertsUsageData { }; } -export function registerCollector(usageCollection: UsageCollectionSetup, alertIndex: string) { +export function registerCollector( + usageCollection: UsageCollectionSetup, + getAlertIndex: () => Promise +) { const collector = usageCollection.makeUsageCollector({ type: 'transform', schema: { @@ -62,7 +65,7 @@ export function registerCollector(usageCollection: UsageCollectionSetup, alertIn }; }>( { - index: alertIndex, + index: await getAlertIndex(), size: 10000, query: { bool: { diff --git a/x-pack/plugins/triggers_actions_ui/server/data/lib/time_series_query.test.ts b/x-pack/plugins/triggers_actions_ui/server/data/lib/time_series_query.test.ts index 9dfc32b6ee930..efc802dc73d3c 100644 --- a/x-pack/plugins/triggers_actions_ui/server/data/lib/time_series_query.test.ts +++ b/x-pack/plugins/triggers_actions_ui/server/data/lib/time_series_query.test.ts @@ -50,7 +50,7 @@ describe('timeSeriesQuery', () => { }); it('fails as expected when the query params are invalid', async () => { - expect( + await expect( timeSeriesQuery({ ...params, query: { ...params.query, dateStart: 'x' } }) ).rejects.toThrowErrorMatchingInlineSnapshot(`"invalid date format for dateStart: \\"x\\""`); }); diff --git a/x-pack/plugins/triggers_actions_ui/server/plugin.ts b/x-pack/plugins/triggers_actions_ui/server/plugin.ts index 04de44a088ed5..b5cafb0571482 100644 --- a/x-pack/plugins/triggers_actions_ui/server/plugin.ts +++ b/x-pack/plugins/triggers_actions_ui/server/plugin.ts @@ -53,14 +53,15 @@ export class TriggersActionsPlugin implements Plugin plugins.alerting !== undefined ); - core.getStartServices().then(([_, pluginStart]) => { - createConfigRoute({ - logger: this.logger, - router, - baseRoute: BASE_TRIGGERS_ACTIONS_UI_API_PATH, - alertingConfig: plugins.alerting.getConfig, - getRulesClientWithRequest: pluginStart.alerting.getRulesClientWithRequest, - }); + createConfigRoute({ + logger: this.logger, + router, + baseRoute: BASE_TRIGGERS_ACTIONS_UI_API_PATH, + alertingConfig: plugins.alerting.getConfig, + getRulesClientWithRequest: async (request) => { + const [, pluginStart] = await core.getStartServices(); + return pluginStart.alerting.getRulesClientWithRequest(request); + }, }); } diff --git a/x-pack/plugins/triggers_actions_ui/server/routes/config.test.ts b/x-pack/plugins/triggers_actions_ui/server/routes/config.test.ts index 8918e77795520..c951a5f9d34d2 100644 --- a/x-pack/plugins/triggers_actions_ui/server/routes/config.test.ts +++ b/x-pack/plugins/triggers_actions_ui/server/routes/config.test.ts @@ -55,7 +55,7 @@ describe('createConfigRoute', () => { maxScheduledPerMinute: 10000, minimumScheduleInterval: { value: '1m', enforce: false }, }), - getRulesClientWithRequest: () => mockRulesClient, + getRulesClientWithRequest: async () => mockRulesClient, }); const [config, handler] = router.get.mock.calls[0]; @@ -89,7 +89,7 @@ describe('createConfigRoute', () => { maxScheduledPerMinute: 10000, minimumScheduleInterval: { value: '1m', enforce: false }, }), - getRulesClientWithRequest: () => mockRulesClient, + getRulesClientWithRequest: async () => mockRulesClient, }); const [config, handler] = router.get.mock.calls[0]; diff --git a/x-pack/plugins/triggers_actions_ui/server/routes/config.ts b/x-pack/plugins/triggers_actions_ui/server/routes/config.ts index 1cc328c0ae5ad..c0212d7dc824f 100644 --- a/x-pack/plugins/triggers_actions_ui/server/routes/config.ts +++ b/x-pack/plugins/triggers_actions_ui/server/routes/config.ts @@ -23,7 +23,7 @@ export interface ConfigRouteOpts { // alertingConfig is a function because "isUsingSecurity" is pulled from the license // state which gets populated after plugin setup(). alertingConfig: () => AlertingRulesConfig; - getRulesClientWithRequest: (request: KibanaRequest) => RulesClientApi; + getRulesClientWithRequest: (request: KibanaRequest) => Promise; } export function createConfigRoute({ @@ -48,7 +48,7 @@ export function createConfigRoute({ res: KibanaResponseFactory ): Promise { // Check that user has access to at least one rule type - const rulesClient = getRulesClientWithRequest(req); + const rulesClient = await getRulesClientWithRequest(req); const ruleTypes = Array.from(await rulesClient.listRuleTypes()); if (ruleTypes.length > 0) { return res.ok({ body: alertingConfig() }); diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/worker.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/worker.ts index 46fcf6a4cec5b..902c7e83c59b4 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/worker.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/worker.ts @@ -6,6 +6,7 @@ */ import { IClusterClient, Logger, SavedObjectsClientContract, FakeRequest } from '@kbn/core/server'; +import { exhaustMap, Subject, takeUntil, timer } from 'rxjs'; import moment from 'moment'; import { SecurityPluginStart } from '@kbn/security-plugin/server'; import { LicensingPluginSetup } from '@kbn/licensing-plugin/server'; @@ -41,9 +42,8 @@ const WORKER_PADDING_MS = 1000; */ export class ReindexWorker { private static workerSingleton?: ReindexWorker; - private continuePolling: boolean = false; + private readonly stop$ = new Subject(); private updateOperationLoopRunning: boolean = false; - private timeout?: NodeJS.Timeout; private inProgressOps: ReindexSavedObject[] = []; private readonly reindexService: ReindexService; private readonly log: Logger; @@ -95,12 +95,16 @@ export class ReindexWorker { } /** - * Begins loop (1) to begin checking for in progress reindex operations. + * Begins loop checking for in progress reindex operations. */ public start = () => { this.log.debug('Starting worker...'); - this.continuePolling = true; - this.pollForOperations(); + timer(0, POLL_INTERVAL) + .pipe( + takeUntil(this.stop$), + exhaustMap(() => this.pollForOperations()) + ) + .subscribe(); }; /** @@ -108,19 +112,18 @@ export class ReindexWorker { */ public stop = () => { this.log.debug('Stopping worker...'); - if (this.timeout) { - clearTimeout(this.timeout); - } - + this.stop$.next(); this.updateOperationLoopRunning = false; - this.continuePolling = false; }; /** * Should be called immediately after this server has started a new reindex operation. */ public forceRefresh = () => { - this.refresh(); + // We know refresh won't throw, but just in case it does in the future + this.refresh().catch((error) => { + this.log.warn(`Failed to force refresh the reindex operations: ${error}`); + }); }; /** @@ -153,6 +156,8 @@ export class ReindexWorker { await new Promise((resolve) => setTimeout(resolve, WORKER_PADDING_MS)); } } + } catch (error) { + this.log.warn(`Failed to update reindex operations: ${error}`); } finally { this.updateOperationLoopRunning = false; } @@ -162,10 +167,6 @@ export class ReindexWorker { this.log.debug(`Polling for reindex operations`); await this.refresh(); - - if (this.continuePolling) { - this.timeout = setTimeout(this.pollForOperations, POLL_INTERVAL); - } }; private getCredentialScopedReindexService = (credential: Credential) => { @@ -194,7 +195,7 @@ export class ReindexWorker { firstOpInQueue.attributes.indexName ); // Re-associate the credentials - this.credentialStore.update({ + await this.credentialStore.update({ reindexOp: firstOpInQueue, security: this.security, credential, @@ -213,7 +214,7 @@ export class ReindexWorker { await this.updateInProgressOps(); // If there are operations in progress and we're not already updating operations, kick off the update loop if (!this.updateOperationLoopRunning) { - this.startUpdateOperationLoop(); + await this.startUpdateOperationLoop(); } }; @@ -250,7 +251,7 @@ export class ReindexWorker { reindexOp = await swallowExceptions(service.processNextStep, this.log)(reindexOp); // Update credential store with most recent state. - this.credentialStore.update({ reindexOp, security: this.security, credential }); + await this.credentialStore.update({ reindexOp, security: this.security, credential }); }; } diff --git a/x-pack/plugins/upgrade_assistant/server/plugin.ts b/x-pack/plugins/upgrade_assistant/server/plugin.ts index 6dfb65be85d7b..a2753279e8f69 100644 --- a/x-pack/plugins/upgrade_assistant/server/plugin.ts +++ b/x-pack/plugins/upgrade_assistant/server/plugin.ts @@ -147,7 +147,7 @@ export class UpgradeAssistantServerPlugin implements Plugin { registerRoutes(dependencies, this.getWorker.bind(this)); if (usageCollection) { - getStartServices().then(([{ elasticsearch }]) => { + void getStartServices().then(([{ elasticsearch }]) => { registerUpgradeAssistantUsageCollector({ elasticsearch, usageCollection, diff --git a/x-pack/test/functional_cors/plugins/kibana_cors_test/server/plugin.ts b/x-pack/test/functional_cors/plugins/kibana_cors_test/server/plugin.ts index 13fd8307a24a3..b13505a081ae9 100644 --- a/x-pack/test/functional_cors/plugins/kibana_cors_test/server/plugin.ts +++ b/x-pack/test/functional_cors/plugins/kibana_cors_test/server/plugin.ts @@ -75,12 +75,12 @@ export class CorsTestPlugin implements Plugin { return h.response(renderBody(kibanaUrl)); }, }); - server.start(); + void server.start(); } public stop() { if (this.server) { - this.server.stop(); + void this.server.stop(); } } } diff --git a/x-pack/test/plugin_api_perf/plugins/task_manager_performance/server/init_routes.ts b/x-pack/test/plugin_api_perf/plugins/task_manager_performance/server/init_routes.ts index 7d5118c5d93d3..e4a8bc76a8908 100644 --- a/x-pack/test/plugin_api_perf/plugins/task_manager_performance/server/init_routes.ts +++ b/x-pack/test/plugin_api_perf/plugins/task_manager_performance/server/init_routes.ts @@ -75,9 +75,9 @@ export function initRoutes( }, Promise.resolve(undefined)); return res.ok({ - body: await new Promise((resolve) => { + body: await new Promise((resolve, reject) => { setTimeout(() => { - performanceApi.endCapture().then((perf) => resolve(perf)); + performanceApi.endCapture().then((perf) => resolve(perf), reject); }, durationInSeconds * 1000 + 10000 /* wait extra 10s to drain queue */); }), });