From 8c3d71b370fadf5872185decedc34886ae151263 Mon Sep 17 00:00:00 2001 From: Melissa Alvarez Date: Thu, 27 Feb 2020 21:15:08 -0500 Subject: [PATCH 1/9] [ML] NP: migrate server (#58680) * remove obsolete legacy server deps * licensePreRoutingFactory uses licensing plugin rather than legacy xpack * move schemas to dir in routes * use NP license check method for license check * store license data in plugin for passing to check * create server plugin files in NP plugin dir * remove dependency on legacy xpack plugin * add sample data links first step * move all server dirs from legacy to np dir * fix requiredPlugin spaces name and update import routes * delete unnecessary files and add sample data links * update license and privilege check tests * add routeInit types --- x-pack/.i18nrc.json | 2 +- .../legacy/plugins/ml/common/constants/app.ts | 2 +- .../plugins/ml/common/constants/license.ts | 2 + x-pack/legacy/plugins/ml/index.ts | 55 +--- x-pack/legacy/plugins/ml/kibana.json | 8 - .../application/license/check_license.tsx | 11 +- .../call_with_internal_user_factory.d.ts | 9 - .../client/call_with_internal_user_factory.js | 18 -- .../call_with_internal_user_factory.test.ts | 28 --- .../client/call_with_request_factory.js | 21 -- .../ml/server/lib/__tests__/security_utils.js | 35 --- .../plugins/ml/server/lib/security_utils.d.ts | 9 - .../plugins/ml/server/lib/security_utils.js | 19 -- .../plugins/ml/server/new_platform/plugin.ts | 238 ------------------ x-pack/plugins/ml/kibana.json | 9 + .../client/__tests__/elasticsearch_ml.js | 0 .../ml/server/client/elasticsearch_ml.js | 0 .../plugins/ml/server/client/error_wrapper.ts | 0 .../plugins/ml/server/client/errors.js | 0 .../plugins/ml/server/client/log.ts | 2 +- .../ml/server}/index.ts | 7 +- .../ml/server/lib/__tests__/query_utils.js | 0 .../server/lib/check_annotations/index.d.ts | 0 .../ml/server/lib/check_annotations/index.js | 2 +- .../lib/check_license/check_license.test.ts | 46 ++-- .../server/lib/check_license/check_license.ts | 22 +- .../ml/server/lib/check_license/index.ts | 0 .../__mocks__/call_with_request.ts | 0 .../check_privileges/check_privileges.test.ts | 120 +++------ .../lib/check_privileges/check_privileges.ts | 16 +- .../ml/server/lib/check_privileges/index.ts | 0 .../server/lib/check_privileges/privileges.ts | 0 .../ml/server/lib/check_privileges/upgrade.ts | 0 .../ml/server/lib/ml_telemetry/index.ts | 0 .../ml_telemetry/make_ml_usage_collector.ts | 0 .../lib/ml_telemetry/ml_telemetry.test.ts | 30 +-- .../server/lib/ml_telemetry/ml_telemetry.ts | 19 +- .../plugins/ml/server/lib/query_utils.ts | 0 .../ml/server/lib/sample_data_sets/index.ts | 0 .../lib/sample_data_sets/sample_data_sets.ts | 0 .../plugins/ml/server/lib/spaces_utils.ts | 7 +- .../__mocks__/get_annotations_request.json | 0 .../__mocks__/get_annotations_response.json | 0 .../annotation_service/annotation.test.ts | 9 +- .../models/annotation_service/annotation.ts | 6 +- .../server/models/annotation_service/index.ts | 0 .../__tests__/bucket_span_estimator.js | 0 .../bucket_span_estimator.d.ts | 4 +- .../bucket_span_estimator.js | 10 +- .../models/bucket_span_estimator/index.ts | 0 .../models/bucket_span_estimator/intervals.js | 0 .../polled_data_checker.js | 0 .../single_series_checker.js | 0 .../calculate_model_memory_limit.d.ts | 0 .../calculate_model_memory_limit.js | 0 .../calculate_model_memory_limit/index.ts | 0 .../models/calendar/calendar_manager.ts | 0 .../server/models/calendar/event_manager.ts | 2 +- .../ml/server/models/calendar/index.ts | 0 .../analytics_audit_messages.ts | 6 +- .../models/data_frame_analytics/index.js | 0 .../data_recognizer/data_recognizer.test.ts | 2 +- .../models/data_recognizer/data_recognizer.ts | 9 +- .../ml/server/models/data_recognizer/index.ts | 0 .../ml_http_access_explorer_ecs.json | 0 .../search/ml_http_access_filebeat_ecs.json | 0 .../ml_http_access_events_timechart_ecs.json | 0 .../visualization/ml_http_access_map_ecs.json | 0 ...l_http_access_source_ip_timechart_ecs.json | 0 ...http_access_status_code_timechart_ecs.json | 0 ..._http_access_top_source_ips_table_ecs.json | 0 .../ml_http_access_top_urls_table_ecs.json | 0 ...access_unique_count_url_timechart_ecs.json | 0 .../modules/apache_ecs/logo.json | 0 .../modules/apache_ecs/manifest.json | 0 .../ml/datafeed_low_request_rate_ecs.json | 0 .../datafeed_source_ip_request_rate_ecs.json | 0 .../ml/datafeed_source_ip_url_count_ecs.json | 0 .../ml/datafeed_status_code_rate_ecs.json | 0 .../ml/datafeed_visitor_rate_ecs.json | 0 .../apache_ecs/ml/low_request_rate_ecs.json | 0 .../ml/source_ip_request_rate_ecs.json | 0 .../ml/source_ip_url_count_ecs.json | 0 .../apache_ecs/ml/status_code_rate_ecs.json | 0 .../apache_ecs/ml/visitor_rate_ecs.json | 0 .../modules/apm_jsbase/logo.json | 0 .../modules/apm_jsbase/manifest.json | 0 .../ml/abnormal_span_durations_jsbase.json | 0 ...ous_error_rate_for_user_agents_jsbase.json | 0 ...tafeed_abnormal_span_durations_jsbase.json | 0 ...ous_error_rate_for_user_agents_jsbase.json | 0 .../datafeed_decreased_throughput_jsbase.json | 0 ...afeed_high_count_by_user_agent_jsbase.json | 0 .../ml/decreased_throughput_jsbase.json | 0 .../ml/high_count_by_user_agent_jsbase.json | 0 .../modules/apm_nodejs/logo.json | 0 .../modules/apm_nodejs/manifest.json | 0 .../ml/abnormal_span_durations_nodejs.json | 0 .../ml/abnormal_trace_durations_nodejs.json | 0 ...tafeed_abnormal_span_durations_nodejs.json | 0 ...afeed_abnormal_trace_durations_nodejs.json | 0 .../datafeed_decreased_throughput_nodejs.json | 0 .../ml/decreased_throughput_nodejs.json | 0 .../modules/apm_transaction/logo.json | 0 .../modules/apm_transaction/manifest.json | 0 .../ml/datafeed_high_mean_response_time.json | 0 .../ml/high_mean_response_time.json | 0 ...ditbeat_docker_process_event_rate_ecs.json | 0 ...auditbeat_docker_process_explorer_ecs.json | 0 ...l_auditbeat_docker_process_events_ecs.json | 0 ...ker_process_event_rate_by_process_ecs.json | 0 ...eat_docker_process_event_rate_vis_ecs.json | 0 ...ditbeat_docker_process_occurrence_ecs.json | 0 .../auditbeat_process_docker_ecs/logo.json | 0 .../manifest.json | 0 ..._docker_high_count_process_events_ecs.json | 0 ...feed_docker_rare_process_activity_ecs.json | 0 .../docker_high_count_process_events_ecs.json | 0 .../ml/docker_rare_process_activity_ecs.json | 0 ...uditbeat_hosts_process_event_rate_ecs.json | 0 ..._auditbeat_hosts_process_explorer_ecs.json | 0 ...ml_auditbeat_hosts_process_events_ecs.json | 0 ...sts_process_event_rate_by_process_ecs.json | 0 ...beat_hosts_process_event_rate_vis_ecs.json | 0 ...uditbeat_hosts_process_occurrence_ecs.json | 0 .../auditbeat_process_hosts_ecs/logo.json | 0 .../auditbeat_process_hosts_ecs/manifest.json | 0 ...d_hosts_high_count_process_events_ecs.json | 0 ...afeed_hosts_rare_process_activity_ecs.json | 0 .../hosts_high_count_process_events_ecs.json | 0 .../ml/hosts_rare_process_activity_ecs.json | 0 .../modules/logs_ui_analysis/logo.json | 0 .../modules/logs_ui_analysis/manifest.json | 0 .../ml/datafeed_log_entry_rate.json | 0 .../logs_ui_analysis/ml/log_entry_rate.json | 0 .../modules/logs_ui_categories/logo.json | 0 .../modules/logs_ui_categories/manifest.json | 0 .../datafeed_log_entry_categories_count.json | 0 .../ml/log_entry_categories_count.json | 0 .../modules/metricbeat_system_ecs/logo.json | 0 .../metricbeat_system_ecs/manifest.json | 0 .../ml/datafeed_high_mean_cpu_iowait_ecs.json | 0 .../ml/datafeed_max_disk_utilization_ecs.json | 0 .../ml/datafeed_metricbeat_outages_ecs.json | 0 .../ml/high_mean_cpu_iowait_ecs.json | 0 .../ml/max_disk_utilization_ecs.json | 0 .../ml/metricbeat_outages_ecs.json | 0 .../ml_http_access_explorer_ecs.json | 0 .../search/ml_http_access_filebeat_ecs.json | 0 .../ml_http_access_events_timechart_ecs.json | 0 .../visualization/ml_http_access_map_ecs.json | 0 ...l_http_access_source_ip_timechart_ecs.json | 0 ...http_access_status_code_timechart_ecs.json | 0 ..._http_access_top_source_ips_table_ecs.json | 0 .../ml_http_access_top_urls_table_ecs.json | 0 ...access_unique_count_url_timechart_ecs.json | 0 .../modules/nginx_ecs/logo.json | 0 .../modules/nginx_ecs/manifest.json | 0 .../ml/datafeed_low_request_rate_ecs.json | 0 .../datafeed_source_ip_request_rate_ecs.json | 0 .../ml/datafeed_source_ip_url_count_ecs.json | 0 .../ml/datafeed_status_code_rate_ecs.json | 0 .../ml/datafeed_visitor_rate_ecs.json | 0 .../nginx_ecs/ml/low_request_rate_ecs.json | 0 .../ml/source_ip_request_rate_ecs.json | 0 .../nginx_ecs/ml/source_ip_url_count_ecs.json | 0 .../nginx_ecs/ml/status_code_rate_ecs.json | 0 .../nginx_ecs/ml/visitor_rate_ecs.json | 0 .../modules/sample_data_ecommerce/logo.json | 0 .../sample_data_ecommerce/manifest.json | 0 .../ml/datafeed_high_sum_total_sales.json | 0 .../ml/high_sum_total_sales.json | 0 .../modules/sample_data_weblogs/logo.json | 0 .../modules/sample_data_weblogs/manifest.json | 0 .../ml/datafeed_low_request_rate.json | 0 .../ml/datafeed_response_code_rates.json | 0 .../ml/datafeed_url_scanning.json | 0 .../ml/low_request_rate.json | 0 .../ml/response_code_rates.json | 0 .../sample_data_weblogs/ml/url_scanning.json | 0 .../modules/siem_auditbeat/logo.json | 0 .../modules/siem_auditbeat/manifest.json | 0 ..._linux_anomalous_network_activity_ecs.json | 0 ...x_anomalous_network_port_activity_ecs.json | 0 ...afeed_linux_anomalous_network_service.json | 0 ...ux_anomalous_network_url_activity_ecs.json | 0 ...linux_anomalous_process_all_hosts_ecs.json | 0 ...atafeed_linux_anomalous_user_name_ecs.json | 0 ...tafeed_rare_process_by_host_linux_ecs.json | 0 .../linux_anomalous_network_activity_ecs.json | 0 ...x_anomalous_network_port_activity_ecs.json | 0 .../ml/linux_anomalous_network_service.json | 0 ...ux_anomalous_network_url_activity_ecs.json | 0 ...linux_anomalous_process_all_hosts_ecs.json | 0 .../ml/linux_anomalous_user_name_ecs.json | 0 .../ml/rare_process_by_host_linux_ecs.json | 0 .../modules/siem_auditbeat_auth/logo.json | 0 .../modules/siem_auditbeat_auth/manifest.json | 0 ...atafeed_suspicious_login_activity_ecs.json | 0 .../ml/suspicious_login_activity_ecs.json | 0 .../modules/siem_packetbeat/logo.json | 0 .../modules/siem_packetbeat/manifest.json | 0 .../ml/datafeed_packetbeat_dns_tunneling.json | 0 ...datafeed_packetbeat_rare_dns_question.json | 0 ...atafeed_packetbeat_rare_server_domain.json | 0 .../ml/datafeed_packetbeat_rare_urls.json | 0 .../datafeed_packetbeat_rare_user_agent.json | 0 .../ml/packetbeat_dns_tunneling.json | 0 .../ml/packetbeat_rare_dns_question.json | 0 .../ml/packetbeat_rare_server_domain.json | 0 .../ml/packetbeat_rare_urls.json | 0 .../ml/packetbeat_rare_user_agent.json | 0 .../modules/siem_winlogbeat/logo.json | 0 .../modules/siem_winlogbeat/manifest.json | 0 ...feed_rare_process_by_host_windows_ecs.json | 0 ...indows_anomalous_network_activity_ecs.json | 0 ...d_windows_anomalous_path_activity_ecs.json | 0 ...ndows_anomalous_process_all_hosts_ecs.json | 0 ...ed_windows_anomalous_process_creation.json | 0 .../ml/datafeed_windows_anomalous_script.json | 0 .../datafeed_windows_anomalous_service.json | 0 ...afeed_windows_anomalous_user_name_ecs.json | 0 ...atafeed_windows_rare_user_runas_event.json | 0 .../ml/rare_process_by_host_windows_ecs.json | 0 ...indows_anomalous_network_activity_ecs.json | 0 .../windows_anomalous_path_activity_ecs.json | 0 ...ndows_anomalous_process_all_hosts_ecs.json | 0 .../windows_anomalous_process_creation.json | 0 .../ml/windows_anomalous_script.json | 0 .../ml/windows_anomalous_service.json | 0 .../ml/windows_anomalous_user_name_ecs.json | 0 .../ml/windows_rare_user_runas_event.json | 0 .../modules/siem_winlogbeat_auth/logo.json | 0 .../siem_winlogbeat_auth/manifest.json | 0 ...windows_rare_user_type10_remote_login.json | 0 ...windows_rare_user_type10_remote_login.json | 0 .../models/data_visualizer/data_visualizer.ts | 4 +- .../ml/server/models/data_visualizer/index.ts | 0 .../models/fields_service/fields_service.d.ts | 0 .../models/fields_service/fields_service.js | 0 .../ml/server/models/fields_service/index.ts | 0 .../file_data_visualizer.ts | 2 +- .../file_data_visualizer/import_data.ts | 2 +- .../models/file_data_visualizer/index.ts | 0 .../ml/server/models/filter/filter_manager.ts | 5 +- .../plugins/ml/server/models/filter/index.js | 0 .../plugins/ml/server/models/filter/index.ts | 0 .../server/models/job_audit_messages/index.ts | 0 .../job_audit_messages.d.ts | 0 .../job_audit_messages/job_audit_messages.js | 2 +- .../ml/server/models/job_service/datafeeds.js | 5 +- .../server/models/job_service/error_utils.js | 5 +- .../ml/server/models/job_service/groups.js | 2 +- .../ml/server/models/job_service/index.js | 0 .../ml/server/models/job_service/jobs.js | 7 +- .../new_job/categorization/examples.ts | 6 +- .../new_job/categorization/index.ts | 0 .../new_job/categorization/top_categories.ts | 9 +- .../categorization/validation_results.ts | 6 +- .../models/job_service/new_job/charts.ts | 2 +- .../models/job_service/new_job/index.ts | 0 .../models/job_service/new_job/line_chart.ts | 9 +- .../job_service/new_job/population_chart.ts | 9 +- .../responses/cloudwatch_field_caps.json | 0 .../responses/farequote_field_caps.json | 0 .../responses/kibana_saved_objects.json | 0 .../__mocks__/responses/rollup_caps.json | 0 .../results/cloudwatch_rollup_job_caps.json | 0 .../__mocks__/results/farequote_job_caps.json | 0 .../results/farequote_job_caps_empty.json | 0 .../job_service/new_job_caps/aggregations.ts | 7 +- .../job_service/new_job_caps/field_service.ts | 6 +- .../models/job_service/new_job_caps/index.ts | 0 .../new_job_caps/new_job_caps.test.ts | 0 .../job_service/new_job_caps/new_job_caps.ts | 6 +- .../models/job_service/new_job_caps/rollup.ts | 4 +- .../__tests__/job_validation.js | 0 .../__tests__/mock_farequote_cardinality.json | 0 .../mock_farequote_search_response.json | 0 .../__tests__/mock_field_caps.json | 0 .../__tests__/mock_it_search_response.json | 0 .../__tests__/mock_time_field.json | 0 .../__tests__/mock_time_field_nested.json | 0 .../__tests__/mock_time_range.json | 0 .../__tests__/validate_bucket_span.js | 2 +- .../__tests__/validate_cardinality.js | 0 .../__tests__/validate_influencers.js | 0 .../__tests__/validate_model_memory_limit.js | 0 .../__tests__/validate_time_range.js | 0 .../ml/server/models/job_validation/index.ts | 0 .../models/job_validation/job_validation.d.ts | 4 +- .../models/job_validation/job_validation.js | 13 +- .../server/models/job_validation/messages.js | 2 +- .../job_validation/validate_bucket_span.js | 10 +- .../job_validation/validate_cardinality.d.ts | 5 +- .../job_validation/validate_cardinality.js | 0 .../job_validation/validate_influencers.js | 0 .../job_validation/validate_job_object.js | 0 .../validate_model_memory_limit.js | 2 +- .../job_validation/validate_time_range.js | 4 +- .../build_anomaly_table_items.d.ts | 2 +- .../build_anomaly_table_items.js | 2 +- .../get_partition_fields_values.ts | 4 +- .../ml/server/models/results_service/index.ts | 0 .../models/results_service/results_service.ts | 6 +- x-pack/plugins/ml/server/plugin.ts | 168 +++++++++++++ .../plugins/ml/server/routes/README.md | 0 .../plugins/ml/server/routes/annotations.ts | 21 +- .../ml/server/routes/anomaly_detectors.ts | 38 +-- .../plugins/ml/server/routes/apidoc.json | 0 .../plugins/ml/server/routes/calendars.ts | 18 +- .../ml/server/routes/data_frame_analytics.ts | 30 +-- .../ml/server/routes/data_visualizer.ts | 12 +- .../plugins/ml/server/routes/datafeeds.ts | 28 +-- .../ml/server/routes/fields_service.ts | 12 +- .../ml/server/routes/file_data_visualizer.ts | 20 +- .../plugins/ml/server/routes/filters.ts | 20 +- .../plugins/ml/server/routes/indices.ts | 8 +- .../ml/server/routes/job_audit_messages.ts | 10 +- .../plugins/ml/server/routes/job_service.ts | 48 ++-- .../ml/server/routes/job_validation.ts | 26 +- .../license_check_pre_routing_factory.ts} | 12 +- .../plugins/ml/server/routes/modules.ts | 18 +- .../ml/server/routes/notification_settings.ts | 8 +- .../ml/server/routes/results_service.ts | 18 +- .../routes/schemas}/annotations_schema.ts | 0 .../schemas}/anomaly_detectors_schema.ts | 0 .../routes/schemas}/calendars_schema.ts | 0 .../routes/schemas}/data_analytics_schema.ts | 0 .../routes/schemas}/data_visualizer_schema.ts | 0 .../routes/schemas}/datafeeds_schema.ts | 0 .../routes/schemas}/fields_service_schema.ts | 0 .../server/routes/schemas}/filters_schema.ts | 0 .../routes/schemas}/job_service_schema.ts | 0 .../routes/schemas}/job_validation_schema.ts | 0 .../ml/server/routes/schemas}/modules.ts | 0 .../routes/schemas}/results_service_schema.ts | 0 .../plugins/ml/server/routes/system.ts | 31 ++- x-pack/plugins/ml/server/types.ts | 43 ++++ 339 files changed, 655 insertions(+), 873 deletions(-) delete mode 100644 x-pack/legacy/plugins/ml/kibana.json delete mode 100644 x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.d.ts delete mode 100644 x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.js delete mode 100644 x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.test.ts delete mode 100644 x-pack/legacy/plugins/ml/server/client/call_with_request_factory.js delete mode 100644 x-pack/legacy/plugins/ml/server/lib/__tests__/security_utils.js delete mode 100644 x-pack/legacy/plugins/ml/server/lib/security_utils.d.ts delete mode 100644 x-pack/legacy/plugins/ml/server/lib/security_utils.js delete mode 100644 x-pack/legacy/plugins/ml/server/new_platform/plugin.ts create mode 100644 x-pack/plugins/ml/kibana.json rename x-pack/{legacy => }/plugins/ml/server/client/__tests__/elasticsearch_ml.js (100%) rename x-pack/{legacy => }/plugins/ml/server/client/elasticsearch_ml.js (100%) rename x-pack/{legacy => }/plugins/ml/server/client/error_wrapper.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/client/errors.js (100%) rename x-pack/{legacy => }/plugins/ml/server/client/log.ts (94%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server}/index.ts (57%) rename x-pack/{legacy => }/plugins/ml/server/lib/__tests__/query_utils.js (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_annotations/index.d.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_annotations/index.js (95%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_license/check_license.test.ts (81%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_license/check_license.ts (75%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_license/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_privileges/__mocks__/call_with_request.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_privileges/check_privileges.test.ts (91%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_privileges/check_privileges.ts (94%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_privileges/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_privileges/privileges.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/check_privileges/upgrade.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/ml_telemetry/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/ml_telemetry/make_ml_usage_collector.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/ml_telemetry/ml_telemetry.test.ts (85%) rename x-pack/{legacy => }/plugins/ml/server/lib/ml_telemetry/ml_telemetry.ts (74%) rename x-pack/{legacy => }/plugins/ml/server/lib/query_utils.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/sample_data_sets/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/sample_data_sets/sample_data_sets.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/lib/spaces_utils.ts (75%) rename x-pack/{legacy => }/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_request.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_response.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/annotation_service/annotation.test.ts (96%) rename x-pack/{legacy => }/plugins/ml/server/models/annotation_service/annotation.ts (96%) rename x-pack/{legacy => }/plugins/ml/server/models/annotation_service/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/bucket_span_estimator/__tests__/bucket_span_estimator.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.d.ts (75%) rename x-pack/{legacy => }/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js (98%) rename x-pack/{legacy => }/plugins/ml/server/models/bucket_span_estimator/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/bucket_span_estimator/intervals.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.d.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/calculate_model_memory_limit/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/calendar/calendar_manager.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/calendar/event_manager.ts (94%) rename x-pack/{legacy => }/plugins/ml/server/models/calendar/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts (88%) rename x-pack/{legacy => }/plugins/ml/server/models/data_frame_analytics/index.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/data_recognizer.test.ts (97%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/data_recognizer.ts (99%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/search/ml_http_access_filebeat_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_map_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_low_request_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_request_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_url_count_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_status_code_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_visitor_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/abnormal_span_durations_jsbase.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/anomalous_error_rate_for_user_agents_jsbase.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_abnormal_span_durations_jsbase.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_anomalous_error_rate_for_user_agents_jsbase.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_decreased_throughput_jsbase.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_high_count_by_user_agent_jsbase.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/decreased_throughput_jsbase.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/high_count_by_user_agent_jsbase.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_span_durations_nodejs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_trace_durations_nodejs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_span_durations_nodejs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_trace_durations_nodejs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_decreased_throughput_nodejs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/decreased_throughput_nodejs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_transaction/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_transaction/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/datafeed_high_mean_response_time.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/high_mean_response_time.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_event_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_explorer_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/search/ml_auditbeat_docker_process_events_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_by_process_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_vis_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_occurrence_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_high_count_process_events_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_rare_process_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_event_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_explorer_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/search/ml_auditbeat_hosts_process_events_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_by_process_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_vis_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_occurrence_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_high_count_process_events_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_rare_process_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/datafeed_log_entry_rate.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/log_entry_rate.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/datafeed_log_entry_categories_count.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/log_entry_categories_count.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_high_mean_cpu_iowait_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_max_disk_utilization_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_metricbeat_outages_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/high_mean_cpu_iowait_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/max_disk_utilization_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/metricbeat_outages_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/search/ml_http_access_filebeat_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_map_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_low_request_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_request_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_url_count_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_status_code_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_visitor_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/high_sum_total_sales.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/low_request_rate.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/response_code_rates.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/url_scanning.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_port_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_service.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_url_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_process_all_hosts_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_user_name_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_rare_process_by_host_linux_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/datafeed_suspicious_login_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_dns_tunneling.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_dns_question.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_server_domain.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_urls.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_user_agent.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_rare_process_by_host_windows_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_network_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_path_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_all_hosts_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_creation.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_script.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_service.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_user_name_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_rare_user_runas_event.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/datafeed_windows_rare_user_type10_remote_login.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/data_visualizer/data_visualizer.ts (99%) rename x-pack/{legacy => }/plugins/ml/server/models/data_visualizer/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/fields_service/fields_service.d.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/fields_service/fields_service.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/fields_service/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/file_data_visualizer/file_data_visualizer.ts (95%) rename x-pack/{legacy => }/plugins/ml/server/models/file_data_visualizer/import_data.ts (97%) rename x-pack/{legacy => }/plugins/ml/server/models/file_data_visualizer/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/filter/filter_manager.ts (98%) rename x-pack/{legacy => }/plugins/ml/server/models/filter/index.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/filter/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_audit_messages/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_audit_messages/job_audit_messages.d.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_audit_messages/job_audit_messages.js (98%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/datafeeds.js (97%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/error_utils.js (94%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/groups.js (95%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/index.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/jobs.js (98%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job/categorization/examples.ts (95%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job/categorization/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts (92%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts (96%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job/charts.ts (87%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job/line_chart.ts (92%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job/population_chart.ts (95%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/cloudwatch_field_caps.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/farequote_field_caps.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/kibana_saved_objects.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/rollup_caps.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/cloudwatch_rollup_job_caps.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps_empty.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/aggregations.ts (97%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/field_service.ts (96%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts (93%) rename x-pack/{legacy => }/plugins/ml/server/models/job_service/new_job_caps/rollup.ts (92%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/job_validation.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/mock_farequote_cardinality.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/mock_farequote_search_response.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/mock_field_caps.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/mock_it_search_response.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/mock_time_field.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/mock_time_field_nested.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/mock_time_range.json (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/validate_bucket_span.js (98%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/validate_cardinality.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/validate_influencers.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/validate_model_memory_limit.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/__tests__/validate_time_range.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/job_validation.d.ts (83%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/job_validation.js (94%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/messages.js (99%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/validate_bucket_span.js (93%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/validate_cardinality.d.ts (78%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/validate_cardinality.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/validate_influencers.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/validate_job_object.js (100%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/validate_model_memory_limit.js (98%) rename x-pack/{legacy => }/plugins/ml/server/models/job_validation/validate_time_range.js (93%) rename x-pack/{legacy => }/plugins/ml/server/models/results_service/build_anomaly_table_items.d.ts (89%) rename x-pack/{legacy => }/plugins/ml/server/models/results_service/build_anomaly_table_items.js (99%) rename x-pack/{legacy => }/plugins/ml/server/models/results_service/get_partition_fields_values.ts (95%) rename x-pack/{legacy => }/plugins/ml/server/models/results_service/index.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/models/results_service/results_service.ts (97%) create mode 100644 x-pack/plugins/ml/server/plugin.ts rename x-pack/{legacy => }/plugins/ml/server/routes/README.md (100%) rename x-pack/{legacy => }/plugins/ml/server/routes/annotations.ts (83%) rename x-pack/{legacy => }/plugins/ml/server/routes/anomaly_detectors.ts (89%) rename x-pack/{legacy => }/plugins/ml/server/routes/apidoc.json (100%) rename x-pack/{legacy => }/plugins/ml/server/routes/calendars.ts (84%) rename x-pack/{legacy => }/plugins/ml/server/routes/data_frame_analytics.ts (89%) rename x-pack/{legacy => }/plugins/ml/server/routes/data_visualizer.ts (89%) rename x-pack/{legacy => }/plugins/ml/server/routes/datafeeds.ts (86%) rename x-pack/{legacy => }/plugins/ml/server/routes/fields_service.ts (84%) rename x-pack/{legacy => }/plugins/ml/server/routes/file_data_visualizer.ts (87%) rename x-pack/{legacy => }/plugins/ml/server/routes/filters.ts (87%) rename x-pack/{legacy => }/plugins/ml/server/routes/indices.ts (80%) rename x-pack/{legacy => }/plugins/ml/server/routes/job_audit_messages.ts (84%) rename x-pack/{legacy => }/plugins/ml/server/routes/job_service.ts (88%) rename x-pack/{legacy => }/plugins/ml/server/routes/job_validation.ts (85%) rename x-pack/{legacy/plugins/ml/server/new_platform/licence_check_pre_routing_factory.ts => plugins/ml/server/routes/license_check_pre_routing_factory.ts} (71%) rename x-pack/{legacy => }/plugins/ml/server/routes/modules.ts (88%) rename x-pack/{legacy => }/plugins/ml/server/routes/notification_settings.ts (75%) rename x-pack/{legacy => }/plugins/ml/server/routes/results_service.ts (88%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/annotations_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/anomaly_detectors_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/calendars_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/data_analytics_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/data_visualizer_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/datafeeds_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/fields_service_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/filters_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/job_service_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/job_validation_schema.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/modules.ts (100%) rename x-pack/{legacy/plugins/ml/server/new_platform => plugins/ml/server/routes/schemas}/results_service_schema.ts (100%) rename x-pack/{legacy => }/plugins/ml/server/routes/system.ts (88%) create mode 100644 x-pack/plugins/ml/server/types.ts diff --git a/x-pack/.i18nrc.json b/x-pack/.i18nrc.json index bb084b3bb72a18..66342266f1dbc6 100644 --- a/x-pack/.i18nrc.json +++ b/x-pack/.i18nrc.json @@ -26,7 +26,7 @@ "xpack.logstash": "legacy/plugins/logstash", "xpack.main": "legacy/plugins/xpack_main", "xpack.maps": "legacy/plugins/maps", - "xpack.ml": "legacy/plugins/ml", + "xpack.ml": ["plugins/ml", "legacy/plugins/ml"], "xpack.monitoring": "legacy/plugins/monitoring", "xpack.remoteClusters": "plugins/remote_clusters", "xpack.reporting": ["plugins/reporting", "legacy/plugins/reporting"], diff --git a/x-pack/legacy/plugins/ml/common/constants/app.ts b/x-pack/legacy/plugins/ml/common/constants/app.ts index 140a709b0c42be..bbec35a17faa54 100644 --- a/x-pack/legacy/plugins/ml/common/constants/app.ts +++ b/x-pack/legacy/plugins/ml/common/constants/app.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export const API_BASE_PATH = '/api/transform/'; +export const PLUGIN_ID = 'ml'; diff --git a/x-pack/legacy/plugins/ml/common/constants/license.ts b/x-pack/legacy/plugins/ml/common/constants/license.ts index 2027e2c8b18653..183844c9ef980c 100644 --- a/x-pack/legacy/plugins/ml/common/constants/license.ts +++ b/x-pack/legacy/plugins/ml/common/constants/license.ts @@ -8,3 +8,5 @@ export enum LICENSE_TYPE { BASIC, FULL, // >= platinum } + +export const VALID_FULL_LICENSE_MODES = ['platinum', 'enterprise', 'trial']; diff --git a/x-pack/legacy/plugins/ml/index.ts b/x-pack/legacy/plugins/ml/index.ts index 09f1b9ccedce4f..47df7c8c3e5e62 100755 --- a/x-pack/legacy/plugins/ml/index.ts +++ b/x-pack/legacy/plugins/ml/index.ts @@ -6,23 +6,13 @@ import { resolve } from 'path'; import { i18n } from '@kbn/i18n'; -import KbnServer, { Server } from 'src/legacy/server/kbn_server'; -import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; -import { plugin } from './server/new_platform'; -import { CloudSetup } from '../../../plugins/cloud/server'; +import { Server } from 'src/legacy/server/kbn_server'; import { DEFAULT_APP_CATEGORIES } from '../../../../src/core/utils'; -import { - MlInitializerContext, - MlCoreSetup, - MlHttpServiceSetup, -} from './server/new_platform/plugin'; +// @ts-ignore: could not find declaration file for module +import { mirrorPluginStatus } from '../../server/lib/mirror_plugin_status'; // @ts-ignore: could not find declaration file for module import mappings from './mappings'; -interface MlServer extends Server { - addAppLinksToSampleDataset: () => {}; -} - export const ml = (kibana: any) => { return new kibana.Plugin({ require: ['kibana', 'elasticsearch', 'xpack_main'], @@ -60,43 +50,8 @@ export const ml = (kibana: any) => { }, }, - async init(server: MlServer) { - const kbnServer = (server as unknown) as KbnServer; - - const initializerContext = ({ - legacyConfig: server.config(), - logger: { - get(...contextParts: string[]) { - return kbnServer.newPlatform.coreContext.logger.get('plugins', 'ml', ...contextParts); - }, - }, - } as unknown) as MlInitializerContext; - - const mlHttpService: MlHttpServiceSetup = { - ...kbnServer.newPlatform.setup.core.http, - route: server.route.bind(server), - }; - - const core: MlCoreSetup = { - injectUiAppVars: server.injectUiAppVars, - http: mlHttpService, - savedObjects: server.savedObjects, - coreSavedObjects: kbnServer.newPlatform.start.core.savedObjects, - elasticsearch: kbnServer.newPlatform.setup.core.elasticsearch, - }; - const { usageCollection, cloud, home } = kbnServer.newPlatform.setup.plugins; - const plugins = { - elasticsearch: server.plugins.elasticsearch, // legacy - security: server.newPlatform.setup.plugins.security, - xpackMain: server.plugins.xpack_main, - spaces: server.plugins.spaces, - home, - usageCollection: usageCollection as UsageCollectionSetup, - cloud: cloud as CloudSetup, - ml: this, - }; - - plugin(initializerContext).setup(core, plugins); + async init(server: Server) { + mirrorPluginStatus(server.plugins.xpack_main, this); }, }); }; diff --git a/x-pack/legacy/plugins/ml/kibana.json b/x-pack/legacy/plugins/ml/kibana.json deleted file mode 100644 index f36b4848186906..00000000000000 --- a/x-pack/legacy/plugins/ml/kibana.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "id": "ml", - "version": "0.0.1", - "kibanaVersion": "kibana", - "configPath": ["ml"], - "server": true, - "ui": true -} diff --git a/x-pack/legacy/plugins/ml/public/application/license/check_license.tsx b/x-pack/legacy/plugins/ml/public/application/license/check_license.tsx index 96e6aab3779621..4af753ddb4d1f2 100644 --- a/x-pack/legacy/plugins/ml/public/application/license/check_license.tsx +++ b/x-pack/legacy/plugins/ml/public/application/license/check_license.tsx @@ -82,9 +82,16 @@ function setLicenseExpired(features: any) { } } } - +// Temporary hack for cutting over server to NP function getFeatures() { - return xpackInfo.get('features.ml'); + return { + isAvailable: true, + showLinks: true, + enableLinks: true, + licenseType: 1, + hasExpired: false, + }; + // return xpackInfo.get('features.ml'); } function redirectToKibana() { diff --git a/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.d.ts b/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.d.ts deleted file mode 100644 index bf2e656afff123..00000000000000 --- a/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { ElasticsearchPlugin } from 'src/legacy/core_plugins/elasticsearch'; - -export function callWithInternalUserFactory(elasticsearchPlugin: ElasticsearchPlugin): any; diff --git a/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.js b/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.js deleted file mode 100644 index 2e5431bdd6ce2d..00000000000000 --- a/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.js +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { once } from 'lodash'; - -const _callWithInternalUser = once(elasticsearchPlugin => { - const { callWithInternalUser } = elasticsearchPlugin.getCluster('admin'); - return callWithInternalUser; -}); - -export const callWithInternalUserFactory = elasticsearchPlugin => { - return (...args) => { - return _callWithInternalUser(elasticsearchPlugin)(...args); - }; -}; diff --git a/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.test.ts b/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.test.ts deleted file mode 100644 index be016cc13ed0f3..00000000000000 --- a/x-pack/legacy/plugins/ml/server/client/call_with_internal_user_factory.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { callWithInternalUserFactory } from './call_with_internal_user_factory'; - -describe('call_with_internal_user_factory', () => { - describe('callWithInternalUserFactory', () => { - let elasticsearchPlugin: any; - let callWithInternalUser: any; - - beforeEach(() => { - callWithInternalUser = jest.fn(); - elasticsearchPlugin = { - getCluster: jest.fn(() => ({ callWithInternalUser })), - }; - }); - - it('should use internal user "admin"', () => { - const callWithInternalUserInstance = callWithInternalUserFactory(elasticsearchPlugin); - callWithInternalUserInstance(); - - expect(elasticsearchPlugin.getCluster).toHaveBeenCalledWith('admin'); - }); - }); -}); diff --git a/x-pack/legacy/plugins/ml/server/client/call_with_request_factory.js b/x-pack/legacy/plugins/ml/server/client/call_with_request_factory.js deleted file mode 100644 index b39a58b317500f..00000000000000 --- a/x-pack/legacy/plugins/ml/server/client/call_with_request_factory.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { once } from 'lodash'; -import { elasticsearchJsPlugin } from './elasticsearch_ml'; - -const callWithRequest = once(elasticsearchPlugin => { - const config = { plugins: [elasticsearchJsPlugin] }; - const cluster = elasticsearchPlugin.createCluster('ml', config); - - return cluster.callWithRequest; -}); - -export const callWithRequestFactory = (elasticsearchPlugin, request) => { - return (...args) => { - return callWithRequest(elasticsearchPlugin)(request, ...args); - }; -}; diff --git a/x-pack/legacy/plugins/ml/server/lib/__tests__/security_utils.js b/x-pack/legacy/plugins/ml/server/lib/__tests__/security_utils.js deleted file mode 100644 index 6e0181f49072e1..00000000000000 --- a/x-pack/legacy/plugins/ml/server/lib/__tests__/security_utils.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { isSecurityDisabled } from '../security_utils'; - -describe('ML - security utils', () => { - function mockXpackMainPluginFactory(isAvailable = true, isEnabled = true) { - return { - info: { - isAvailable: () => isAvailable, - feature: () => ({ - isEnabled: () => isEnabled, - }), - }, - }; - } - - describe('isSecurityDisabled', () => { - it('returns not disabled for given mock server object #1', () => { - expect(isSecurityDisabled(mockXpackMainPluginFactory())).to.be(false); - }); - - it('returns not disabled for given mock server object #2', () => { - expect(isSecurityDisabled(mockXpackMainPluginFactory(false))).to.be(false); - }); - - it('returns disabled for given mock server object #3', () => { - expect(isSecurityDisabled(mockXpackMainPluginFactory(true, false))).to.be(true); - }); - }); -}); diff --git a/x-pack/legacy/plugins/ml/server/lib/security_utils.d.ts b/x-pack/legacy/plugins/ml/server/lib/security_utils.d.ts deleted file mode 100644 index 26fdff73b34606..00000000000000 --- a/x-pack/legacy/plugins/ml/server/lib/security_utils.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { XPackMainPlugin } from '../../../xpack_main/server/xpack_main'; - -export function isSecurityDisabled(xpackMainPlugin: XPackMainPlugin): boolean; diff --git a/x-pack/legacy/plugins/ml/server/lib/security_utils.js b/x-pack/legacy/plugins/ml/server/lib/security_utils.js deleted file mode 100644 index 27109e645b185b..00000000000000 --- a/x-pack/legacy/plugins/ml/server/lib/security_utils.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -/* - * Contains utility functions related to x-pack security. - */ - -export function isSecurityDisabled(xpackMainPlugin) { - const xpackInfo = xpackMainPlugin && xpackMainPlugin.info; - // we assume that `xpack.isAvailable()` always returns `true` because we're inside x-pack - // if for whatever reason it returns `false`, `isSecurityDisabled()` would also return `false` - // which would result in follow-up behavior assuming security is enabled. This is intentional, - // because it results in more defensive behavior. - const securityInfo = xpackInfo && xpackInfo.isAvailable() && xpackInfo.feature('security'); - return securityInfo && securityInfo.isEnabled() === false; -} diff --git a/x-pack/legacy/plugins/ml/server/new_platform/plugin.ts b/x-pack/legacy/plugins/ml/server/new_platform/plugin.ts deleted file mode 100644 index 43c276ac63a13d..00000000000000 --- a/x-pack/legacy/plugins/ml/server/new_platform/plugin.ts +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import Boom from 'boom'; -import { i18n } from '@kbn/i18n'; -import { ServerRoute } from 'hapi'; -import { KibanaConfig, SavedObjectsLegacyService } from 'src/legacy/server/kbn_server'; -import { - Logger, - PluginInitializerContext, - CoreSetup, - IRouter, - IScopedClusterClient, - SavedObjectsServiceStart, -} from 'src/core/server'; -import { ElasticsearchPlugin } from 'src/legacy/core_plugins/elasticsearch'; -import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; -import { ElasticsearchServiceSetup } from 'src/core/server'; -import { CloudSetup } from '../../../../../plugins/cloud/server'; -import { XPackMainPlugin } from '../../../xpack_main/server/xpack_main'; -import { addLinksToSampleDatasets } from '../lib/sample_data_sets'; -import { checkLicense } from '../lib/check_license'; -// @ts-ignore: could not find declaration file for module -import { mirrorPluginStatus } from '../../../../server/lib/mirror_plugin_status'; -import { LICENSE_TYPE } from '../../common/constants/license'; -import { annotationRoutes } from '../routes/annotations'; -import { jobRoutes } from '../routes/anomaly_detectors'; -import { dataFeedRoutes } from '../routes/datafeeds'; -import { indicesRoutes } from '../routes/indices'; -import { jobValidationRoutes } from '../routes/job_validation'; -import { makeMlUsageCollector } from '../lib/ml_telemetry'; -import { notificationRoutes } from '../routes/notification_settings'; -import { systemRoutes } from '../routes/system'; -import { dataFrameAnalyticsRoutes } from '../routes/data_frame_analytics'; -import { dataRecognizer } from '../routes/modules'; -import { dataVisualizerRoutes } from '../routes/data_visualizer'; -import { calendars } from '../routes/calendars'; -// @ts-ignore: could not find declaration file for module -import { fieldsService } from '../routes/fields_service'; -import { filtersRoutes } from '../routes/filters'; -import { resultsServiceRoutes } from '../routes/results_service'; -import { jobServiceRoutes } from '../routes/job_service'; -import { jobAuditMessagesRoutes } from '../routes/job_audit_messages'; -import { fileDataVisualizerRoutes } from '../routes/file_data_visualizer'; -import { initMlServerLog, LogInitialization } from '../client/log'; -import { HomeServerPluginSetup } from '../../../../../../src/plugins/home/server'; -// @ts-ignore: could not find declaration file for module -import { elasticsearchJsPlugin } from '../client/elasticsearch_ml'; - -export const PLUGIN_ID = 'ml'; - -type CoreHttpSetup = CoreSetup['http']; -export interface MlHttpServiceSetup extends CoreHttpSetup { - route(route: ServerRoute | ServerRoute[]): void; -} - -export interface MlXpackMainPlugin extends XPackMainPlugin { - status?: any; -} - -export interface MlCoreSetup { - injectUiAppVars: (id: string, callback: () => {}) => any; - http: MlHttpServiceSetup; - savedObjects: SavedObjectsLegacyService; - coreSavedObjects: SavedObjectsServiceStart; - elasticsearch: ElasticsearchServiceSetup; -} -export interface MlInitializerContext extends PluginInitializerContext { - legacyConfig: KibanaConfig; - log: Logger; -} -export interface PluginsSetup { - elasticsearch: ElasticsearchPlugin; - xpackMain: MlXpackMainPlugin; - security: any; - spaces: any; - usageCollection?: UsageCollectionSetup; - cloud?: CloudSetup; - home?: HomeServerPluginSetup; - // TODO: this is temporary for `mirrorPluginStatus` - ml: any; -} - -export interface RouteInitialization { - commonRouteConfig: any; - config?: any; - elasticsearchPlugin: ElasticsearchPlugin; - elasticsearchService: ElasticsearchServiceSetup; - route(route: ServerRoute | ServerRoute[]): void; - router: IRouter; - xpackMainPlugin: MlXpackMainPlugin; - savedObjects?: SavedObjectsServiceStart; - spacesPlugin: any; - securityPlugin: any; - cloud?: CloudSetup; -} - -declare module 'kibana/server' { - interface RequestHandlerContext { - ml?: { - mlClient: IScopedClusterClient; - }; - } -} - -export class Plugin { - private readonly pluginId: string = PLUGIN_ID; - private config: any; - private log: Logger; - - constructor(initializerContext: MlInitializerContext) { - this.config = initializerContext.legacyConfig; - this.log = initializerContext.logger.get(); - } - - public setup(core: MlCoreSetup, plugins: PluginsSetup) { - const xpackMainPlugin: MlXpackMainPlugin = plugins.xpackMain; - const { http, coreSavedObjects } = core; - const pluginId = this.pluginId; - - mirrorPluginStatus(xpackMainPlugin, plugins.ml); - xpackMainPlugin.status.once('green', () => { - // Register a function that is called whenever the xpack info changes, - // to re-compute the license check results for this plugin - const mlFeature = xpackMainPlugin.info.feature(pluginId); - mlFeature.registerLicenseCheckResultsGenerator(checkLicense); - - // Add links to the Kibana sample data sets if ml is enabled - // and there is a full license (trial or platinum). - if (mlFeature.isEnabled() === true && plugins.home) { - const licenseCheckResults = mlFeature.getLicenseCheckResults(); - if (licenseCheckResults.licenseType === LICENSE_TYPE.FULL) { - addLinksToSampleDatasets({ - addAppLinksToSampleDataset: plugins.home.sampleData.addAppLinksToSampleDataset, - }); - } - } - }); - - xpackMainPlugin.registerFeature({ - id: 'ml', - name: i18n.translate('xpack.ml.featureRegistry.mlFeatureName', { - defaultMessage: 'Machine Learning', - }), - icon: 'machineLearningApp', - navLinkId: 'ml', - app: ['ml', 'kibana'], - catalogue: ['ml'], - privileges: {}, - reserved: { - privilege: { - savedObject: { - all: [], - read: [], - }, - ui: [], - }, - description: i18n.translate('xpack.ml.feature.reserved.description', { - defaultMessage: - 'To grant users access, you should also assign either the machine_learning_user or machine_learning_admin role.', - }), - }, - }); - - // Add server routes and initialize the plugin here - const commonRouteConfig = { - pre: [ - function forbidApiAccess() { - const licenseCheckResults = xpackMainPlugin.info - .feature(pluginId) - .getLicenseCheckResults(); - if (licenseCheckResults.isAvailable) { - return null; - } else { - throw Boom.forbidden(licenseCheckResults.message); - } - }, - ], - }; - - // Can access via new platform router's handler function 'context' parameter - context.ml.mlClient - const mlClient = core.elasticsearch.createClient('ml', { plugins: [elasticsearchJsPlugin] }); - http.registerRouteHandlerContext('ml', (context, request) => { - return { - mlClient: mlClient.asScoped(request), - }; - }); - - const routeInitializationDeps: RouteInitialization = { - commonRouteConfig, - route: http.route, - router: http.createRouter(), - elasticsearchPlugin: plugins.elasticsearch, - elasticsearchService: core.elasticsearch, - xpackMainPlugin: plugins.xpackMain, - spacesPlugin: plugins.spaces, - securityPlugin: plugins.security, - }; - - const extendedRouteInitializationDeps: RouteInitialization = { - ...routeInitializationDeps, - config: this.config, - savedObjects: coreSavedObjects, - spacesPlugin: plugins.spaces, - cloud: plugins.cloud, - }; - - const logInitializationDeps: LogInitialization = { - log: this.log, - }; - - annotationRoutes(routeInitializationDeps); - jobRoutes(routeInitializationDeps); - dataFeedRoutes(routeInitializationDeps); - dataFrameAnalyticsRoutes(routeInitializationDeps); - indicesRoutes(routeInitializationDeps); - jobValidationRoutes(extendedRouteInitializationDeps); - notificationRoutes(routeInitializationDeps); - systemRoutes(extendedRouteInitializationDeps); - dataRecognizer(extendedRouteInitializationDeps); - dataVisualizerRoutes(routeInitializationDeps); - calendars(routeInitializationDeps); - fieldsService(routeInitializationDeps); - filtersRoutes(routeInitializationDeps); - resultsServiceRoutes(routeInitializationDeps); - jobServiceRoutes(routeInitializationDeps); - jobAuditMessagesRoutes(routeInitializationDeps); - fileDataVisualizerRoutes(extendedRouteInitializationDeps); - - initMlServerLog(logInitializationDeps); - makeMlUsageCollector(plugins.usageCollection, coreSavedObjects); - } - - public stop() {} -} diff --git a/x-pack/plugins/ml/kibana.json b/x-pack/plugins/ml/kibana.json new file mode 100644 index 00000000000000..e944af6821c0b6 --- /dev/null +++ b/x-pack/plugins/ml/kibana.json @@ -0,0 +1,9 @@ +{ + "id": "ml", + "version": "0.0.1", + "kibanaVersion": "kibana", + "configPath": ["ml"], + "requiredPlugins": ["cloud", "features", "home", "licensing", "security", "spaces", "usageCollection"], + "server": true, + "ui": false +} diff --git a/x-pack/legacy/plugins/ml/server/client/__tests__/elasticsearch_ml.js b/x-pack/plugins/ml/server/client/__tests__/elasticsearch_ml.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/client/__tests__/elasticsearch_ml.js rename to x-pack/plugins/ml/server/client/__tests__/elasticsearch_ml.js diff --git a/x-pack/legacy/plugins/ml/server/client/elasticsearch_ml.js b/x-pack/plugins/ml/server/client/elasticsearch_ml.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/client/elasticsearch_ml.js rename to x-pack/plugins/ml/server/client/elasticsearch_ml.js diff --git a/x-pack/legacy/plugins/ml/server/client/error_wrapper.ts b/x-pack/plugins/ml/server/client/error_wrapper.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/client/error_wrapper.ts rename to x-pack/plugins/ml/server/client/error_wrapper.ts diff --git a/x-pack/legacy/plugins/ml/server/client/errors.js b/x-pack/plugins/ml/server/client/errors.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/client/errors.js rename to x-pack/plugins/ml/server/client/errors.js diff --git a/x-pack/legacy/plugins/ml/server/client/log.ts b/x-pack/plugins/ml/server/client/log.ts similarity index 94% rename from x-pack/legacy/plugins/ml/server/client/log.ts rename to x-pack/plugins/ml/server/client/log.ts index ae82383ead6050..8ee5882f6c2c16 100644 --- a/x-pack/legacy/plugins/ml/server/client/log.ts +++ b/x-pack/plugins/ml/server/client/log.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Logger } from '../../../../../../src/core/server'; +import { Logger } from '../../../../../src/core/server'; export interface LogInitialization { log: Logger; diff --git a/x-pack/legacy/plugins/ml/server/new_platform/index.ts b/x-pack/plugins/ml/server/index.ts similarity index 57% rename from x-pack/legacy/plugins/ml/server/new_platform/index.ts rename to x-pack/plugins/ml/server/index.ts index b03f2dac613b03..55e87ed6f0c6a3 100644 --- a/x-pack/legacy/plugins/ml/server/new_platform/index.ts +++ b/x-pack/plugins/ml/server/index.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Plugin, MlInitializerContext } from './plugin'; +import { PluginInitializerContext } from 'kibana/server'; +import { MlServerPlugin } from './plugin'; -export function plugin(initializerContext: MlInitializerContext) { - return new Plugin(initializerContext); -} +export const plugin = (ctx: PluginInitializerContext) => new MlServerPlugin(ctx); diff --git a/x-pack/legacy/plugins/ml/server/lib/__tests__/query_utils.js b/x-pack/plugins/ml/server/lib/__tests__/query_utils.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/__tests__/query_utils.js rename to x-pack/plugins/ml/server/lib/__tests__/query_utils.js diff --git a/x-pack/legacy/plugins/ml/server/lib/check_annotations/index.d.ts b/x-pack/plugins/ml/server/lib/check_annotations/index.d.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/check_annotations/index.d.ts rename to x-pack/plugins/ml/server/lib/check_annotations/index.d.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/check_annotations/index.js b/x-pack/plugins/ml/server/lib/check_annotations/index.js similarity index 95% rename from x-pack/legacy/plugins/ml/server/lib/check_annotations/index.js rename to x-pack/plugins/ml/server/lib/check_annotations/index.js index 186c27b0326d70..55a90c0cec322c 100644 --- a/x-pack/legacy/plugins/ml/server/lib/check_annotations/index.js +++ b/x-pack/plugins/ml/server/lib/check_annotations/index.js @@ -10,7 +10,7 @@ import { ML_ANNOTATIONS_INDEX_ALIAS_READ, ML_ANNOTATIONS_INDEX_ALIAS_WRITE, ML_ANNOTATIONS_INDEX_PATTERN, -} from '../../../common/constants/index_patterns'; +} from '../../../../../legacy/plugins/ml/common/constants/index_patterns'; // Annotations Feature is available if: // - ML_ANNOTATIONS_INDEX_PATTERN index is present diff --git a/x-pack/legacy/plugins/ml/server/lib/check_license/check_license.test.ts b/x-pack/plugins/ml/server/lib/check_license/check_license.test.ts similarity index 81% rename from x-pack/legacy/plugins/ml/server/lib/check_license/check_license.test.ts rename to x-pack/plugins/ml/server/lib/check_license/check_license.test.ts index 1d80a226486bb1..942dbe37226175 100644 --- a/x-pack/legacy/plugins/ml/server/lib/check_license/check_license.test.ts +++ b/x-pack/plugins/ml/server/lib/check_license/check_license.test.ts @@ -7,12 +7,12 @@ import expect from '@kbn/expect'; import sinon from 'sinon'; import { set } from 'lodash'; -import { XPackInfo } from '../../../../xpack_main/server/lib/xpack_info'; +import { LicenseCheckResult } from '../../types'; import { checkLicense } from './check_license'; describe('check_license', () => { - let mockLicenseInfo: XPackInfo; - beforeEach(() => (mockLicenseInfo = {} as XPackInfo)); + let mockLicenseInfo: LicenseCheckResult; + beforeEach(() => (mockLicenseInfo = {} as LicenseCheckResult)); describe('license information is undefined', () => { it('should set isAvailable to false', () => { @@ -33,7 +33,9 @@ describe('check_license', () => { }); describe('license information is not available', () => { - beforeEach(() => (mockLicenseInfo.isAvailable = () => false)); + beforeEach(() => { + mockLicenseInfo.isAvailable = false; + }); it('should set isAvailable to false', () => { expect(checkLicense(mockLicenseInfo).isAvailable).to.be(false); @@ -54,8 +56,8 @@ describe('check_license', () => { describe('license information is available', () => { beforeEach(() => { - mockLicenseInfo.isAvailable = () => true; - set(mockLicenseInfo, 'license.getType', () => 'basic'); + mockLicenseInfo.isAvailable = true; + mockLicenseInfo.type = 'basic'; }); describe('& ML is disabled in Elasticsearch', () => { @@ -66,7 +68,7 @@ describe('check_license', () => { sinon .stub() .withArgs('ml') - .returns({ isEnabled: () => false }) + .returns({ isEnabled: false }) ); }); @@ -89,21 +91,17 @@ describe('check_license', () => { describe('& ML is enabled in Elasticsearch', () => { beforeEach(() => { - set( - mockLicenseInfo, - 'feature', - sinon - .stub() - .withArgs('ml') - .returns({ isEnabled: () => true }) - ); + mockLicenseInfo.isEnabled = true; }); describe('& license is >= platinum', () => { - beforeEach(() => set(mockLicenseInfo, 'license.isOneOf', () => true)); - + beforeEach(() => { + mockLicenseInfo.type = 'platinum'; + }); describe('& license is active', () => { - beforeEach(() => set(mockLicenseInfo, 'license.isActive', () => true)); + beforeEach(() => { + mockLicenseInfo.isActive = true; + }); it('should set isAvailable to true', () => { expect(checkLicense(mockLicenseInfo).isAvailable).to.be(true); @@ -123,7 +121,9 @@ describe('check_license', () => { }); describe('& license is expired', () => { - beforeEach(() => set(mockLicenseInfo, 'license.isActive', () => false)); + beforeEach(() => { + mockLicenseInfo.isActive = false; + }); it('should set isAvailable to true', () => { expect(checkLicense(mockLicenseInfo).isAvailable).to.be(true); @@ -144,10 +144,14 @@ describe('check_license', () => { }); describe('& license is basic', () => { - beforeEach(() => set(mockLicenseInfo, 'license.isOneOf', () => false)); + beforeEach(() => { + mockLicenseInfo.type = 'basic'; + }); describe('& license is active', () => { - beforeEach(() => set(mockLicenseInfo, 'license.isActive', () => true)); + beforeEach(() => { + mockLicenseInfo.isActive = true; + }); it('should set isAvailable to true', () => { expect(checkLicense(mockLicenseInfo).isAvailable).to.be(true); diff --git a/x-pack/legacy/plugins/ml/server/lib/check_license/check_license.ts b/x-pack/plugins/ml/server/lib/check_license/check_license.ts similarity index 75% rename from x-pack/legacy/plugins/ml/server/lib/check_license/check_license.ts rename to x-pack/plugins/ml/server/lib/check_license/check_license.ts index c88ab087a81985..5bf3d590a1912d 100644 --- a/x-pack/legacy/plugins/ml/server/lib/check_license/check_license.ts +++ b/x-pack/plugins/ml/server/lib/check_license/check_license.ts @@ -5,8 +5,11 @@ */ import { i18n } from '@kbn/i18n'; -import { LICENSE_TYPE } from '../../../common/constants/license'; -import { XPackInfo } from '../../../../../../legacy/plugins/xpack_main/server/lib/xpack_info'; +import { + LICENSE_TYPE, + VALID_FULL_LICENSE_MODES, +} from '../../../../../legacy/plugins/ml/common/constants/license'; +import { LicenseCheckResult } from '../../types'; interface Response { isAvailable: boolean; @@ -17,10 +20,10 @@ interface Response { message?: string; } -export function checkLicense(xpackLicenseInfo: XPackInfo): Response { +export function checkLicense(licenseCheckResult: LicenseCheckResult): Response { // If, for some reason, we cannot get the license information // from Elasticsearch, assume worst case and disable the Machine Learning UI - if (!xpackLicenseInfo || !xpackLicenseInfo.isAvailable()) { + if (licenseCheckResult === undefined || !licenseCheckResult.isAvailable) { return { isAvailable: false, showLinks: true, @@ -35,7 +38,7 @@ export function checkLicense(xpackLicenseInfo: XPackInfo): Response { }; } - const featureEnabled = xpackLicenseInfo.feature('ml').isEnabled(); + const featureEnabled = licenseCheckResult.isEnabled; if (!featureEnabled) { return { isAvailable: false, @@ -47,12 +50,11 @@ export function checkLicense(xpackLicenseInfo: XPackInfo): Response { }; } - const VALID_FULL_LICENSE_MODES = ['platinum', 'enterprise', 'trial']; - - const isLicenseModeValid = xpackLicenseInfo.license.isOneOf(VALID_FULL_LICENSE_MODES); + const isLicenseModeValid = + licenseCheckResult.type && VALID_FULL_LICENSE_MODES.includes(licenseCheckResult.type); const licenseType = isLicenseModeValid === true ? LICENSE_TYPE.FULL : LICENSE_TYPE.BASIC; - const isLicenseActive = xpackLicenseInfo.license.isActive(); - const licenseTypeName = xpackLicenseInfo.license.getType(); + const isLicenseActive = licenseCheckResult.isActive; + const licenseTypeName = licenseCheckResult.type; // Platinum or trial license is valid but not active, i.e. expired if (licenseType === LICENSE_TYPE.FULL && isLicenseActive === false) { diff --git a/x-pack/legacy/plugins/ml/server/lib/check_license/index.ts b/x-pack/plugins/ml/server/lib/check_license/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/check_license/index.ts rename to x-pack/plugins/ml/server/lib/check_license/index.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/check_privileges/__mocks__/call_with_request.ts b/x-pack/plugins/ml/server/lib/check_privileges/__mocks__/call_with_request.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/check_privileges/__mocks__/call_with_request.ts rename to x-pack/plugins/ml/server/lib/check_privileges/__mocks__/call_with_request.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/check_privileges/check_privileges.test.ts b/x-pack/plugins/ml/server/lib/check_privileges/check_privileges.test.ts similarity index 91% rename from x-pack/legacy/plugins/ml/server/lib/check_privileges/check_privileges.test.ts rename to x-pack/plugins/ml/server/lib/check_privileges/check_privileges.test.ts index da8ef25b2f4dff..0690aa53576a5a 100644 --- a/x-pack/legacy/plugins/ml/server/lib/check_privileges/check_privileges.test.ts +++ b/x-pack/plugins/ml/server/lib/check_privileges/check_privileges.test.ts @@ -8,81 +8,29 @@ import { callWithRequestProvider } from './__mocks__/call_with_request'; import { privilegesProvider } from './check_privileges'; import { mlPrivileges } from './privileges'; -const xpackMainPluginWithSecurity = { - info: { - isAvailable: () => true, - feature: (f: string) => { - switch (f) { - case 'ml': - return { isEnabled: () => true }; - case 'security': - return { isEnabled: () => true }; - } - }, - license: { - isOneOf: () => true, - isActive: () => true, - getType: () => 'platinum', - }, - }, -} as any; +const licenseCheckResultWithSecurity = { + isAvailable: true, + isEnabled: true, + isSecurityDisabled: false, + type: 'platinum', + isActive: true, +}; -const xpackMainPluginWithOutSecurity = { - info: { - isAvailable: () => true, - feature: (f: string) => { - switch (f) { - case 'ml': - return { isEnabled: () => true }; - case 'security': - return { isEnabled: () => false }; - } - }, - license: { - isOneOf: () => true, - isActive: () => true, - getType: () => 'platinum', - }, - }, -} as any; +const licenseCheckResultWithOutSecurity = { + ...licenseCheckResultWithSecurity, + isSecurityDisabled: true, +}; -const xpackMainPluginWithOutSecurityBasicLicense = { - info: { - isAvailable: () => true, - feature: (f: string) => { - switch (f) { - case 'ml': - return { isEnabled: () => true }; - case 'security': - return { isEnabled: () => false }; - } - }, - license: { - isOneOf: () => false, - isActive: () => true, - getType: () => 'basic', - }, - }, -} as any; +const licenseCheckResultWithOutSecurityBasicLicense = { + ...licenseCheckResultWithSecurity, + isSecurityDisabled: true, + type: 'basic', +}; -const xpackMainPluginWithSecurityBasicLicense = { - info: { - isAvailable: () => true, - feature: (f: string) => { - switch (f) { - case 'ml': - return { isEnabled: () => true }; - case 'security': - return { isEnabled: () => true }; - } - }, - license: { - isOneOf: () => false, - isActive: () => true, - getType: () => 'basic', - }, - }, -} as any; +const licenseCheckResultWithSecurityBasicLicense = { + ...licenseCheckResultWithSecurity, + type: 'basic', +}; const mlIsEnabled = async () => true; const mlIsNotEnabled = async () => false; @@ -99,7 +47,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('partialPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithSecurity, + licenseCheckResultWithSecurity, mlIsEnabled ); const { capabilities } = await getPrivileges(); @@ -114,7 +62,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('partialPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithSecurity, + licenseCheckResultWithSecurity, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -149,7 +97,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('fullPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithSecurity, + licenseCheckResultWithSecurity, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -184,7 +132,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('upgradeWithFullPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithSecurity, + licenseCheckResultWithSecurity, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -219,7 +167,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('upgradeWithPartialPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithSecurity, + licenseCheckResultWithSecurity, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -254,7 +202,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('partialPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithSecurityBasicLicense, + licenseCheckResultWithSecurityBasicLicense, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -289,7 +237,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('fullPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithSecurityBasicLicense, + licenseCheckResultWithSecurityBasicLicense, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -324,7 +272,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('fullPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithSecurity, + licenseCheckResultWithSecurity, mlIsNotEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -361,7 +309,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('partialPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithOutSecurity, + licenseCheckResultWithOutSecurity, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -396,7 +344,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('upgradeWithFullPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithOutSecurity, + licenseCheckResultWithOutSecurity, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -431,7 +379,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('upgradeWithPartialPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithOutSecurity, + licenseCheckResultWithOutSecurity, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -466,7 +414,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('partialPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithOutSecurityBasicLicense, + licenseCheckResultWithOutSecurityBasicLicense, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -501,7 +449,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('fullPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithOutSecurityBasicLicense, + licenseCheckResultWithOutSecurityBasicLicense, mlIsEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); @@ -536,7 +484,7 @@ describe('check_privileges', () => { const callWithRequest = callWithRequestProvider('partialPrivileges'); const { getPrivileges } = privilegesProvider( callWithRequest, - xpackMainPluginWithOutSecurity, + licenseCheckResultWithOutSecurity, mlIsNotEnabled ); const { capabilities, upgradeInProgress, mlFeatureEnabledInSpace } = await getPrivileges(); diff --git a/x-pack/legacy/plugins/ml/server/lib/check_privileges/check_privileges.ts b/x-pack/plugins/ml/server/lib/check_privileges/check_privileges.ts similarity index 94% rename from x-pack/legacy/plugins/ml/server/lib/check_privileges/check_privileges.ts rename to x-pack/plugins/ml/server/lib/check_privileges/check_privileges.ts index 617778afbe121b..a427780d13344a 100644 --- a/x-pack/legacy/plugins/ml/server/lib/check_privileges/check_privileges.ts +++ b/x-pack/plugins/ml/server/lib/check_privileges/check_privileges.ts @@ -5,12 +5,14 @@ */ import { IScopedClusterClient } from 'kibana/server'; -import { Privileges, getDefaultPrivileges } from '../../../common/types/privileges'; -import { XPackMainPlugin } from '../../../../xpack_main/server/xpack_main'; -import { isSecurityDisabled } from '../../lib/security_utils'; +import { + Privileges, + getDefaultPrivileges, +} from '../../../../../legacy/plugins/ml/common/types/privileges'; import { upgradeCheckProvider } from './upgrade'; import { checkLicense } from '../check_license'; -import { LICENSE_TYPE } from '../../../common/constants/license'; +import { LICENSE_TYPE } from '../../../../../legacy/plugins/ml/common/constants/license'; +import { LicenseCheckResult } from '../../types'; import { mlPrivileges } from './privileges'; @@ -25,7 +27,7 @@ interface Response { export function privilegesProvider( callAsCurrentUser: IScopedClusterClient['callAsCurrentUser'], - xpackMainPlugin: XPackMainPlugin, + licenseCheckResult: LicenseCheckResult, isMlEnabledInSpace: () => Promise, ignoreSpaces: boolean = false ) { @@ -35,8 +37,8 @@ export function privilegesProvider( const privileges = getDefaultPrivileges(); const upgradeInProgress = await isUpgradeInProgress(); - const securityDisabled = isSecurityDisabled(xpackMainPlugin); - const license = checkLicense(xpackMainPlugin.info); + const securityDisabled = licenseCheckResult.isSecurityDisabled; + const license = checkLicense(licenseCheckResult); const isPlatinumOrTrialLicense = license.licenseType === LICENSE_TYPE.FULL; const mlFeatureEnabledInSpace = await isMlEnabledInSpace(); diff --git a/x-pack/legacy/plugins/ml/server/lib/check_privileges/index.ts b/x-pack/plugins/ml/server/lib/check_privileges/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/check_privileges/index.ts rename to x-pack/plugins/ml/server/lib/check_privileges/index.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/check_privileges/privileges.ts b/x-pack/plugins/ml/server/lib/check_privileges/privileges.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/check_privileges/privileges.ts rename to x-pack/plugins/ml/server/lib/check_privileges/privileges.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/check_privileges/upgrade.ts b/x-pack/plugins/ml/server/lib/check_privileges/upgrade.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/check_privileges/upgrade.ts rename to x-pack/plugins/ml/server/lib/check_privileges/upgrade.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/ml_telemetry/index.ts b/x-pack/plugins/ml/server/lib/ml_telemetry/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/ml_telemetry/index.ts rename to x-pack/plugins/ml/server/lib/ml_telemetry/index.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/ml_telemetry/make_ml_usage_collector.ts b/x-pack/plugins/ml/server/lib/ml_telemetry/make_ml_usage_collector.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/ml_telemetry/make_ml_usage_collector.ts rename to x-pack/plugins/ml/server/lib/ml_telemetry/make_ml_usage_collector.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/ml_telemetry/ml_telemetry.test.ts b/x-pack/plugins/ml/server/lib/ml_telemetry/ml_telemetry.test.ts similarity index 85% rename from x-pack/legacy/plugins/ml/server/lib/ml_telemetry/ml_telemetry.test.ts rename to x-pack/plugins/ml/server/lib/ml_telemetry/ml_telemetry.test.ts index 9d14ffb31be631..c03396445f8687 100644 --- a/x-pack/legacy/plugins/ml/server/lib/ml_telemetry/ml_telemetry.test.ts +++ b/x-pack/plugins/ml/server/lib/ml_telemetry/ml_telemetry.test.ts @@ -55,10 +55,9 @@ describe('ml_telemetry', () => { }); describe('incrementFileDataVisualizerIndexCreationCount', () => { - let savedObjects: any; - let internalRepository: any; + let savedObjectsClient: any; - function createInternalRepositoryInstance( + function createSavedObjectsClientInstance( telemetryEnabled?: boolean, indexCreationCount?: number ) { @@ -93,42 +92,39 @@ describe('ml_telemetry', () => { } function mockInit(telemetryEnabled?: boolean, indexCreationCount?: number): void { - internalRepository = createInternalRepositoryInstance(telemetryEnabled, indexCreationCount); - savedObjects = { - createInternalRepository: jest.fn(() => internalRepository), - }; + savedObjectsClient = createSavedObjectsClientInstance(telemetryEnabled, indexCreationCount); } it('should not increment if telemetry status cannot be determined', async () => { mockInit(); - await incrementFileDataVisualizerIndexCreationCount(savedObjects); + await incrementFileDataVisualizerIndexCreationCount(savedObjectsClient); - expect(internalRepository.create.mock.calls).toHaveLength(0); + expect(savedObjectsClient.create.mock.calls).toHaveLength(0); }); it('should not increment if telemetry status is disabled', async () => { mockInit(false); - await incrementFileDataVisualizerIndexCreationCount(savedObjects); + await incrementFileDataVisualizerIndexCreationCount(savedObjectsClient); - expect(internalRepository.create.mock.calls).toHaveLength(0); + expect(savedObjectsClient.create.mock.calls).toHaveLength(0); }); it('should initialize index_creation_count with 1', async () => { mockInit(true); - await incrementFileDataVisualizerIndexCreationCount(savedObjects); + await incrementFileDataVisualizerIndexCreationCount(savedObjectsClient); - expect(internalRepository.create.mock.calls[0][0]).toBe('ml-telemetry'); - expect(internalRepository.create.mock.calls[0][1]).toEqual({ + expect(savedObjectsClient.create.mock.calls[0][0]).toBe('ml-telemetry'); + expect(savedObjectsClient.create.mock.calls[0][1]).toEqual({ file_data_visualizer: { index_creation_count: 1 }, }); }); it('should increment index_creation_count to 2', async () => { mockInit(true, 1); - await incrementFileDataVisualizerIndexCreationCount(savedObjects); + await incrementFileDataVisualizerIndexCreationCount(savedObjectsClient); - expect(internalRepository.create.mock.calls[0][0]).toBe('ml-telemetry'); - expect(internalRepository.create.mock.calls[0][1]).toEqual({ + expect(savedObjectsClient.create.mock.calls[0][0]).toBe('ml-telemetry'); + expect(savedObjectsClient.create.mock.calls[0][1]).toEqual({ file_data_visualizer: { index_creation_count: 2 }, }); }); diff --git a/x-pack/legacy/plugins/ml/server/lib/ml_telemetry/ml_telemetry.ts b/x-pack/plugins/ml/server/lib/ml_telemetry/ml_telemetry.ts similarity index 74% rename from x-pack/legacy/plugins/ml/server/lib/ml_telemetry/ml_telemetry.ts rename to x-pack/plugins/ml/server/lib/ml_telemetry/ml_telemetry.ts index d76b1ee94e21e9..8cf24213961b18 100644 --- a/x-pack/legacy/plugins/ml/server/lib/ml_telemetry/ml_telemetry.ts +++ b/x-pack/plugins/ml/server/lib/ml_telemetry/ml_telemetry.ts @@ -4,11 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - SavedObjectAttributes, - SavedObjectsServiceStart, - ISavedObjectsRepository, -} from 'src/core/server'; +import { SavedObjectAttributes, SavedObjectsClientContract } from 'src/core/server'; export interface MlTelemetry extends SavedObjectAttributes { file_data_visualizer: { @@ -31,21 +27,20 @@ export function createMlTelemetry(count: number = 0): MlTelemetry { } // savedObjects export function storeMlTelemetry( - internalRepository: ISavedObjectsRepository, + savedObjectsClient: SavedObjectsClientContract, mlTelemetry: MlTelemetry ): void { - internalRepository.create('ml-telemetry', mlTelemetry, { + savedObjectsClient.create('ml-telemetry', mlTelemetry, { id: ML_TELEMETRY_DOC_ID, overwrite: true, }); } export async function incrementFileDataVisualizerIndexCreationCount( - savedObjects: SavedObjectsServiceStart + savedObjectsClient: SavedObjectsClientContract ): Promise { - const internalRepository = await savedObjects.createInternalRepository(); try { - const { attributes } = await internalRepository.get('telemetry', 'telemetry'); + const { attributes } = await savedObjectsClient.get('telemetry', 'telemetry'); if (attributes.enabled === false) { return; @@ -59,7 +54,7 @@ export async function incrementFileDataVisualizerIndexCreationCount( let indicesCount = 1; try { - const { attributes } = (await internalRepository.get( + const { attributes } = (await savedObjectsClient.get( 'ml-telemetry', ML_TELEMETRY_DOC_ID )) as MlTelemetrySavedObject; @@ -69,5 +64,5 @@ export async function incrementFileDataVisualizerIndexCreationCount( } const mlTelemetry = createMlTelemetry(indicesCount); - storeMlTelemetry(internalRepository, mlTelemetry); + storeMlTelemetry(savedObjectsClient, mlTelemetry); } diff --git a/x-pack/legacy/plugins/ml/server/lib/query_utils.ts b/x-pack/plugins/ml/server/lib/query_utils.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/query_utils.ts rename to x-pack/plugins/ml/server/lib/query_utils.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/sample_data_sets/index.ts b/x-pack/plugins/ml/server/lib/sample_data_sets/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/sample_data_sets/index.ts rename to x-pack/plugins/ml/server/lib/sample_data_sets/index.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/sample_data_sets/sample_data_sets.ts b/x-pack/plugins/ml/server/lib/sample_data_sets/sample_data_sets.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/lib/sample_data_sets/sample_data_sets.ts rename to x-pack/plugins/ml/server/lib/sample_data_sets/sample_data_sets.ts diff --git a/x-pack/legacy/plugins/ml/server/lib/spaces_utils.ts b/x-pack/plugins/ml/server/lib/spaces_utils.ts similarity index 75% rename from x-pack/legacy/plugins/ml/server/lib/spaces_utils.ts rename to x-pack/plugins/ml/server/lib/spaces_utils.ts index 92373bae4ea1d0..ed684eadb95704 100644 --- a/x-pack/legacy/plugins/ml/server/lib/spaces_utils.ts +++ b/x-pack/plugins/ml/server/lib/spaces_utils.ts @@ -5,20 +5,19 @@ */ import { Request } from 'hapi'; -import { Space } from '../../../../../plugins/spaces/server'; -import { LegacySpacesPlugin } from '../../../spaces'; +import { Space, SpacesPluginSetup } from '../../../spaces/server'; interface GetActiveSpaceResponse { valid: boolean; space?: Space; } -export function spacesUtilsProvider(spacesPlugin: LegacySpacesPlugin, request: Request) { +export function spacesUtilsProvider(spacesPlugin: SpacesPluginSetup, request: Request) { async function activeSpace(): Promise { try { return { valid: true, - space: await spacesPlugin.getActiveSpace(request), + space: await spacesPlugin.spacesService.getActiveSpace(request), }; } catch (e) { return { diff --git a/x-pack/legacy/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_request.json b/x-pack/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_request.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_request.json rename to x-pack/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_request.json diff --git a/x-pack/legacy/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_response.json b/x-pack/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_response.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_response.json rename to x-pack/plugins/ml/server/models/annotation_service/__mocks__/get_annotations_response.json diff --git a/x-pack/legacy/plugins/ml/server/models/annotation_service/annotation.test.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts similarity index 96% rename from x-pack/legacy/plugins/ml/server/models/annotation_service/annotation.test.ts rename to x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts index 7e0649d15bfb0e..d7a13154a6f378 100644 --- a/x-pack/legacy/plugins/ml/server/models/annotation_service/annotation.test.ts +++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts @@ -8,9 +8,12 @@ import getAnnotationsRequestMock from './__mocks__/get_annotations_request.json' import getAnnotationsResponseMock from './__mocks__/get_annotations_response.json'; import { RequestHandlerContext } from 'src/core/server'; -import { ANNOTATION_TYPE } from '../../../common/constants/annotations'; -import { ML_ANNOTATIONS_INDEX_ALIAS_WRITE } from '../../../common/constants/index_patterns'; -import { Annotation, isAnnotations } from '../../../common/types/annotations'; +import { ANNOTATION_TYPE } from '../../../../../legacy/plugins/ml/common/constants/annotations'; +import { ML_ANNOTATIONS_INDEX_ALIAS_WRITE } from '../../../../../legacy/plugins/ml/common/constants/index_patterns'; +import { + Annotation, + isAnnotations, +} from '../../../../../legacy/plugins/ml/common/types/annotations'; import { DeleteParams, GetResponse, IndexAnnotationArgs } from './annotation'; import { annotationServiceProvider } from './index'; diff --git a/x-pack/legacy/plugins/ml/server/models/annotation_service/annotation.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts similarity index 96% rename from x-pack/legacy/plugins/ml/server/models/annotation_service/annotation.ts rename to x-pack/plugins/ml/server/models/annotation_service/annotation.ts index 399305ea2603eb..042d7bbc80653a 100644 --- a/x-pack/legacy/plugins/ml/server/models/annotation_service/annotation.ts +++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts @@ -8,18 +8,18 @@ import Boom from 'boom'; import _ from 'lodash'; import { RequestHandlerContext } from 'src/core/server'; -import { ANNOTATION_TYPE } from '../../../common/constants/annotations'; +import { ANNOTATION_TYPE } from '../../../../../legacy/plugins/ml/common/constants/annotations'; import { ML_ANNOTATIONS_INDEX_ALIAS_READ, ML_ANNOTATIONS_INDEX_ALIAS_WRITE, -} from '../../../common/constants/index_patterns'; +} from '../../../../../legacy/plugins/ml/common/constants/index_patterns'; import { Annotation, Annotations, isAnnotation, isAnnotations, -} from '../../../common/types/annotations'; +} from '../../../../../legacy/plugins/ml/common/types/annotations'; // TODO All of the following interface/type definitions should // eventually be replaced by the proper upstream definitions diff --git a/x-pack/legacy/plugins/ml/server/models/annotation_service/index.ts b/x-pack/plugins/ml/server/models/annotation_service/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/annotation_service/index.ts rename to x-pack/plugins/ml/server/models/annotation_service/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/__tests__/bucket_span_estimator.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/__tests__/bucket_span_estimator.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/__tests__/bucket_span_estimator.js rename to x-pack/plugins/ml/server/models/bucket_span_estimator/__tests__/bucket_span_estimator.js diff --git a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.d.ts b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.d.ts similarity index 75% rename from x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.d.ts rename to x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.d.ts index ea986feab4e997..e39a0177c31b95 100644 --- a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.d.ts +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.d.ts @@ -5,10 +5,10 @@ */ import { APICaller } from 'src/core/server'; -import { BucketSpanEstimatorData } from '../../../public/application/services/ml_api_service'; +import { BucketSpanEstimatorData } from '../../../../../legacy/plugins/ml/public/application/services/ml_api_service'; export function estimateBucketSpanFactory( callAsCurrentUser: APICaller, callAsInternalUser: APICaller, - xpackMainPlugin: any + isSecurityDisabled: boolean ): (config: BucketSpanEstimatorData) => Promise; diff --git a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js similarity index 98% rename from x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js rename to x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js index aec677dd57d614..53b9d75304963b 100644 --- a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js @@ -12,9 +12,11 @@ import { INTERVALS } from './intervals'; import { singleSeriesCheckerFactory } from './single_series_checker'; import { polledDataCheckerFactory } from './polled_data_checker'; -import { isSecurityDisabled } from '../../lib/security_utils'; - -export function estimateBucketSpanFactory(callAsCurrentUser, callAsInternalUser, xpackMainPlugin) { +export function estimateBucketSpanFactory( + callAsCurrentUser, + callAsInternalUser, + isSecurityDisabled +) { const PolledDataChecker = polledDataCheckerFactory(callAsCurrentUser); const SingleSeriesChecker = singleSeriesCheckerFactory(callAsCurrentUser); @@ -384,7 +386,7 @@ export function estimateBucketSpanFactory(callAsCurrentUser, callAsInternalUser, }); } - if (isSecurityDisabled(xpackMainPlugin)) { + if (isSecurityDisabled) { getBucketSpanEstimation(); } else { // if security is enabled, check that the user has permission to diff --git a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/index.ts b/x-pack/plugins/ml/server/models/bucket_span_estimator/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/index.ts rename to x-pack/plugins/ml/server/models/bucket_span_estimator/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/intervals.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/intervals.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/intervals.js rename to x-pack/plugins/ml/server/models/bucket_span_estimator/intervals.js diff --git a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js rename to x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js diff --git a/x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js rename to x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js diff --git a/x-pack/legacy/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.d.ts b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.d.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.d.ts rename to x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.d.ts diff --git a/x-pack/legacy/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.js b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.js rename to x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.js diff --git a/x-pack/legacy/plugins/ml/server/models/calculate_model_memory_limit/index.ts b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/calculate_model_memory_limit/index.ts rename to x-pack/plugins/ml/server/models/calculate_model_memory_limit/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/calendar/calendar_manager.ts b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/calendar/calendar_manager.ts rename to x-pack/plugins/ml/server/models/calendar/calendar_manager.ts diff --git a/x-pack/legacy/plugins/ml/server/models/calendar/event_manager.ts b/x-pack/plugins/ml/server/models/calendar/event_manager.ts similarity index 94% rename from x-pack/legacy/plugins/ml/server/models/calendar/event_manager.ts rename to x-pack/plugins/ml/server/models/calendar/event_manager.ts index 488839f68b3fe2..0a3108016da0e3 100644 --- a/x-pack/legacy/plugins/ml/server/models/calendar/event_manager.ts +++ b/x-pack/plugins/ml/server/models/calendar/event_manager.ts @@ -6,7 +6,7 @@ import Boom from 'boom'; -import { GLOBAL_CALENDAR } from '../../../common/constants/calendars'; +import { GLOBAL_CALENDAR } from '../../../../../legacy/plugins/ml/common/constants/calendars'; export interface CalendarEvent { calendar_id?: string; diff --git a/x-pack/legacy/plugins/ml/server/models/calendar/index.ts b/x-pack/plugins/ml/server/models/calendar/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/calendar/index.ts rename to x-pack/plugins/ml/server/models/calendar/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts b/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts similarity index 88% rename from x-pack/legacy/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts rename to x-pack/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts index abe389165182f0..a8757e289dcf75 100644 --- a/x-pack/legacy/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts +++ b/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_audit_messages.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { callWithRequestType } from '../../../common/types/kibana'; -import { ML_NOTIFICATION_INDEX_PATTERN } from '../../../common/constants/index_patterns'; -import { JobMessage } from '../../../common/types/audit_message'; +import { callWithRequestType } from '../../../../../legacy/plugins/ml/common/types/kibana'; +import { ML_NOTIFICATION_INDEX_PATTERN } from '../../../../../legacy/plugins/ml/common/constants/index_patterns'; +import { JobMessage } from '../../../../../legacy/plugins/ml/common/types/audit_message'; const SIZE = 50; diff --git a/x-pack/legacy/plugins/ml/server/models/data_frame_analytics/index.js b/x-pack/plugins/ml/server/models/data_frame_analytics/index.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_frame_analytics/index.js rename to x-pack/plugins/ml/server/models/data_frame_analytics/index.js diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/data_recognizer.test.ts b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.test.ts similarity index 97% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/data_recognizer.test.ts rename to x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.test.ts index de23950e5cc1c8..c51f65714bc055 100644 --- a/x-pack/legacy/plugins/ml/server/models/data_recognizer/data_recognizer.test.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.test.ts @@ -5,7 +5,7 @@ */ import { RequestHandlerContext } from 'kibana/server'; -import { Module } from '../../../common/types/modules'; +import { Module } from '../../../../../legacy/plugins/ml/common/types/modules'; import { DataRecognizer } from '../data_recognizer'; describe('ML - data recognizer', () => { diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/data_recognizer.ts b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts similarity index 99% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/data_recognizer.ts rename to x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts index 553de75e38e05d..8d2a6c9955da36 100644 --- a/x-pack/legacy/plugins/ml/server/models/data_recognizer/data_recognizer.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts @@ -10,7 +10,7 @@ import numeral from '@elastic/numeral'; import { CallAPIOptions, RequestHandlerContext, SavedObjectsClientContract } from 'kibana/server'; import { IndexPatternAttributes } from 'src/plugins/data/server'; import { merge } from 'lodash'; -import { MlJob } from '../../../common/types/jobs'; +import { MlJob } from '../../../../../legacy/plugins/ml/common/types/jobs'; import { KibanaObjects, ModuleDataFeed, @@ -23,8 +23,11 @@ import { JobResponse, KibanaObjectResponse, DataRecognizerConfigResponse, -} from '../../../common/types/modules'; -import { getLatestDataOrBucketTimestamp, prefixDatafeedId } from '../../../common/util/job_utils'; +} from '../../../../../legacy/plugins/ml/common/types/modules'; +import { + getLatestDataOrBucketTimestamp, + prefixDatafeedId, +} from '../../../../../legacy/plugins/ml/common/util/job_utils'; import { mlLog } from '../../client/log'; // @ts-ignore import { jobServiceProvider } from '../job_service'; diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/index.ts b/x-pack/plugins/ml/server/models/data_recognizer/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/index.ts rename to x-pack/plugins/ml/server/models/data_recognizer/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/search/ml_http_access_filebeat_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/search/ml_http_access_filebeat_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/search/ml_http_access_filebeat_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/search/ml_http_access_filebeat_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_map_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_map_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_map_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_map_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_low_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_low_request_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_low_request_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_low_request_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_request_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_request_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_request_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_url_count_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_url_count_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_url_count_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_source_ip_url_count_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_status_code_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_status_code_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_status_code_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_status_code_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_visitor_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_visitor_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_visitor_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/datafeed_visitor_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/low_request_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_request_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/source_ip_url_count_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/status_code_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apache_ecs/ml/visitor_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/abnormal_span_durations_jsbase.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/abnormal_span_durations_jsbase.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/abnormal_span_durations_jsbase.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/abnormal_span_durations_jsbase.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/anomalous_error_rate_for_user_agents_jsbase.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/anomalous_error_rate_for_user_agents_jsbase.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/anomalous_error_rate_for_user_agents_jsbase.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/anomalous_error_rate_for_user_agents_jsbase.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_abnormal_span_durations_jsbase.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_abnormal_span_durations_jsbase.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_abnormal_span_durations_jsbase.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_abnormal_span_durations_jsbase.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_anomalous_error_rate_for_user_agents_jsbase.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_anomalous_error_rate_for_user_agents_jsbase.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_anomalous_error_rate_for_user_agents_jsbase.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_anomalous_error_rate_for_user_agents_jsbase.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_decreased_throughput_jsbase.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_decreased_throughput_jsbase.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_decreased_throughput_jsbase.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_decreased_throughput_jsbase.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_high_count_by_user_agent_jsbase.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_high_count_by_user_agent_jsbase.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_high_count_by_user_agent_jsbase.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/datafeed_high_count_by_user_agent_jsbase.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/decreased_throughput_jsbase.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/decreased_throughput_jsbase.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/decreased_throughput_jsbase.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/decreased_throughput_jsbase.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/high_count_by_user_agent_jsbase.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/high_count_by_user_agent_jsbase.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/high_count_by_user_agent_jsbase.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_jsbase/ml/high_count_by_user_agent_jsbase.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_span_durations_nodejs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_span_durations_nodejs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_span_durations_nodejs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_span_durations_nodejs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_trace_durations_nodejs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_trace_durations_nodejs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_trace_durations_nodejs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/abnormal_trace_durations_nodejs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_span_durations_nodejs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_span_durations_nodejs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_span_durations_nodejs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_span_durations_nodejs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_trace_durations_nodejs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_trace_durations_nodejs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_trace_durations_nodejs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_abnormal_trace_durations_nodejs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_decreased_throughput_nodejs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_decreased_throughput_nodejs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_decreased_throughput_nodejs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/datafeed_decreased_throughput_nodejs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/decreased_throughput_nodejs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/decreased_throughput_nodejs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/decreased_throughput_nodejs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_nodejs/ml/decreased_throughput_nodejs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_transaction/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_transaction/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_transaction/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_transaction/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_transaction/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_transaction/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_transaction/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_transaction/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/datafeed_high_mean_response_time.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/datafeed_high_mean_response_time.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/datafeed_high_mean_response_time.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/datafeed_high_mean_response_time.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/high_mean_response_time.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/high_mean_response_time.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/high_mean_response_time.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/apm_transaction/ml/high_mean_response_time.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_event_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_event_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_event_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_event_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_explorer_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_explorer_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_explorer_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/dashboard/ml_auditbeat_docker_process_explorer_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/search/ml_auditbeat_docker_process_events_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/search/ml_auditbeat_docker_process_events_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/search/ml_auditbeat_docker_process_events_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/search/ml_auditbeat_docker_process_events_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_by_process_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_by_process_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_by_process_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_by_process_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_vis_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_vis_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_vis_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_event_rate_vis_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_occurrence_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_occurrence_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_occurrence_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/kibana/visualization/ml_auditbeat_docker_process_occurrence_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_high_count_process_events_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_high_count_process_events_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_high_count_process_events_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_high_count_process_events_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_rare_process_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_rare_process_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_rare_process_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/datafeed_docker_rare_process_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_high_count_process_events_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_docker_ecs/ml/docker_rare_process_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_event_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_event_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_event_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_event_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_explorer_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_explorer_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_explorer_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/dashboard/ml_auditbeat_hosts_process_explorer_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/search/ml_auditbeat_hosts_process_events_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/search/ml_auditbeat_hosts_process_events_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/search/ml_auditbeat_hosts_process_events_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/search/ml_auditbeat_hosts_process_events_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_by_process_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_by_process_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_by_process_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_by_process_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_vis_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_vis_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_vis_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_event_rate_vis_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_occurrence_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_occurrence_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_occurrence_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/kibana/visualization/ml_auditbeat_hosts_process_occurrence_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_high_count_process_events_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_high_count_process_events_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_high_count_process_events_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_high_count_process_events_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_rare_process_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_rare_process_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_rare_process_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/datafeed_hosts_rare_process_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_high_count_process_events_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/auditbeat_process_hosts_ecs/ml/hosts_rare_process_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/datafeed_log_entry_rate.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/datafeed_log_entry_rate.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/datafeed_log_entry_rate.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/datafeed_log_entry_rate.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/log_entry_rate.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/log_entry_rate.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/log_entry_rate.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_analysis/ml/log_entry_rate.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/datafeed_log_entry_categories_count.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/datafeed_log_entry_categories_count.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/datafeed_log_entry_categories_count.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/datafeed_log_entry_categories_count.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/log_entry_categories_count.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/log_entry_categories_count.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/log_entry_categories_count.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/logs_ui_categories/ml/log_entry_categories_count.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_high_mean_cpu_iowait_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_high_mean_cpu_iowait_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_high_mean_cpu_iowait_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_high_mean_cpu_iowait_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_max_disk_utilization_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_max_disk_utilization_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_max_disk_utilization_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_max_disk_utilization_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_metricbeat_outages_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_metricbeat_outages_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_metricbeat_outages_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/datafeed_metricbeat_outages_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/high_mean_cpu_iowait_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/high_mean_cpu_iowait_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/high_mean_cpu_iowait_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/high_mean_cpu_iowait_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/max_disk_utilization_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/max_disk_utilization_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/max_disk_utilization_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/max_disk_utilization_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/metricbeat_outages_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/metricbeat_outages_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/metricbeat_outages_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/metricbeat_system_ecs/ml/metricbeat_outages_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/dashboard/ml_http_access_explorer_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/search/ml_http_access_filebeat_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/search/ml_http_access_filebeat_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/search/ml_http_access_filebeat_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/search/ml_http_access_filebeat_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_events_timechart_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_map_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_map_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_map_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_map_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_source_ip_timechart_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_status_code_timechart_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_source_ips_table_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_top_urls_table_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/kibana/visualization/ml_http_access_unique_count_url_timechart_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_low_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_low_request_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_low_request_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_low_request_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_request_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_request_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_request_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_url_count_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_url_count_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_url_count_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_source_ip_url_count_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_status_code_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_status_code_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_status_code_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_status_code_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_visitor_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_visitor_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_visitor_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/datafeed_visitor_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/low_request_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_request_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/source_ip_url_count_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/status_code_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/nginx_ecs/ml/visitor_rate_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/datafeed_high_sum_total_sales.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/high_sum_total_sales.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/high_sum_total_sales.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/high_sum_total_sales.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_ecommerce/ml/high_sum_total_sales.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_low_request_rate.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_response_code_rates.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/datafeed_url_scanning.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/low_request_rate.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/low_request_rate.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/low_request_rate.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/low_request_rate.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/response_code_rates.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/response_code_rates.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/response_code_rates.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/response_code_rates.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/url_scanning.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/url_scanning.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/url_scanning.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/sample_data_weblogs/ml/url_scanning.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_port_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_port_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_port_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_port_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_service.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_service.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_service.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_service.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_url_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_url_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_url_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_network_url_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_process_all_hosts_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_process_all_hosts_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_process_all_hosts_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_process_all_hosts_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_user_name_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_user_name_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_user_name_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_linux_anomalous_user_name_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_rare_process_by_host_linux_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_rare_process_by_host_linux_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_rare_process_by_host_linux_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/datafeed_rare_process_by_host_linux_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/datafeed_suspicious_login_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/datafeed_suspicious_login_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/datafeed_suspicious_login_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/datafeed_suspicious_login_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_dns_tunneling.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_dns_tunneling.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_dns_tunneling.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_dns_tunneling.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_dns_question.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_dns_question.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_dns_question.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_dns_question.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_server_domain.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_server_domain.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_server_domain.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_server_domain.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_urls.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_urls.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_urls.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_urls.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_user_agent.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_user_agent.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_user_agent.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/datafeed_packetbeat_rare_user_agent.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_rare_process_by_host_windows_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_rare_process_by_host_windows_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_rare_process_by_host_windows_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_rare_process_by_host_windows_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_network_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_network_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_network_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_network_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_path_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_path_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_path_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_path_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_all_hosts_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_all_hosts_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_all_hosts_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_all_hosts_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_creation.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_creation.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_creation.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_process_creation.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_script.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_script.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_script.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_script.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_service.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_service.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_service.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_service.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_user_name_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_user_name_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_user_name_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_anomalous_user_name_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_rare_user_runas_event.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_rare_user_runas_event.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_rare_user_runas_event.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/datafeed_windows_rare_user_runas_event.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/logo.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/datafeed_windows_rare_user_type10_remote_login.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/datafeed_windows_rare_user_type10_remote_login.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/datafeed_windows_rare_user_type10_remote_login.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/datafeed_windows_rare_user_type10_remote_login.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json rename to x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json diff --git a/x-pack/legacy/plugins/ml/server/models/data_visualizer/data_visualizer.ts b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts similarity index 99% rename from x-pack/legacy/plugins/ml/server/models/data_visualizer/data_visualizer.ts rename to x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts index b0a61b1232dc0b..9463f74e1e746e 100644 --- a/x-pack/legacy/plugins/ml/server/models/data_visualizer/data_visualizer.ts +++ b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts @@ -6,8 +6,8 @@ import { CallAPIOptions, IScopedClusterClient } from 'src/core/server'; import _ from 'lodash'; -import { ML_JOB_FIELD_TYPES } from '../../../common/constants/field_types'; -import { getSafeAggregationName } from '../../../common/util/job_utils'; +import { ML_JOB_FIELD_TYPES } from '../../../../../legacy/plugins/ml/common/constants/field_types'; +import { getSafeAggregationName } from '../../../../../legacy/plugins/ml/common/util/job_utils'; import { buildBaseFilterCriteria, buildSamplerAggregation, diff --git a/x-pack/legacy/plugins/ml/server/models/data_visualizer/index.ts b/x-pack/plugins/ml/server/models/data_visualizer/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/data_visualizer/index.ts rename to x-pack/plugins/ml/server/models/data_visualizer/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/fields_service/fields_service.d.ts b/x-pack/plugins/ml/server/models/fields_service/fields_service.d.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/fields_service/fields_service.d.ts rename to x-pack/plugins/ml/server/models/fields_service/fields_service.d.ts diff --git a/x-pack/legacy/plugins/ml/server/models/fields_service/fields_service.js b/x-pack/plugins/ml/server/models/fields_service/fields_service.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/fields_service/fields_service.js rename to x-pack/plugins/ml/server/models/fields_service/fields_service.js diff --git a/x-pack/legacy/plugins/ml/server/models/fields_service/index.ts b/x-pack/plugins/ml/server/models/fields_service/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/fields_service/index.ts rename to x-pack/plugins/ml/server/models/fields_service/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/file_data_visualizer/file_data_visualizer.ts b/x-pack/plugins/ml/server/models/file_data_visualizer/file_data_visualizer.ts similarity index 95% rename from x-pack/legacy/plugins/ml/server/models/file_data_visualizer/file_data_visualizer.ts rename to x-pack/plugins/ml/server/models/file_data_visualizer/file_data_visualizer.ts index 9f30f609c60b63..1d0452f2337f95 100644 --- a/x-pack/legacy/plugins/ml/server/models/file_data_visualizer/file_data_visualizer.ts +++ b/x-pack/plugins/ml/server/models/file_data_visualizer/file_data_visualizer.ts @@ -6,7 +6,7 @@ import Boom from 'boom'; import { RequestHandlerContext } from 'kibana/server'; -import { FindFileStructureResponse } from '../../../common/types/file_datavisualizer'; +import { FindFileStructureResponse } from '../../../../../legacy/plugins/ml/common/types/file_datavisualizer'; export type InputData = any[]; diff --git a/x-pack/legacy/plugins/ml/server/models/file_data_visualizer/import_data.ts b/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts similarity index 97% rename from x-pack/legacy/plugins/ml/server/models/file_data_visualizer/import_data.ts rename to x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts index 008efb43a6c07e..e4de71ad0793d2 100644 --- a/x-pack/legacy/plugins/ml/server/models/file_data_visualizer/import_data.ts +++ b/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts @@ -5,7 +5,7 @@ */ import { RequestHandlerContext } from 'kibana/server'; -import { INDEX_META_DATA_CREATED_BY } from '../../../common/constants/file_datavisualizer'; +import { INDEX_META_DATA_CREATED_BY } from '../../../../../legacy/plugins/ml/common/constants/file_datavisualizer'; import { InputData } from './file_data_visualizer'; export interface Settings { diff --git a/x-pack/legacy/plugins/ml/server/models/file_data_visualizer/index.ts b/x-pack/plugins/ml/server/models/file_data_visualizer/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/file_data_visualizer/index.ts rename to x-pack/plugins/ml/server/models/file_data_visualizer/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/filter/filter_manager.ts b/x-pack/plugins/ml/server/models/filter/filter_manager.ts similarity index 98% rename from x-pack/legacy/plugins/ml/server/models/filter/filter_manager.ts rename to x-pack/plugins/ml/server/models/filter/filter_manager.ts index f40663a5eb6b2d..baba495257acac 100644 --- a/x-pack/legacy/plugins/ml/server/models/filter/filter_manager.ts +++ b/x-pack/plugins/ml/server/models/filter/filter_manager.ts @@ -7,7 +7,10 @@ import Boom from 'boom'; import { IScopedClusterClient } from 'src/core/server'; -import { DetectorRule, DetectorRuleScope } from '../../../common/types/detector_rules'; +import { + DetectorRule, + DetectorRuleScope, +} from '../../../../../legacy/plugins/ml/common/types/detector_rules'; export interface Filter { filter_id: string; diff --git a/x-pack/legacy/plugins/ml/server/models/filter/index.js b/x-pack/plugins/ml/server/models/filter/index.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/filter/index.js rename to x-pack/plugins/ml/server/models/filter/index.js diff --git a/x-pack/legacy/plugins/ml/server/models/filter/index.ts b/x-pack/plugins/ml/server/models/filter/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/filter/index.ts rename to x-pack/plugins/ml/server/models/filter/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/job_audit_messages/index.ts b/x-pack/plugins/ml/server/models/job_audit_messages/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_audit_messages/index.ts rename to x-pack/plugins/ml/server/models/job_audit_messages/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/job_audit_messages/job_audit_messages.d.ts b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.d.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_audit_messages/job_audit_messages.d.ts rename to x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.d.ts diff --git a/x-pack/legacy/plugins/ml/server/models/job_audit_messages/job_audit_messages.js b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js similarity index 98% rename from x-pack/legacy/plugins/ml/server/models/job_audit_messages/job_audit_messages.js rename to x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js index 2cdfc0ef4f4c5f..b434846d6f0f4c 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_audit_messages/job_audit_messages.js +++ b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ML_NOTIFICATION_INDEX_PATTERN } from '../../../common/constants/index_patterns'; +import { ML_NOTIFICATION_INDEX_PATTERN } from '../../../../../legacy/plugins/ml/common/constants/index_patterns'; import moment from 'moment'; const SIZE = 1000; diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/datafeeds.js b/x-pack/plugins/ml/server/models/job_service/datafeeds.js similarity index 97% rename from x-pack/legacy/plugins/ml/server/models/job_service/datafeeds.js rename to x-pack/plugins/ml/server/models/job_service/datafeeds.js index c3b54fff0682d8..961b712610512d 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/datafeeds.js +++ b/x-pack/plugins/ml/server/models/job_service/datafeeds.js @@ -5,7 +5,10 @@ */ import { i18n } from '@kbn/i18n'; -import { JOB_STATE, DATAFEED_STATE } from '../../../common/constants/states'; +import { + JOB_STATE, + DATAFEED_STATE, +} from '../../../../../legacy/plugins/ml/common/constants/states'; import { fillResultsWithTimeouts, isRequestTimeout } from './error_utils'; export function datafeedsProvider(callWithRequest) { diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/error_utils.js b/x-pack/plugins/ml/server/models/job_service/error_utils.js similarity index 94% rename from x-pack/legacy/plugins/ml/server/models/job_service/error_utils.js rename to x-pack/plugins/ml/server/models/job_service/error_utils.js index 6f25b5870f85ce..21e45110e70930 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/error_utils.js +++ b/x-pack/plugins/ml/server/models/job_service/error_utils.js @@ -5,7 +5,10 @@ */ import { i18n } from '@kbn/i18n'; -import { JOB_STATE, DATAFEED_STATE } from '../../../common/constants/states'; +import { + JOB_STATE, + DATAFEED_STATE, +} from '../../../../../legacy/plugins/ml/common/constants/states'; const REQUEST_TIMEOUT = 'RequestTimeout'; diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/groups.js b/x-pack/plugins/ml/server/models/job_service/groups.js similarity index 95% rename from x-pack/legacy/plugins/ml/server/models/job_service/groups.js rename to x-pack/plugins/ml/server/models/job_service/groups.js index 6fbc071ef9854f..b30e9cdc6048b7 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/groups.js +++ b/x-pack/plugins/ml/server/models/job_service/groups.js @@ -5,7 +5,7 @@ */ import { CalendarManager } from '../calendar'; -import { GLOBAL_CALENDAR } from '../../../common/constants/calendars'; +import { GLOBAL_CALENDAR } from '../../../../../legacy/plugins/ml/common/constants/calendars'; export function groupsProvider(callWithRequest) { const calMngr = new CalendarManager(callWithRequest); diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/index.js b/x-pack/plugins/ml/server/models/job_service/index.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/index.js rename to x-pack/plugins/ml/server/models/job_service/index.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/jobs.js b/x-pack/plugins/ml/server/models/job_service/jobs.js similarity index 98% rename from x-pack/legacy/plugins/ml/server/models/job_service/jobs.js rename to x-pack/plugins/ml/server/models/job_service/jobs.js index b4b476c1f926ea..16d3c30bb0a280 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/jobs.js +++ b/x-pack/plugins/ml/server/models/job_service/jobs.js @@ -5,7 +5,10 @@ */ import { i18n } from '@kbn/i18n'; -import { JOB_STATE, DATAFEED_STATE } from '../../../common/constants/states'; +import { + JOB_STATE, + DATAFEED_STATE, +} from '../../../../../legacy/plugins/ml/common/constants/states'; import { datafeedsProvider } from './datafeeds'; import { jobAuditMessagesProvider } from '../job_audit_messages'; import { resultsServiceProvider } from '../results_service'; @@ -14,7 +17,7 @@ import { fillResultsWithTimeouts, isRequestTimeout } from './error_utils'; import { getLatestDataOrBucketTimestamp, isTimeSeriesViewJob, -} from '../../../common/util/job_utils'; +} from '../../../../../legacy/plugins/ml/common/util/job_utils'; import { groupsProvider } from './groups'; import { uniq } from 'lodash'; diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/examples.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts similarity index 95% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/examples.ts rename to x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts index ea2c71b04f56d2..1a098fdf16bb7c 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/examples.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts @@ -6,13 +6,13 @@ import { chunk } from 'lodash'; import { SearchResponse } from 'elasticsearch'; -import { CATEGORY_EXAMPLES_SAMPLE_SIZE } from '../../../../../common/constants/new_job'; +import { CATEGORY_EXAMPLES_SAMPLE_SIZE } from '../../../../../../../legacy/plugins/ml/common/constants/new_job'; import { Token, CategorizationAnalyzer, CategoryFieldExample, -} from '../../../../../common/types/categories'; -import { callWithRequestType } from '../../../../../common/types/kibana'; +} from '../../../../../../../legacy/plugins/ml/common/types/categories'; +import { callWithRequestType } from '../../../../../../../legacy/plugins/ml/common/types/kibana'; import { ValidationResults } from './validation_results'; const CHUNK_SIZE = 100; diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/index.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/index.ts rename to x-pack/plugins/ml/server/models/job_service/new_job/categorization/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts similarity index 92% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts rename to x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts index 3361cc454e2b7b..c8eb0002a31c80 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts @@ -5,9 +5,12 @@ */ import { SearchResponse } from 'elasticsearch'; -import { ML_RESULTS_INDEX_PATTERN } from '../../../../../common/constants/index_patterns'; -import { CategoryId, Category } from '../../../../../common/types/categories'; -import { callWithRequestType } from '../../../../../common/types/kibana'; +import { ML_RESULTS_INDEX_PATTERN } from '../../../../../../../legacy/plugins/ml/common/constants/index_patterns'; +import { + CategoryId, + Category, +} from '../../../../../../../legacy/plugins/ml/common/types/categories'; +import { callWithRequestType } from '../../../../../../../legacy/plugins/ml/common/types/kibana'; export function topCategoriesProvider(callWithRequest: callWithRequestType) { async function getTotalCategories(jobId: string): Promise<{ total: number }> { diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts similarity index 96% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts rename to x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts index 34e63eabb405ef..bb1106b4d6396f 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts @@ -9,13 +9,13 @@ import { CATEGORY_EXAMPLES_VALIDATION_STATUS, CATEGORY_EXAMPLES_ERROR_LIMIT, CATEGORY_EXAMPLES_WARNING_LIMIT, -} from '../../../../../common/constants/new_job'; +} from '../../../../../../../legacy/plugins/ml/common/constants/new_job'; import { FieldExampleCheck, CategoryFieldExample, VALIDATION_RESULT, -} from '../../../../../common/types/categories'; -import { getMedianStringLength } from '../../../../../common/util/string_utils'; +} from '../../../../../../../legacy/plugins/ml/common/types/categories'; +import { getMedianStringLength } from '../../../../../../../legacy/plugins/ml/common/util/string_utils'; const VALID_TOKEN_COUNT = 3; const MEDIAN_LINE_LENGTH_LIMIT = 400; diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/charts.ts b/x-pack/plugins/ml/server/models/job_service/new_job/charts.ts similarity index 87% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job/charts.ts rename to x-pack/plugins/ml/server/models/job_service/new_job/charts.ts index 88ae8caa91e4a1..e662e3ca03ded6 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/charts.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/charts.ts @@ -6,7 +6,7 @@ import { newJobLineChartProvider } from './line_chart'; import { newJobPopulationChartProvider } from './population_chart'; -import { callWithRequestType } from '../../../../common/types/kibana'; +import { callWithRequestType } from '../../../../../../legacy/plugins/ml/common/types/kibana'; export function newJobChartsProvider(callWithRequest: callWithRequestType) { const { newJobLineChart } = newJobLineChartProvider(callWithRequest); diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/index.ts b/x-pack/plugins/ml/server/models/job_service/new_job/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job/index.ts rename to x-pack/plugins/ml/server/models/job_service/new_job/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/line_chart.ts b/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts similarity index 92% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job/line_chart.ts rename to x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts index c1a5ad5e38ecc9..3dfe935c655d5c 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/line_chart.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts @@ -5,9 +5,12 @@ */ import { get } from 'lodash'; -import { AggFieldNamePair, EVENT_RATE_FIELD_ID } from '../../../../common/types/fields'; -import { callWithRequestType } from '../../../../common/types/kibana'; -import { ML_MEDIAN_PERCENTS } from '../../../../common/util/job_utils'; +import { + AggFieldNamePair, + EVENT_RATE_FIELD_ID, +} from '../../../../../../legacy/plugins/ml/common/types/fields'; +import { callWithRequestType } from '../../../../../../legacy/plugins/ml/common/types/kibana'; +import { ML_MEDIAN_PERCENTS } from '../../../../../../legacy/plugins/ml/common/util/job_utils'; type DtrIndex = number; type TimeStamp = number; diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/population_chart.ts b/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts similarity index 95% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job/population_chart.ts rename to x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts index ee35f13c44ee60..d1ef9773f8f179 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job/population_chart.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts @@ -5,9 +5,12 @@ */ import { get } from 'lodash'; -import { AggFieldNamePair, EVENT_RATE_FIELD_ID } from '../../../../common/types/fields'; -import { callWithRequestType } from '../../../../common/types/kibana'; -import { ML_MEDIAN_PERCENTS } from '../../../../common/util/job_utils'; +import { + AggFieldNamePair, + EVENT_RATE_FIELD_ID, +} from '../../../../../../legacy/plugins/ml/common/types/fields'; +import { callWithRequestType } from '../../../../../../legacy/plugins/ml/common/types/kibana'; +import { ML_MEDIAN_PERCENTS } from '../../../../../../legacy/plugins/ml/common/util/job_utils'; const OVER_FIELD_EXAMPLES_COUNT = 40; diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/cloudwatch_field_caps.json b/x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/cloudwatch_field_caps.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/cloudwatch_field_caps.json rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/cloudwatch_field_caps.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/farequote_field_caps.json b/x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/farequote_field_caps.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/farequote_field_caps.json rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/farequote_field_caps.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/kibana_saved_objects.json b/x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/kibana_saved_objects.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/kibana_saved_objects.json rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/kibana_saved_objects.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/rollup_caps.json b/x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/rollup_caps.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/rollup_caps.json rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/responses/rollup_caps.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/cloudwatch_rollup_job_caps.json b/x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/cloudwatch_rollup_job_caps.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/cloudwatch_rollup_job_caps.json rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/cloudwatch_rollup_job_caps.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps.json b/x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps.json rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps_empty.json b/x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps_empty.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps_empty.json rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/__mocks__/results/farequote_job_caps_empty.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/aggregations.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/aggregations.ts similarity index 97% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/aggregations.ts rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/aggregations.ts index efe06f8b5ad4ab..475612f276c724 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/aggregations.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/aggregations.ts @@ -4,12 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Aggregation, METRIC_AGG_TYPE } from '../../../../common/types/fields'; +import { + Aggregation, + METRIC_AGG_TYPE, +} from '../../../../../../legacy/plugins/ml/common/types/fields'; import { ML_JOB_AGGREGATION, KIBANA_AGGREGATION, ES_AGGREGATION, -} from '../../../../common/constants/aggregation_types'; +} from '../../../../../../legacy/plugins/ml/common/constants/aggregation_types'; // aggregation object missing id, title and fields and has null for kibana and dsl aggregation names. // this is used as the basis for the ML only aggregations diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/field_service.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts similarity index 96% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/field_service.ts rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts index 5827201a636619..446c71dd40f684 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/field_service.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts @@ -12,9 +12,9 @@ import { FieldId, NewJobCaps, METRIC_AGG_TYPE, -} from '../../../../common/types/fields'; -import { ES_FIELD_TYPES } from '../../../../../../../../src/plugins/data/server'; -import { ML_JOB_AGGREGATION } from '../../../../common/constants/aggregation_types'; +} from '../../../../../../legacy/plugins/ml/common/types/fields'; +import { ES_FIELD_TYPES } from '../../../../../../../src/plugins/data/server'; +import { ML_JOB_AGGREGATION } from '../../../../../../legacy/plugins/ml/common/constants/aggregation_types'; import { rollupServiceProvider, RollupJob, RollupFields } from './rollup'; import { aggregations, mlOnlyAggregations } from './aggregations'; diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/index.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/index.ts rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts similarity index 93% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts index 3a9d979ccb22ca..0a967c760a1932 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts @@ -5,7 +5,11 @@ */ import { SavedObjectsClientContract } from 'kibana/server'; -import { Aggregation, Field, NewJobCaps } from '../../../../common/types/fields'; +import { + Aggregation, + Field, + NewJobCaps, +} from '../../../../../../legacy/plugins/ml/common/types/fields'; import { fieldServiceProvider } from './field_service'; interface NewJobCapsResponse { diff --git a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/rollup.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts similarity index 92% rename from x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/rollup.ts rename to x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts index 1e9ce3d8d50225..4cbdfe4f360e03 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_service/new_job_caps/rollup.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts @@ -7,8 +7,8 @@ import { SavedObject } from 'src/core/server'; import { IndexPatternAttributes } from 'src/plugins/data/server'; import { SavedObjectsClientContract } from 'kibana/server'; -import { FieldId } from '../../../../common/types/fields'; -import { ES_AGGREGATION } from '../../../../common/constants/aggregation_types'; +import { FieldId } from '../../../../../../legacy/plugins/ml/common/types/fields'; +import { ES_AGGREGATION } from '../../../../../../legacy/plugins/ml/common/constants/aggregation_types'; export type RollupFields = Record]>; diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/job_validation.js b/x-pack/plugins/ml/server/models/job_validation/__tests__/job_validation.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/job_validation.js rename to x-pack/plugins/ml/server/models/job_validation/__tests__/job_validation.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_farequote_cardinality.json b/x-pack/plugins/ml/server/models/job_validation/__tests__/mock_farequote_cardinality.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_farequote_cardinality.json rename to x-pack/plugins/ml/server/models/job_validation/__tests__/mock_farequote_cardinality.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_farequote_search_response.json b/x-pack/plugins/ml/server/models/job_validation/__tests__/mock_farequote_search_response.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_farequote_search_response.json rename to x-pack/plugins/ml/server/models/job_validation/__tests__/mock_farequote_search_response.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_field_caps.json b/x-pack/plugins/ml/server/models/job_validation/__tests__/mock_field_caps.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_field_caps.json rename to x-pack/plugins/ml/server/models/job_validation/__tests__/mock_field_caps.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_it_search_response.json b/x-pack/plugins/ml/server/models/job_validation/__tests__/mock_it_search_response.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_it_search_response.json rename to x-pack/plugins/ml/server/models/job_validation/__tests__/mock_it_search_response.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_time_field.json b/x-pack/plugins/ml/server/models/job_validation/__tests__/mock_time_field.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_time_field.json rename to x-pack/plugins/ml/server/models/job_validation/__tests__/mock_time_field.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_time_field_nested.json b/x-pack/plugins/ml/server/models/job_validation/__tests__/mock_time_field_nested.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_time_field_nested.json rename to x-pack/plugins/ml/server/models/job_validation/__tests__/mock_time_field_nested.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_time_range.json b/x-pack/plugins/ml/server/models/job_validation/__tests__/mock_time_range.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/mock_time_range.json rename to x-pack/plugins/ml/server/models/job_validation/__tests__/mock_time_range.json diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_bucket_span.js b/x-pack/plugins/ml/server/models/job_validation/__tests__/validate_bucket_span.js similarity index 98% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_bucket_span.js rename to x-pack/plugins/ml/server/models/job_validation/__tests__/validate_bucket_span.js index 3dc2bee1e8705f..023e0f5b614ed8 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_bucket_span.js +++ b/x-pack/plugins/ml/server/models/job_validation/__tests__/validate_bucket_span.js @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { validateBucketSpan } from '../validate_bucket_span'; -import { SKIP_BUCKET_SPAN_ESTIMATION } from '../../../../common/constants/validation'; +import { SKIP_BUCKET_SPAN_ESTIMATION } from '../../../../../../legacy/plugins/ml/common/constants/validation'; // farequote2017 snapshot snapshot mock search response // it returns a mock for the response of PolledDataChecker's search request diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_cardinality.js b/x-pack/plugins/ml/server/models/job_validation/__tests__/validate_cardinality.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_cardinality.js rename to x-pack/plugins/ml/server/models/job_validation/__tests__/validate_cardinality.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_influencers.js b/x-pack/plugins/ml/server/models/job_validation/__tests__/validate_influencers.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_influencers.js rename to x-pack/plugins/ml/server/models/job_validation/__tests__/validate_influencers.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_model_memory_limit.js b/x-pack/plugins/ml/server/models/job_validation/__tests__/validate_model_memory_limit.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_model_memory_limit.js rename to x-pack/plugins/ml/server/models/job_validation/__tests__/validate_model_memory_limit.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_time_range.js b/x-pack/plugins/ml/server/models/job_validation/__tests__/validate_time_range.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/__tests__/validate_time_range.js rename to x-pack/plugins/ml/server/models/job_validation/__tests__/validate_time_range.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/index.ts b/x-pack/plugins/ml/server/models/job_validation/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/index.ts rename to x-pack/plugins/ml/server/models/job_validation/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/job_validation.d.ts b/x-pack/plugins/ml/server/models/job_validation/job_validation.d.ts similarity index 83% rename from x-pack/legacy/plugins/ml/server/models/job_validation/job_validation.d.ts rename to x-pack/plugins/ml/server/models/job_validation/job_validation.d.ts index 4580602b0af238..bb8a372eaba30c 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_validation/job_validation.d.ts +++ b/x-pack/plugins/ml/server/models/job_validation/job_validation.d.ts @@ -6,7 +6,7 @@ import { APICaller } from 'src/core/server'; import { TypeOf } from '@kbn/config-schema'; -import { validateJobSchema } from '../../new_platform/job_validation_schema'; +import { validateJobSchema } from '../../routes/schemas/job_validation_schema'; type ValidateJobPayload = TypeOf; @@ -15,5 +15,5 @@ export function validateJob( payload: ValidateJobPayload, kbnVersion: string, callAsInternalUser: APICaller, - xpackMainPlugin: any + isSecurityDisabled: boolean ): string[]; diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/job_validation.js b/x-pack/plugins/ml/server/models/job_validation/job_validation.js similarity index 94% rename from x-pack/legacy/plugins/ml/server/models/job_validation/job_validation.js rename to x-pack/plugins/ml/server/models/job_validation/job_validation.js index ab1fbb39ee7062..d453c9add97d11 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_validation/job_validation.js +++ b/x-pack/plugins/ml/server/models/job_validation/job_validation.js @@ -8,11 +8,14 @@ import { i18n } from '@kbn/i18n'; import Boom from 'boom'; import { fieldsServiceProvider } from '../fields_service'; -import { renderTemplate } from '../../../common/util/string_utils'; +import { renderTemplate } from '../../../../../legacy/plugins/ml/common/util/string_utils'; import { getMessages } from './messages'; -import { VALIDATION_STATUS } from '../../../common/constants/validation'; +import { VALIDATION_STATUS } from '../../../../../legacy/plugins/ml/common/constants/validation'; -import { basicJobValidation, uniqWithIsEqual } from '../../../common/util/job_utils'; +import { + basicJobValidation, + uniqWithIsEqual, +} from '../../../../../legacy/plugins/ml/common/util/job_utils'; import { validateBucketSpan } from './validate_bucket_span'; import { validateCardinality } from './validate_cardinality'; import { validateInfluencers } from './validate_influencers'; @@ -24,7 +27,7 @@ export async function validateJob( payload, kbnVersion = 'current', callAsInternalUser, - xpackMainPlugin + isSecurityDisabled ) { const messages = getMessages(); @@ -112,7 +115,7 @@ export async function validateJob( job, duration, callAsInternalUser, - xpackMainPlugin + isSecurityDisabled )) ); validationMessages.push(...(await validateTimeRange(callWithRequest, job, duration))); diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/messages.js b/x-pack/plugins/ml/server/models/job_validation/messages.js similarity index 99% rename from x-pack/legacy/plugins/ml/server/models/job_validation/messages.js rename to x-pack/plugins/ml/server/models/job_validation/messages.js index 2c0c218bf86b51..33931f03facc3a 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_validation/messages.js +++ b/x-pack/plugins/ml/server/models/job_validation/messages.js @@ -5,7 +5,7 @@ */ import { i18n } from '@kbn/i18n'; -import { JOB_ID_MAX_LENGTH } from '../../../common/constants/validation'; +import { JOB_ID_MAX_LENGTH } from '../../../../../legacy/plugins/ml/common/constants/validation'; let messages; diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_bucket_span.js b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js similarity index 93% rename from x-pack/legacy/plugins/ml/server/models/job_validation/validate_bucket_span.js rename to x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js index 2914f086c1a83e..9e96e2219fb0f5 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_bucket_span.js +++ b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js @@ -5,9 +5,9 @@ */ import { estimateBucketSpanFactory } from '../../models/bucket_span_estimator'; -import { mlFunctionToESAggregation } from '../../../common/util/job_utils'; -import { SKIP_BUCKET_SPAN_ESTIMATION } from '../../../common/constants/validation'; -import { parseInterval } from '../../../common/util/parse_interval'; +import { mlFunctionToESAggregation } from '../../../../../legacy/plugins/ml/common/util/job_utils'; +import { SKIP_BUCKET_SPAN_ESTIMATION } from '../../../../../legacy/plugins/ml/common/constants/validation'; +import { parseInterval } from '../../../../../legacy/plugins/ml/common/util/parse_interval'; import { validateJobObject } from './validate_job_object'; @@ -51,7 +51,7 @@ export async function validateBucketSpan( job, duration, callAsInternalUser, - xpackMainPlugin + isSecurityDisabled ) { validateJobObject(job); @@ -124,7 +124,7 @@ export async function validateBucketSpan( estimateBucketSpanFactory( callWithRequest, callAsInternalUser, - xpackMainPlugin + isSecurityDisabled )(data) .then(resolve) // this catch gets triggered when the estimation code runs without error diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_cardinality.d.ts b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.d.ts similarity index 78% rename from x-pack/legacy/plugins/ml/server/models/job_validation/validate_cardinality.d.ts rename to x-pack/plugins/ml/server/models/job_validation/validate_cardinality.d.ts index dc109055337889..d3930ecf44c8d5 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_cardinality.d.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.d.ts @@ -5,7 +5,10 @@ */ import { APICaller } from 'src/core/server'; -import { Job, Datafeed } from '../../../public/application/jobs/new_job/common/job_creator/configs'; +import { + Job, + Datafeed, +} from '../../../../../legacy/plugins/ml/public/application/jobs/new_job/common/job_creator/configs'; interface ValidateCardinalityConfig extends Job { datafeed_config?: Datafeed; diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_cardinality.js b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/validate_cardinality.js rename to x-pack/plugins/ml/server/models/job_validation/validate_cardinality.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_influencers.js b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/validate_influencers.js rename to x-pack/plugins/ml/server/models/job_validation/validate_influencers.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_job_object.js b/x-pack/plugins/ml/server/models/job_validation/validate_job_object.js similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/job_validation/validate_job_object.js rename to x-pack/plugins/ml/server/models/job_validation/validate_job_object.js diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_model_memory_limit.js b/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.js similarity index 98% rename from x-pack/legacy/plugins/ml/server/models/job_validation/validate_model_memory_limit.js rename to x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.js index 733ed9c3c22c67..354a3124a534f7 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_model_memory_limit.js +++ b/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.js @@ -7,7 +7,7 @@ import numeral from '@elastic/numeral'; import { validateJobObject } from './validate_job_object'; import { calculateModelMemoryLimitProvider } from '../../models/calculate_model_memory_limit'; -import { ALLOWED_DATA_UNITS } from '../../../common/constants/validation'; +import { ALLOWED_DATA_UNITS } from '../../../../../legacy/plugins/ml/common/constants/validation'; // The minimum value the backend expects is 1MByte const MODEL_MEMORY_LIMIT_MINIMUM_BYTES = 1048576; diff --git a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_time_range.js b/x-pack/plugins/ml/server/models/job_validation/validate_time_range.js similarity index 93% rename from x-pack/legacy/plugins/ml/server/models/job_validation/validate_time_range.js rename to x-pack/plugins/ml/server/models/job_validation/validate_time_range.js index df14d372664961..e6a92b45649b0d 100644 --- a/x-pack/legacy/plugins/ml/server/models/job_validation/validate_time_range.js +++ b/x-pack/plugins/ml/server/models/job_validation/validate_time_range.js @@ -6,8 +6,8 @@ import _ from 'lodash'; -import { ES_FIELD_TYPES } from '../../../../../../../src/plugins/data/server'; -import { parseInterval } from '../../../common/util/parse_interval'; +import { ES_FIELD_TYPES } from '../../../../../../src/plugins/data/server'; +import { parseInterval } from '../../../../../legacy/plugins/ml/common/util/parse_interval'; import { validateJobObject } from './validate_job_object'; const BUCKET_SPAN_COMPARE_FACTOR = 25; diff --git a/x-pack/legacy/plugins/ml/server/models/results_service/build_anomaly_table_items.d.ts b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.d.ts similarity index 89% rename from x-pack/legacy/plugins/ml/server/models/results_service/build_anomaly_table_items.d.ts rename to x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.d.ts index 2bd19985c85189..f2d74fb9152996 100644 --- a/x-pack/legacy/plugins/ml/server/models/results_service/build_anomaly_table_items.d.ts +++ b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.d.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { AnomalyRecordDoc } from '../../../common/types/anomalies'; +import { AnomalyRecordDoc } from '../../../../../legacy/plugins/ml/common/types/anomalies'; export interface AnomaliesTableRecord { time: number; diff --git a/x-pack/legacy/plugins/ml/server/models/results_service/build_anomaly_table_items.js b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js similarity index 99% rename from x-pack/legacy/plugins/ml/server/models/results_service/build_anomaly_table_items.js rename to x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js index 4934a0ba07081e..fc4280c74994d9 100644 --- a/x-pack/legacy/plugins/ml/server/models/results_service/build_anomaly_table_items.js +++ b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js @@ -12,7 +12,7 @@ import { getEntityFieldValue, showActualForFunction, showTypicalForFunction, -} from '../../../common/util/anomaly_utils'; +} from '../../../../../legacy/plugins/ml/common/util/anomaly_utils'; // Builds the items for display in the anomalies table from the supplied list of anomaly records. // Provide the timezone to use for aggregating anomalies (by day or hour) as set in the diff --git a/x-pack/legacy/plugins/ml/server/models/results_service/get_partition_fields_values.ts b/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts similarity index 95% rename from x-pack/legacy/plugins/ml/server/models/results_service/get_partition_fields_values.ts rename to x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts index 99eeaacc8de9cd..5d536059cb0a27 100644 --- a/x-pack/legacy/plugins/ml/server/models/results_service/get_partition_fields_values.ts +++ b/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts @@ -5,8 +5,8 @@ */ import Boom from 'boom'; -import { ML_RESULTS_INDEX_PATTERN } from '../../../common/constants/index_patterns'; -import { callWithRequestType } from '../../../common/types/kibana'; +import { ML_RESULTS_INDEX_PATTERN } from '../../../../../legacy/plugins/ml/common/constants/index_patterns'; +import { callWithRequestType } from '../../../../../legacy/plugins/ml/common/types/kibana'; import { CriteriaField } from './results_service'; const PARTITION_FIELDS = ['partition_field', 'over_field', 'by_field'] as const; diff --git a/x-pack/legacy/plugins/ml/server/models/results_service/index.ts b/x-pack/plugins/ml/server/models/results_service/index.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/models/results_service/index.ts rename to x-pack/plugins/ml/server/models/results_service/index.ts diff --git a/x-pack/legacy/plugins/ml/server/models/results_service/results_service.ts b/x-pack/plugins/ml/server/models/results_service/results_service.ts similarity index 97% rename from x-pack/legacy/plugins/ml/server/models/results_service/results_service.ts rename to x-pack/plugins/ml/server/models/results_service/results_service.ts index 555a58fbb53335..324cbb91ca8c10 100644 --- a/x-pack/legacy/plugins/ml/server/models/results_service/results_service.ts +++ b/x-pack/plugins/ml/server/models/results_service/results_service.ts @@ -9,10 +9,10 @@ import moment from 'moment'; import { SearchResponse } from 'elasticsearch'; import { RequestHandlerContext } from 'kibana/server'; import { buildAnomalyTableItems, AnomaliesTableRecord } from './build_anomaly_table_items'; -import { ML_RESULTS_INDEX_PATTERN } from '../../../common/constants/index_patterns'; -import { ANOMALIES_TABLE_DEFAULT_QUERY_SIZE } from '../../../common/constants/search'; +import { ML_RESULTS_INDEX_PATTERN } from '../../../../../legacy/plugins/ml/common/constants/index_patterns'; +import { ANOMALIES_TABLE_DEFAULT_QUERY_SIZE } from '../../../../../legacy/plugins/ml/common/constants/search'; import { getPartitionFieldsValuesFactory } from './get_partition_fields_values'; -import { AnomalyRecordDoc } from '../../../common/types/anomalies'; +import { AnomalyRecordDoc } from '../../../../../legacy/plugins/ml/common/types/anomalies'; // Service for carrying out Elasticsearch queries to obtain data for the // ML Results dashboards. diff --git a/x-pack/plugins/ml/server/plugin.ts b/x-pack/plugins/ml/server/plugin.ts new file mode 100644 index 00000000000000..b5adf1fedec791 --- /dev/null +++ b/x-pack/plugins/ml/server/plugin.ts @@ -0,0 +1,168 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { CoreSetup, IScopedClusterClient, Logger, PluginInitializerContext } from 'src/core/server'; +import { LicenseCheckResult, PluginsSetup, RouteInitialization } from './types'; +import { PLUGIN_ID } from '../../../legacy/plugins/ml/common/constants/app'; +import { VALID_FULL_LICENSE_MODES } from '../../../legacy/plugins/ml/common/constants/license'; + +// @ts-ignore: could not find declaration file for module +import { elasticsearchJsPlugin } from './client/elasticsearch_ml'; +import { makeMlUsageCollector } from './lib/ml_telemetry'; +import { initMlServerLog } from './client/log'; +import { addLinksToSampleDatasets } from './lib/sample_data_sets'; + +import { annotationRoutes } from './routes/annotations'; +import { calendars } from './routes/calendars'; +import { dataFeedRoutes } from './routes/datafeeds'; +import { dataFrameAnalyticsRoutes } from './routes/data_frame_analytics'; +import { dataRecognizer } from './routes/modules'; +import { dataVisualizerRoutes } from './routes/data_visualizer'; +import { fieldsService } from './routes/fields_service'; +import { fileDataVisualizerRoutes } from './routes/file_data_visualizer'; +import { filtersRoutes } from './routes/filters'; +import { indicesRoutes } from './routes/indices'; +import { jobAuditMessagesRoutes } from './routes/job_audit_messages'; +import { jobRoutes } from './routes/anomaly_detectors'; +import { jobServiceRoutes } from './routes/job_service'; +import { jobValidationRoutes } from './routes/job_validation'; +import { notificationRoutes } from './routes/notification_settings'; +import { resultsServiceRoutes } from './routes/results_service'; +import { systemRoutes } from './routes/system'; + +declare module 'kibana/server' { + interface RequestHandlerContext { + ml?: { + mlClient: IScopedClusterClient; + }; + } +} + +export class MlServerPlugin { + private readonly pluginId: string = PLUGIN_ID; + private log: Logger; + private version: string; + + private licenseCheckResults: LicenseCheckResult = { + isAvailable: false, + isActive: false, + isEnabled: false, + isSecurityDisabled: false, + }; + + constructor(ctx: PluginInitializerContext) { + this.log = ctx.logger.get(); + this.version = ctx.env.packageInfo.branch; + } + + public setup(coreSetup: CoreSetup, plugins: PluginsSetup) { + let sampleLinksInitialized = false; + + plugins.features.registerFeature({ + id: PLUGIN_ID, + name: i18n.translate('xpack.ml.featureRegistry.mlFeatureName', { + defaultMessage: 'Machine Learning', + }), + icon: 'machineLearningApp', + navLinkId: PLUGIN_ID, + app: [PLUGIN_ID, 'kibana'], + catalogue: [PLUGIN_ID], + privileges: {}, + reserved: { + privilege: { + savedObject: { + all: [], + read: [], + }, + ui: [], + }, + description: i18n.translate('xpack.ml.feature.reserved.description', { + defaultMessage: + 'To grant users access, you should also assign either the machine_learning_user or machine_learning_admin role.', + }), + }, + }); + + // Can access via router's handler function 'context' parameter - context.ml.mlClient + const mlClient = coreSetup.elasticsearch.createClient(PLUGIN_ID, { + plugins: [elasticsearchJsPlugin], + }); + + coreSetup.http.registerRouteHandlerContext(PLUGIN_ID, (context, request) => { + return { + mlClient: mlClient.asScoped(request), + }; + }); + + const routeInit: RouteInitialization = { + router: coreSetup.http.createRouter(), + getLicenseCheckResults: () => this.licenseCheckResults, + }; + + annotationRoutes(routeInit, plugins.security); + calendars(routeInit); + dataFeedRoutes(routeInit); + dataFrameAnalyticsRoutes(routeInit); + dataRecognizer(routeInit); + dataVisualizerRoutes(routeInit); + fieldsService(routeInit); + fileDataVisualizerRoutes(routeInit); + filtersRoutes(routeInit); + indicesRoutes(routeInit); + jobAuditMessagesRoutes(routeInit); + jobRoutes(routeInit); + jobServiceRoutes(routeInit); + notificationRoutes(routeInit); + resultsServiceRoutes(routeInit); + jobValidationRoutes(routeInit, this.version); + systemRoutes(routeInit, { + spacesPlugin: plugins.spaces, + cloud: plugins.cloud, + }); + initMlServerLog({ log: this.log }); + coreSetup.getStartServices().then(([core]) => { + makeMlUsageCollector(plugins.usageCollection, core.savedObjects); + }); + + plugins.licensing.license$.subscribe(async license => { + const { isEnabled: securityIsEnabled } = license.getFeature('security'); + // @ts-ignore isAvailable is not read + const { isAvailable, isEnabled } = license.getFeature(this.pluginId); + + this.licenseCheckResults = { + isActive: license.isActive, + // This `isAvailable` check for the ml plugin returns false for a basic license + // ML should be available on basic with reduced functionality (only file data visualizer) + // TODO: This will need to be updated in the second step of this cutover to NP. + isAvailable: isEnabled, + isEnabled, + isSecurityDisabled: securityIsEnabled === false, + type: license.type, + }; + + if (sampleLinksInitialized === false) { + sampleLinksInitialized = true; + // Add links to the Kibana sample data sets if ml is enabled + // and license is trial or platinum. + if (isEnabled === true && plugins.home) { + if ( + this.licenseCheckResults.type && + VALID_FULL_LICENSE_MODES.includes(this.licenseCheckResults.type) + ) { + addLinksToSampleDatasets({ + addAppLinksToSampleDataset: plugins.home.sampleData.addAppLinksToSampleDataset, + }); + } + } + } + }); + } + + public start() {} + + public stop() {} +} diff --git a/x-pack/legacy/plugins/ml/server/routes/README.md b/x-pack/plugins/ml/server/routes/README.md similarity index 100% rename from x-pack/legacy/plugins/ml/server/routes/README.md rename to x-pack/plugins/ml/server/routes/README.md diff --git a/x-pack/legacy/plugins/ml/server/routes/annotations.ts b/x-pack/plugins/ml/server/routes/annotations.ts similarity index 83% rename from x-pack/legacy/plugins/ml/server/routes/annotations.ts rename to x-pack/plugins/ml/server/routes/annotations.ts index 20f52b4b051c4c..bcc0238c366a3d 100644 --- a/x-pack/legacy/plugins/ml/server/routes/annotations.ts +++ b/x-pack/plugins/ml/server/routes/annotations.ts @@ -9,18 +9,19 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; import { schema } from '@kbn/config-schema'; +import { SecurityPluginSetup } from '../../../security/server'; import { isAnnotationsFeatureAvailable } from '../lib/check_annotations'; import { annotationServiceProvider } from '../models/annotation_service'; import { wrapError } from '../client/error_wrapper'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; -import { RouteInitialization } from '../new_platform/plugin'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; +import { RouteInitialization } from '../types'; import { deleteAnnotationSchema, getAnnotationsSchema, indexAnnotationSchema, -} from '../new_platform/annotations_schema'; +} from './schemas/annotations_schema'; -import { ANNOTATION_USER_UNKNOWN } from '../../common/constants/annotations'; +import { ANNOTATION_USER_UNKNOWN } from '../../../../legacy/plugins/ml/common/constants/annotations'; function getAnnotationsFeatureUnavailableErrorMessage() { return Boom.badRequest( @@ -34,7 +35,10 @@ function getAnnotationsFeatureUnavailableErrorMessage() { /** * Routes for annotations */ -export function annotationRoutes({ xpackMainPlugin, router, securityPlugin }: RouteInitialization) { +export function annotationRoutes( + { router, getLicenseCheckResults }: RouteInitialization, + securityPlugin: SecurityPluginSetup +) { /** * @apiGroup Annotations * @@ -57,7 +61,7 @@ export function annotationRoutes({ xpackMainPlugin, router, securityPlugin }: Ro body: schema.object(getAnnotationsSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { getAnnotations } = annotationServiceProvider(context); const resp = await getAnnotations(request.body); @@ -88,7 +92,7 @@ export function annotationRoutes({ xpackMainPlugin, router, securityPlugin }: Ro body: schema.object(indexAnnotationSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const annotationsFeatureAvailable = await isAnnotationsFeatureAvailable( context.ml!.mlClient.callAsCurrentUser @@ -99,6 +103,7 @@ export function annotationRoutes({ xpackMainPlugin, router, securityPlugin }: Ro const { indexAnnotation } = annotationServiceProvider(context); const user = securityPlugin.authc.getCurrentUser(request) || {}; + // @ts-ignore username doesn't exist on {} const resp = await indexAnnotation(request.body, user.username || ANNOTATION_USER_UNKNOWN); return response.ok({ @@ -126,7 +131,7 @@ export function annotationRoutes({ xpackMainPlugin, router, securityPlugin }: Ro params: schema.object(deleteAnnotationSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const annotationsFeatureAvailable = await isAnnotationsFeatureAvailable( context.ml!.mlClient.callAsCurrentUser diff --git a/x-pack/legacy/plugins/ml/server/routes/anomaly_detectors.ts b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts similarity index 89% rename from x-pack/legacy/plugins/ml/server/routes/anomaly_detectors.ts rename to x-pack/plugins/ml/server/routes/anomaly_detectors.ts index 99dbdec9e945bd..7bf2fb7bc6903d 100644 --- a/x-pack/legacy/plugins/ml/server/routes/anomaly_detectors.ts +++ b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts @@ -6,17 +6,17 @@ import { schema } from '@kbn/config-schema'; import { wrapError } from '../client/error_wrapper'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; -import { RouteInitialization } from '../new_platform/plugin'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; +import { RouteInitialization } from '../types'; import { anomalyDetectionJobSchema, anomalyDetectionUpdateJobSchema, -} from '../new_platform/anomaly_detectors_schema'; +} from './schemas/anomaly_detectors_schema'; /** * Routes for the anomaly detectors */ -export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function jobRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup AnomalyDetectors * @@ -32,7 +32,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { path: '/api/ml/anomaly_detectors', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser('ml.jobs'); return response.ok({ @@ -62,7 +62,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { jobId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser('ml.jobs', { jobId }); @@ -90,7 +90,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { path: '/api/ml/anomaly_detectors/_stats', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser('ml.jobStats'); return response.ok({ @@ -120,7 +120,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { jobId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser('ml.jobStats', { jobId }); @@ -152,7 +152,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { body: schema.object({ ...anomalyDetectionJobSchema }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { jobId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser('ml.addJob', { @@ -187,7 +187,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { body: schema.object({ ...anomalyDetectionUpdateJobSchema }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { jobId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser('ml.updateJob', { @@ -221,7 +221,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { jobId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser('ml.openJob', { @@ -254,7 +254,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const options: { jobId: string; force?: boolean } = { jobId: request.params.jobId, @@ -291,7 +291,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const options: { jobId: string; force?: boolean } = { jobId: request.params.jobId, @@ -326,7 +326,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { body: schema.any(), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser('ml.validateDetector', { body: request.body, @@ -359,7 +359,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { body: schema.object({ duration: schema.any() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const jobId = request.params.jobId; const duration = request.body.duration; @@ -407,7 +407,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser('ml.records', { jobId: request.params.jobId, @@ -456,7 +456,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser('ml.buckets', { jobId: request.params.jobId, @@ -499,7 +499,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser('ml.overallBuckets', { jobId: request.params.jobId, @@ -537,7 +537,7 @@ export function jobRoutes({ xpackMainPlugin, router }: RouteInitialization) { }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const options = { jobId: request.params.jobId, diff --git a/x-pack/legacy/plugins/ml/server/routes/apidoc.json b/x-pack/plugins/ml/server/routes/apidoc.json similarity index 100% rename from x-pack/legacy/plugins/ml/server/routes/apidoc.json rename to x-pack/plugins/ml/server/routes/apidoc.json diff --git a/x-pack/legacy/plugins/ml/server/routes/calendars.ts b/x-pack/plugins/ml/server/routes/calendars.ts similarity index 84% rename from x-pack/legacy/plugins/ml/server/routes/calendars.ts rename to x-pack/plugins/ml/server/routes/calendars.ts index 8e4e1c4c14751d..ae494d3578890b 100644 --- a/x-pack/legacy/plugins/ml/server/routes/calendars.ts +++ b/x-pack/plugins/ml/server/routes/calendars.ts @@ -6,10 +6,10 @@ import { RequestHandlerContext } from 'src/core/server'; import { schema } from '@kbn/config-schema'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; -import { calendarSchema } from '../new_platform/calendars_schema'; +import { RouteInitialization } from '../types'; +import { calendarSchema } from './schemas/calendars_schema'; import { CalendarManager, Calendar, FormCalendar } from '../models/calendar'; function getAllCalendars(context: RequestHandlerContext) { @@ -42,13 +42,13 @@ function getCalendarsByIds(context: RequestHandlerContext, calendarIds: string) return cal.getCalendarsByIds(calendarIds); } -export function calendars({ xpackMainPlugin, router }: RouteInitialization) { +export function calendars({ router, getLicenseCheckResults }: RouteInitialization) { router.get( { path: '/api/ml/calendars', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getAllCalendars(context); @@ -68,7 +68,7 @@ export function calendars({ xpackMainPlugin, router }: RouteInitialization) { params: schema.object({ calendarIds: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { let returnValue; try { const calendarIds = request.params.calendarIds.split(','); @@ -95,7 +95,7 @@ export function calendars({ xpackMainPlugin, router }: RouteInitialization) { body: schema.object({ ...calendarSchema }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const body = request.body; const resp = await newCalendar(context, body); @@ -117,7 +117,7 @@ export function calendars({ xpackMainPlugin, router }: RouteInitialization) { body: schema.object({ ...calendarSchema }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { calendarId } = request.params; const body = request.body; @@ -139,7 +139,7 @@ export function calendars({ xpackMainPlugin, router }: RouteInitialization) { params: schema.object({ calendarId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { calendarId } = request.params; const resp = await deleteCalendar(context, calendarId); diff --git a/x-pack/legacy/plugins/ml/server/routes/data_frame_analytics.ts b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts similarity index 89% rename from x-pack/legacy/plugins/ml/server/routes/data_frame_analytics.ts rename to x-pack/plugins/ml/server/routes/data_frame_analytics.ts index 6541fa541a59ff..0a93320c05eb5b 100644 --- a/x-pack/legacy/plugins/ml/server/routes/data_frame_analytics.ts +++ b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts @@ -7,18 +7,18 @@ import { schema } from '@kbn/config-schema'; import { wrapError } from '../client/error_wrapper'; import { analyticsAuditMessagesProvider } from '../models/data_frame_analytics/analytics_audit_messages'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; -import { RouteInitialization } from '../new_platform/plugin'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; +import { RouteInitialization } from '../types'; import { dataAnalyticsJobConfigSchema, dataAnalyticsEvaluateSchema, dataAnalyticsExplainSchema, -} from '../new_platform/data_analytics_schema'; +} from './schemas/data_analytics_schema'; /** * Routes for the data frame analytics */ -export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function dataFrameAnalyticsRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup DataFrameAnalytics * @@ -36,7 +36,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti params: schema.object({ analyticsId: schema.maybe(schema.string()) }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser('ml.getDataFrameAnalytics'); return response.ok({ @@ -64,7 +64,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti params: schema.object({ analyticsId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { analyticsId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser('ml.getDataFrameAnalytics', { @@ -91,7 +91,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti path: '/api/ml/data_frame/analytics/_stats', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser( 'ml.getDataFrameAnalyticsStats' @@ -121,7 +121,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti params: schema.object({ analyticsId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { analyticsId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser( @@ -159,7 +159,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti body: schema.object(dataAnalyticsJobConfigSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { analyticsId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser( @@ -192,7 +192,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti body: schema.object({ ...dataAnalyticsEvaluateSchema }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser( 'ml.evaluateDataFrameAnalytics', @@ -232,7 +232,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti body: schema.object({ ...dataAnalyticsExplainSchema }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const results = await context.ml!.mlClient.callAsCurrentUser( 'ml.explainDataFrameAnalytics', @@ -267,7 +267,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { analyticsId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser( @@ -303,7 +303,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { analyticsId } = request.params; const results = await context.ml!.mlClient.callAsCurrentUser('ml.startDataFrameAnalytics', { @@ -337,7 +337,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const options: { analyticsId: string; force?: boolean | undefined } = { analyticsId: request.params.analyticsId, @@ -377,7 +377,7 @@ export function dataFrameAnalyticsRoutes({ xpackMainPlugin, router }: RouteIniti params: schema.object({ analyticsId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { analyticsId } = request.params; const { getAnalyticsAuditMessages } = analyticsAuditMessagesProvider( diff --git a/x-pack/legacy/plugins/ml/server/routes/data_visualizer.ts b/x-pack/plugins/ml/server/routes/data_visualizer.ts similarity index 89% rename from x-pack/legacy/plugins/ml/server/routes/data_visualizer.ts rename to x-pack/plugins/ml/server/routes/data_visualizer.ts index df7e4b70108777..e4d068784def1b 100644 --- a/x-pack/legacy/plugins/ml/server/routes/data_visualizer.ts +++ b/x-pack/plugins/ml/server/routes/data_visualizer.ts @@ -11,9 +11,9 @@ import { Field } from '../models/data_visualizer/data_visualizer'; import { dataVisualizerFieldStatsSchema, dataVisualizerOverallStatsSchema, -} from '../new_platform/data_visualizer_schema'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; -import { RouteInitialization } from '../new_platform/plugin'; +} from './schemas/data_visualizer_schema'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; +import { RouteInitialization } from '../types'; function getOverallStats( context: RequestHandlerContext, @@ -68,7 +68,7 @@ function getStatsForFields( /** * Routes for the index data visualizer. */ -export function dataVisualizerRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function dataVisualizerRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup DataVisualizer * @@ -83,7 +83,7 @@ export function dataVisualizerRoutes({ xpackMainPlugin, router }: RouteInitializ path: '/api/ml/data_visualizer/get_field_stats/{indexPatternTitle}', validate: dataVisualizerFieldStatsSchema, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { params: { indexPatternTitle }, @@ -135,7 +135,7 @@ export function dataVisualizerRoutes({ xpackMainPlugin, router }: RouteInitializ path: '/api/ml/data_visualizer/get_overall_stats/{indexPatternTitle}', validate: dataVisualizerOverallStatsSchema, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { params: { indexPatternTitle }, diff --git a/x-pack/legacy/plugins/ml/server/routes/datafeeds.ts b/x-pack/plugins/ml/server/routes/datafeeds.ts similarity index 86% rename from x-pack/legacy/plugins/ml/server/routes/datafeeds.ts rename to x-pack/plugins/ml/server/routes/datafeeds.ts index 9335403616cf7d..e3bce4c1328e4e 100644 --- a/x-pack/legacy/plugins/ml/server/routes/datafeeds.ts +++ b/x-pack/plugins/ml/server/routes/datafeeds.ts @@ -5,15 +5,15 @@ */ import { schema } from '@kbn/config-schema'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; -import { startDatafeedSchema, datafeedConfigSchema } from '../new_platform/datafeeds_schema'; +import { RouteInitialization } from '../types'; +import { startDatafeedSchema, datafeedConfigSchema } from './schemas/datafeeds_schema'; /** * Routes for datafeed service */ -export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function dataFeedRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup DatafeedService * @@ -26,7 +26,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) path: '/api/ml/datafeeds', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await context.ml!.mlClient.callAsCurrentUser('ml.datafeeds'); @@ -53,7 +53,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) params: schema.object({ datafeedId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const datafeedId = request.params.datafeedId; const resp = await context.ml!.mlClient.callAsCurrentUser('ml.datafeeds', { datafeedId }); @@ -79,7 +79,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) path: '/api/ml/datafeeds/_stats', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await context.ml!.mlClient.callAsCurrentUser('ml.datafeedStats'); @@ -106,7 +106,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) params: schema.object({ datafeedId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const datafeedId = request.params.datafeedId; const resp = await context.ml!.mlClient.callAsCurrentUser('ml.datafeedStats', { @@ -137,7 +137,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) body: datafeedConfigSchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const datafeedId = request.params.datafeedId; const resp = await context.ml!.mlClient.callAsCurrentUser('ml.addDatafeed', { @@ -169,7 +169,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) body: datafeedConfigSchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const datafeedId = request.params.datafeedId; const resp = await context.ml!.mlClient.callAsCurrentUser('ml.updateDatafeed', { @@ -201,7 +201,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) query: schema.maybe(schema.object({ force: schema.maybe(schema.any()) })), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const options: { datafeedId: string; force?: boolean } = { datafeedId: request.params.jobId, @@ -237,7 +237,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) body: startDatafeedSchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const datafeedId = request.params.datafeedId; const { start, end } = request.body; @@ -271,7 +271,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) params: schema.object({ datafeedId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const datafeedId = request.params.datafeedId; @@ -302,7 +302,7 @@ export function dataFeedRoutes({ xpackMainPlugin, router }: RouteInitialization) params: schema.object({ datafeedId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const datafeedId = request.params.datafeedId; const resp = await context.ml!.mlClient.callAsCurrentUser('ml.datafeedPreview', { diff --git a/x-pack/legacy/plugins/ml/server/routes/fields_service.ts b/x-pack/plugins/ml/server/routes/fields_service.ts similarity index 84% rename from x-pack/legacy/plugins/ml/server/routes/fields_service.ts rename to x-pack/plugins/ml/server/routes/fields_service.ts index 4827adf23d7b46..bc092190c2c620 100644 --- a/x-pack/legacy/plugins/ml/server/routes/fields_service.ts +++ b/x-pack/plugins/ml/server/routes/fields_service.ts @@ -5,13 +5,13 @@ */ import { RequestHandlerContext } from 'src/core/server'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; +import { RouteInitialization } from '../types'; import { getCardinalityOfFieldsSchema, getTimeFieldRangeSchema, -} from '../new_platform/fields_service_schema'; +} from './schemas/fields_service_schema'; import { fieldsServiceProvider } from '../models/fields_service'; function getCardinalityOfFields(context: RequestHandlerContext, payload: any) { @@ -29,7 +29,7 @@ function getTimeFieldRange(context: RequestHandlerContext, payload: any) { /** * Routes for fields service */ -export function fieldsService({ xpackMainPlugin, router }: RouteInitialization) { +export function fieldsService({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup FieldsService * @@ -44,7 +44,7 @@ export function fieldsService({ xpackMainPlugin, router }: RouteInitialization) body: getCardinalityOfFieldsSchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getCardinalityOfFields(context, request.body); @@ -71,7 +71,7 @@ export function fieldsService({ xpackMainPlugin, router }: RouteInitialization) body: getTimeFieldRangeSchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getTimeFieldRange(context, request.body); diff --git a/x-pack/legacy/plugins/ml/server/routes/file_data_visualizer.ts b/x-pack/plugins/ml/server/routes/file_data_visualizer.ts similarity index 87% rename from x-pack/legacy/plugins/ml/server/routes/file_data_visualizer.ts rename to x-pack/plugins/ml/server/routes/file_data_visualizer.ts index d5a992c9332930..1d724a8843350d 100644 --- a/x-pack/legacy/plugins/ml/server/routes/file_data_visualizer.ts +++ b/x-pack/plugins/ml/server/routes/file_data_visualizer.ts @@ -6,7 +6,7 @@ import { schema } from '@kbn/config-schema'; import { RequestHandlerContext } from 'kibana/server'; -import { MAX_BYTES } from '../../common/constants/file_datavisualizer'; +import { MAX_BYTES } from '../../../../legacy/plugins/ml/common/constants/file_datavisualizer'; import { wrapError } from '../client/error_wrapper'; import { InputOverrides, @@ -18,8 +18,8 @@ import { Mappings, } from '../models/file_data_visualizer'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; -import { RouteInitialization } from '../new_platform/plugin'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; +import { RouteInitialization } from '../types'; import { incrementFileDataVisualizerIndexCreationCount } from '../lib/ml_telemetry'; function analyzeFiles(context: RequestHandlerContext, data: InputData, overrides: InputOverrides) { @@ -43,12 +43,7 @@ function importData( /** * Routes for the file data visualizer. */ -export function fileDataVisualizerRoutes({ - router, - xpackMainPlugin, - savedObjects, - elasticsearchPlugin, -}: RouteInitialization) { +export function fileDataVisualizerRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup FileDataVisualizer * @@ -87,7 +82,7 @@ export function fileDataVisualizerRoutes({ }, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const result = await analyzeFiles(context, request.body, request.query); return response.ok({ body: result }); @@ -129,7 +124,7 @@ export function fileDataVisualizerRoutes({ }, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { id } = request.query; const { index, data, settings, mappings, ingestPipeline } = request.body; @@ -138,7 +133,8 @@ export function fileDataVisualizerRoutes({ // follow-up import calls to just add additional data will include the `id` of the created // index, we'll ignore those and don't increment the counter. if (id === undefined) { - await incrementFileDataVisualizerIndexCreationCount(savedObjects!); + // @ts-ignore + await incrementFileDataVisualizerIndexCreationCount(context.core.savedObjects.client); } const result = await importData( diff --git a/x-pack/legacy/plugins/ml/server/routes/filters.ts b/x-pack/plugins/ml/server/routes/filters.ts similarity index 87% rename from x-pack/legacy/plugins/ml/server/routes/filters.ts rename to x-pack/plugins/ml/server/routes/filters.ts index a06f8d4f8b727b..d5530668b26062 100644 --- a/x-pack/legacy/plugins/ml/server/routes/filters.ts +++ b/x-pack/plugins/ml/server/routes/filters.ts @@ -6,10 +6,10 @@ import { RequestHandlerContext } from 'src/core/server'; import { schema } from '@kbn/config-schema'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; -import { createFilterSchema, updateFilterSchema } from '../new_platform/filters_schema'; +import { RouteInitialization } from '../types'; +import { createFilterSchema, updateFilterSchema } from './schemas/filters_schema'; import { FilterManager, FormFilter } from '../models/filter'; // TODO - add function for returning a list of just the filter IDs. @@ -44,7 +44,7 @@ function deleteFilter(context: RequestHandlerContext, filterId: string) { return mgr.deleteFilter(filterId); } -export function filtersRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function filtersRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup Filters * @@ -60,7 +60,7 @@ export function filtersRoutes({ xpackMainPlugin, router }: RouteInitialization) path: '/api/ml/filters', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getAllFilters(context); @@ -90,7 +90,7 @@ export function filtersRoutes({ xpackMainPlugin, router }: RouteInitialization) params: schema.object({ filterId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getFilter(context, request.params.filterId); return response.ok({ @@ -119,7 +119,7 @@ export function filtersRoutes({ xpackMainPlugin, router }: RouteInitialization) body: schema.object(createFilterSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const body = request.body; const resp = await newFilter(context, body); @@ -151,7 +151,7 @@ export function filtersRoutes({ xpackMainPlugin, router }: RouteInitialization) body: schema.object(updateFilterSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { filterId } = request.params; const body = request.body; @@ -182,7 +182,7 @@ export function filtersRoutes({ xpackMainPlugin, router }: RouteInitialization) params: schema.object({ filterId: schema.string() }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { filterId } = request.params; const resp = await deleteFilter(context, filterId); @@ -212,7 +212,7 @@ export function filtersRoutes({ xpackMainPlugin, router }: RouteInitialization) path: '/api/ml/filters/_stats', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getAllFilterStats(context); diff --git a/x-pack/legacy/plugins/ml/server/routes/indices.ts b/x-pack/plugins/ml/server/routes/indices.ts similarity index 80% rename from x-pack/legacy/plugins/ml/server/routes/indices.ts rename to x-pack/plugins/ml/server/routes/indices.ts index 0ee15f1321e9c2..e01a7a0cbad287 100644 --- a/x-pack/legacy/plugins/ml/server/routes/indices.ts +++ b/x-pack/plugins/ml/server/routes/indices.ts @@ -6,13 +6,13 @@ import { schema } from '@kbn/config-schema'; import { wrapError } from '../client/error_wrapper'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; -import { RouteInitialization } from '../new_platform/plugin'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; +import { RouteInitialization } from '../types'; /** * Indices routes. */ -export function indicesRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function indicesRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup Indices * @@ -30,7 +30,7 @@ export function indicesRoutes({ xpackMainPlugin, router }: RouteInitialization) }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { body: { index, fields: requestFields }, diff --git a/x-pack/legacy/plugins/ml/server/routes/job_audit_messages.ts b/x-pack/plugins/ml/server/routes/job_audit_messages.ts similarity index 84% rename from x-pack/legacy/plugins/ml/server/routes/job_audit_messages.ts rename to x-pack/plugins/ml/server/routes/job_audit_messages.ts index 76986b935b993a..38df28e17ec0d6 100644 --- a/x-pack/legacy/plugins/ml/server/routes/job_audit_messages.ts +++ b/x-pack/plugins/ml/server/routes/job_audit_messages.ts @@ -5,15 +5,15 @@ */ import { schema } from '@kbn/config-schema'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; +import { RouteInitialization } from '../types'; import { jobAuditMessagesProvider } from '../models/job_audit_messages'; /** * Routes for job audit message routes */ -export function jobAuditMessagesRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function jobAuditMessagesRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup JobAuditMessages * @@ -29,7 +29,7 @@ export function jobAuditMessagesRoutes({ xpackMainPlugin, router }: RouteInitial query: schema.maybe(schema.object({ from: schema.maybe(schema.any()) })), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { getJobAuditMessages } = jobAuditMessagesProvider( context.ml!.mlClient.callAsCurrentUser @@ -62,7 +62,7 @@ export function jobAuditMessagesRoutes({ xpackMainPlugin, router }: RouteInitial query: schema.maybe(schema.object({ from: schema.maybe(schema.any()) })), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { getJobAuditMessages } = jobAuditMessagesProvider( context.ml!.mlClient.callAsCurrentUser diff --git a/x-pack/legacy/plugins/ml/server/routes/job_service.ts b/x-pack/plugins/ml/server/routes/job_service.ts similarity index 88% rename from x-pack/legacy/plugins/ml/server/routes/job_service.ts rename to x-pack/plugins/ml/server/routes/job_service.ts index 5ddbd4cdfd5a5d..e15888088d3a13 100644 --- a/x-pack/legacy/plugins/ml/server/routes/job_service.ts +++ b/x-pack/plugins/ml/server/routes/job_service.ts @@ -7,10 +7,9 @@ import Boom from 'boom'; import { schema } from '@kbn/config-schema'; import { IScopedClusterClient } from 'src/core/server'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; -import { isSecurityDisabled } from '../lib/security_utils'; +import { RouteInitialization } from '../types'; import { categorizationFieldExamplesSchema, chartSchema, @@ -21,7 +20,7 @@ import { lookBackProgressSchema, topCategoriesSchema, updateGroupsSchema, -} from '../new_platform/job_service_schema'; +} from './schemas/job_service_schema'; // @ts-ignore no declaration module import { jobServiceProvider } from '../models/job_service'; import { categorizationExamplesProvider } from '../models/job_service/new_job'; @@ -29,11 +28,12 @@ import { categorizationExamplesProvider } from '../models/job_service/new_job'; /** * Routes for job service */ -export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function jobServiceRoutes({ router, getLicenseCheckResults }: RouteInitialization) { async function hasPermissionToCreateJobs( callAsCurrentUser: IScopedClusterClient['callAsCurrentUser'] ) { - if (isSecurityDisabled(xpackMainPlugin) === true) { + const { isSecurityDisabled } = getLicenseCheckResults(); + if (isSecurityDisabled === true) { return true; } @@ -63,7 +63,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(forceStartDatafeedSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { forceStartDatafeeds } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { datafeedIds, start, end } = request.body; @@ -92,7 +92,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(datafeedIdsSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { stopDatafeeds } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { datafeedIds } = request.body; @@ -121,7 +121,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(jobIdsSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { deleteJobs } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { jobIds } = request.body; @@ -150,7 +150,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(jobIdsSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { closeJobs } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { jobIds } = request.body; @@ -179,7 +179,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(jobIdsSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { jobsSummary } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { jobIds } = request.body; @@ -208,7 +208,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(jobsWithTimerangeSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { jobsWithTimerange } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { dateFormatTz } = request.body; @@ -237,7 +237,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(jobIdsSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { createFullJobsList } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { jobIds } = request.body; @@ -264,7 +264,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio path: '/api/ml/jobs/groups', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { getAllGroups } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const resp = await getAllGroups(); @@ -292,7 +292,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(updateGroupsSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { updateGroups } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { jobs } = request.body; @@ -319,7 +319,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio path: '/api/ml/jobs/deleting_jobs_tasks', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { deletingJobTasks } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const resp = await deletingJobTasks(); @@ -347,7 +347,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(jobIdsSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { jobsExist } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { jobIds } = request.body; @@ -377,7 +377,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio query: schema.maybe(schema.object({ rollup: schema.maybe(schema.string()) })), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { indexPattern } = request.params; const isRollup = request.query.rollup === 'true'; @@ -408,7 +408,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(chartSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { indexPatternTitle, @@ -461,7 +461,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(chartSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { indexPatternTitle, @@ -509,7 +509,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio path: '/api/ml/jobs/all_jobs_and_group_ids', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { getAllJobAndGroupIds } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const resp = await getAllJobAndGroupIds(); @@ -537,7 +537,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(lookBackProgressSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { getLookBackProgress } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { jobId, start, end } = request.body; @@ -566,7 +566,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(categorizationFieldExamplesSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { // due to the use of the _analyze endpoint which is called by the kibana user, // basic job creation privileges are required to use this endpoint @@ -625,7 +625,7 @@ export function jobServiceRoutes({ xpackMainPlugin, router }: RouteInitializatio body: schema.object(topCategoriesSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { topCategories } = jobServiceProvider(context.ml!.mlClient.callAsCurrentUser); const { jobId, count } = request.body; diff --git a/x-pack/legacy/plugins/ml/server/routes/job_validation.ts b/x-pack/plugins/ml/server/routes/job_validation.ts similarity index 85% rename from x-pack/legacy/plugins/ml/server/routes/job_validation.ts rename to x-pack/plugins/ml/server/routes/job_validation.ts index 64c9ccd27720a8..ae2e6885ba0f3b 100644 --- a/x-pack/legacy/plugins/ml/server/routes/job_validation.ts +++ b/x-pack/plugins/ml/server/routes/job_validation.ts @@ -7,15 +7,15 @@ import Boom from 'boom'; import { RequestHandlerContext } from 'src/core/server'; import { schema, TypeOf } from '@kbn/config-schema'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; +import { RouteInitialization } from '../types'; import { estimateBucketSpanSchema, modelMemoryLimitSchema, validateCardinalitySchema, validateJobSchema, -} from '../new_platform/job_validation_schema'; +} from './schemas/job_validation_schema'; import { estimateBucketSpanFactory } from '../models/bucket_span_estimator'; import { calculateModelMemoryLimitProvider } from '../models/calculate_model_memory_limit'; import { validateJob, validateCardinality } from '../models/job_validation'; @@ -25,7 +25,10 @@ type CalculateModelMemoryLimitPayload = TypeOf; /** * Routes for job validation */ -export function jobValidationRoutes({ config, xpackMainPlugin, router }: RouteInitialization) { +export function jobValidationRoutes( + { getLicenseCheckResults, router }: RouteInitialization, + version: string +) { function calculateModelMemoryLimit( context: RequestHandlerContext, payload: CalculateModelMemoryLimitPayload @@ -67,13 +70,13 @@ export function jobValidationRoutes({ config, xpackMainPlugin, router }: RouteIn body: estimateBucketSpanSchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { let errorResp; const resp = await estimateBucketSpanFactory( context.ml!.mlClient.callAsCurrentUser, context.core.elasticsearch.adminClient.callAsInternalUser, - xpackMainPlugin + getLicenseCheckResults().isSecurityDisabled )(request.body) // this catch gets triggered when the estimation code runs without error // but isn't able to come up with a bucket span estimation. @@ -114,7 +117,7 @@ export function jobValidationRoutes({ config, xpackMainPlugin, router }: RouteIn body: modelMemoryLimitSchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await calculateModelMemoryLimit(context, request.body); @@ -141,7 +144,7 @@ export function jobValidationRoutes({ config, xpackMainPlugin, router }: RouteIn body: schema.object(validateCardinalitySchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await validateCardinality( context.ml!.mlClient.callAsCurrentUser, @@ -171,16 +174,15 @@ export function jobValidationRoutes({ config, xpackMainPlugin, router }: RouteIn body: validateJobSchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { - // pkg.branch corresponds to the version used in documentation links. - const version = config.get('pkg.branch'); + // version corresponds to the version used in documentation links. const resp = await validateJob( context.ml!.mlClient.callAsCurrentUser, request.body, version, context.core.elasticsearch.adminClient.callAsInternalUser, - xpackMainPlugin + getLicenseCheckResults().isSecurityDisabled ); return response.ok({ diff --git a/x-pack/legacy/plugins/ml/server/new_platform/licence_check_pre_routing_factory.ts b/x-pack/plugins/ml/server/routes/license_check_pre_routing_factory.ts similarity index 71% rename from x-pack/legacy/plugins/ml/server/new_platform/licence_check_pre_routing_factory.ts rename to x-pack/plugins/ml/server/routes/license_check_pre_routing_factory.ts index cc77d2872fb909..a371af1abf2d13 100644 --- a/x-pack/legacy/plugins/ml/server/new_platform/licence_check_pre_routing_factory.ts +++ b/x-pack/plugins/ml/server/routes/license_check_pre_routing_factory.ts @@ -10,10 +10,10 @@ import { RequestHandler, RequestHandlerContext, } from 'src/core/server'; -import { PLUGIN_ID, MlXpackMainPlugin } from './plugin'; +import { LicenseCheckResult } from '../types'; export const licensePreRoutingFactory = ( - xpackMainPlugin: MlXpackMainPlugin, + getLicenseCheckResults: () => LicenseCheckResult, handler: RequestHandler ): RequestHandler => { // License checking and enable/disable logic @@ -22,14 +22,10 @@ export const licensePreRoutingFactory = ( request: KibanaRequest, response: KibanaResponseFactory ) { - const licenseCheckResults = xpackMainPlugin.info.feature(PLUGIN_ID).getLicenseCheckResults(); + const licenseCheckResults = getLicenseCheckResults(); if (!licenseCheckResults.isAvailable) { - return response.forbidden({ - body: { - message: licenseCheckResults.message, - }, - }); + return response.forbidden(); } return handler(ctx, request, response); diff --git a/x-pack/legacy/plugins/ml/server/routes/modules.ts b/x-pack/plugins/ml/server/routes/modules.ts similarity index 88% rename from x-pack/legacy/plugins/ml/server/routes/modules.ts rename to x-pack/plugins/ml/server/routes/modules.ts index a40fb1c9149ca1..c9b005d4e43f92 100644 --- a/x-pack/legacy/plugins/ml/server/routes/modules.ts +++ b/x-pack/plugins/ml/server/routes/modules.ts @@ -6,12 +6,12 @@ import { schema } from '@kbn/config-schema'; import { RequestHandlerContext } from 'kibana/server'; -import { DatafeedOverride, JobOverride } from '../../common/types/modules'; +import { DatafeedOverride, JobOverride } from '../../../../legacy/plugins/ml/common/types/modules'; import { wrapError } from '../client/error_wrapper'; import { DataRecognizer } from '../models/data_recognizer'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; -import { getModuleIdParamSchema, setupModuleBodySchema } from '../new_platform/modules'; -import { RouteInitialization } from '../new_platform/plugin'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; +import { getModuleIdParamSchema, setupModuleBodySchema } from './schemas/modules'; +import { RouteInitialization } from '../types'; function recognize(context: RequestHandlerContext, indexPatternTitle: string) { const dr = new DataRecognizer(context); @@ -65,7 +65,7 @@ function dataRecognizerJobsExist(context: RequestHandlerContext, moduleId: strin /** * Recognizer routes. */ -export function dataRecognizer({ xpackMainPlugin, router }: RouteInitialization) { +export function dataRecognizer({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup DataRecognizer * @@ -84,7 +84,7 @@ export function dataRecognizer({ xpackMainPlugin, router }: RouteInitialization) }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { indexPatternTitle } = request.params; const results = await recognize(context, indexPatternTitle); @@ -114,7 +114,7 @@ export function dataRecognizer({ xpackMainPlugin, router }: RouteInitialization) }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { let { moduleId } = request.params; if (moduleId === '') { @@ -150,7 +150,7 @@ export function dataRecognizer({ xpackMainPlugin, router }: RouteInitialization) body: setupModuleBodySchema, }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { moduleId } = request.params; @@ -207,7 +207,7 @@ export function dataRecognizer({ xpackMainPlugin, router }: RouteInitialization) }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const { moduleId } = request.params; const result = await dataRecognizerJobsExist(context, moduleId); diff --git a/x-pack/legacy/plugins/ml/server/routes/notification_settings.ts b/x-pack/plugins/ml/server/routes/notification_settings.ts similarity index 75% rename from x-pack/legacy/plugins/ml/server/routes/notification_settings.ts rename to x-pack/plugins/ml/server/routes/notification_settings.ts index c65627543b21d8..b68d2441333f93 100644 --- a/x-pack/legacy/plugins/ml/server/routes/notification_settings.ts +++ b/x-pack/plugins/ml/server/routes/notification_settings.ts @@ -4,14 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; +import { RouteInitialization } from '../types'; /** * Routes for notification settings */ -export function notificationRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function notificationRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup NotificationSettings * @@ -24,7 +24,7 @@ export function notificationRoutes({ xpackMainPlugin, router }: RouteInitializat path: '/api/ml/notification_settings', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const params = { includeDefaults: true, diff --git a/x-pack/legacy/plugins/ml/server/routes/results_service.ts b/x-pack/plugins/ml/server/routes/results_service.ts similarity index 88% rename from x-pack/legacy/plugins/ml/server/routes/results_service.ts rename to x-pack/plugins/ml/server/routes/results_service.ts index 5d107b2d978090..77c998acc9f27a 100644 --- a/x-pack/legacy/plugins/ml/server/routes/results_service.ts +++ b/x-pack/plugins/ml/server/routes/results_service.ts @@ -6,16 +6,16 @@ import { RequestHandlerContext } from 'src/core/server'; import { schema } from '@kbn/config-schema'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; import { wrapError } from '../client/error_wrapper'; -import { RouteInitialization } from '../new_platform/plugin'; +import { RouteInitialization } from '../types'; import { anomaliesTableDataSchema, categoryDefinitionSchema, categoryExamplesSchema, maxAnomalyScoreSchema, partitionFieldValuesSchema, -} from '../new_platform/results_service_schema'; +} from './schemas/results_service_schema'; import { resultsServiceProvider } from '../models/results_service'; function getAnomaliesTableData(context: RequestHandlerContext, payload: any) { @@ -74,7 +74,7 @@ function getPartitionFieldsValues(context: RequestHandlerContext, payload: any) /** * Routes for results service */ -export function resultsServiceRoutes({ xpackMainPlugin, router }: RouteInitialization) { +export function resultsServiceRoutes({ router, getLicenseCheckResults }: RouteInitialization) { /** * @apiGroup ResultsService * @@ -89,7 +89,7 @@ export function resultsServiceRoutes({ xpackMainPlugin, router }: RouteInitializ body: schema.object(anomaliesTableDataSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getAnomaliesTableData(context, request.body); @@ -116,7 +116,7 @@ export function resultsServiceRoutes({ xpackMainPlugin, router }: RouteInitializ body: schema.object(categoryDefinitionSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getCategoryDefinition(context, request.body); @@ -143,7 +143,7 @@ export function resultsServiceRoutes({ xpackMainPlugin, router }: RouteInitializ body: schema.object(maxAnomalyScoreSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getMaxAnomalyScore(context, request.body); @@ -170,7 +170,7 @@ export function resultsServiceRoutes({ xpackMainPlugin, router }: RouteInitializ body: schema.object(categoryExamplesSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getCategoryExamples(context, request.body); @@ -197,7 +197,7 @@ export function resultsServiceRoutes({ xpackMainPlugin, router }: RouteInitializ body: schema.object(partitionFieldValuesSchema), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const resp = await getPartitionFieldsValues(context, request.body); diff --git a/x-pack/legacy/plugins/ml/server/new_platform/annotations_schema.ts b/x-pack/plugins/ml/server/routes/schemas/annotations_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/annotations_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/annotations_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/anomaly_detectors_schema.ts b/x-pack/plugins/ml/server/routes/schemas/anomaly_detectors_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/anomaly_detectors_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/anomaly_detectors_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/calendars_schema.ts b/x-pack/plugins/ml/server/routes/schemas/calendars_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/calendars_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/calendars_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/data_analytics_schema.ts b/x-pack/plugins/ml/server/routes/schemas/data_analytics_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/data_analytics_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/data_analytics_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/data_visualizer_schema.ts b/x-pack/plugins/ml/server/routes/schemas/data_visualizer_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/data_visualizer_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/data_visualizer_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/datafeeds_schema.ts b/x-pack/plugins/ml/server/routes/schemas/datafeeds_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/datafeeds_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/datafeeds_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/fields_service_schema.ts b/x-pack/plugins/ml/server/routes/schemas/fields_service_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/fields_service_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/fields_service_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/filters_schema.ts b/x-pack/plugins/ml/server/routes/schemas/filters_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/filters_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/filters_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/job_service_schema.ts b/x-pack/plugins/ml/server/routes/schemas/job_service_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/job_service_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/job_service_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/job_validation_schema.ts b/x-pack/plugins/ml/server/routes/schemas/job_validation_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/job_validation_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/job_validation_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/modules.ts b/x-pack/plugins/ml/server/routes/schemas/modules.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/modules.ts rename to x-pack/plugins/ml/server/routes/schemas/modules.ts diff --git a/x-pack/legacy/plugins/ml/server/new_platform/results_service_schema.ts b/x-pack/plugins/ml/server/routes/schemas/results_service_schema.ts similarity index 100% rename from x-pack/legacy/plugins/ml/server/new_platform/results_service_schema.ts rename to x-pack/plugins/ml/server/routes/schemas/results_service_schema.ts diff --git a/x-pack/legacy/plugins/ml/server/routes/system.ts b/x-pack/plugins/ml/server/routes/system.ts similarity index 88% rename from x-pack/legacy/plugins/ml/server/routes/system.ts rename to x-pack/plugins/ml/server/routes/system.ts index 5861b53d74875c..36a9ea1447f583 100644 --- a/x-pack/legacy/plugins/ml/server/routes/system.ts +++ b/x-pack/plugins/ml/server/routes/system.ts @@ -11,20 +11,17 @@ import { RequestHandlerContext } from 'kibana/server'; import { wrapError } from '../client/error_wrapper'; import { mlLog } from '../client/log'; import { privilegesProvider } from '../lib/check_privileges'; -import { isSecurityDisabled } from '../lib/security_utils'; import { spacesUtilsProvider } from '../lib/spaces_utils'; -import { licensePreRoutingFactory } from '../new_platform/licence_check_pre_routing_factory'; -import { RouteInitialization } from '../new_platform/plugin'; +import { licensePreRoutingFactory } from './license_check_pre_routing_factory'; +import { RouteInitialization, SystemRouteDeps } from '../types'; /** * System routes */ -export function systemRoutes({ - router, - xpackMainPlugin, - spacesPlugin, - cloud, -}: RouteInitialization) { +export function systemRoutes( + { getLicenseCheckResults, router }: RouteInitialization, + { spacesPlugin, cloud }: SystemRouteDeps +) { async function getNodeCount(context: RequestHandlerContext) { const filterPath = 'nodes.*.attributes'; const resp = await context.ml!.mlClient.callAsInternalUser('nodes.info', { @@ -59,7 +56,7 @@ export function systemRoutes({ body: schema.maybe(schema.any()), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { let upgradeInProgress = false; try { @@ -80,7 +77,7 @@ export function systemRoutes({ } } - if (isSecurityDisabled(xpackMainPlugin)) { + if (getLicenseCheckResults().isSecurityDisabled) { // if xpack.security.enabled has been explicitly set to false // return that security is disabled and don't call the privilegeCheck endpoint return response.ok({ @@ -119,7 +116,7 @@ export function systemRoutes({ }), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const ignoreSpaces = request.query && request.query.ignoreSpaces === 'true'; // if spaces is disabled force isMlEnabledInSpace to be true @@ -130,7 +127,7 @@ export function systemRoutes({ const { getPrivileges } = privilegesProvider( context.ml!.mlClient.callAsCurrentUser, - xpackMainPlugin, + getLicenseCheckResults(), isMlEnabledInSpace, ignoreSpaces ); @@ -155,11 +152,11 @@ export function systemRoutes({ path: '/api/ml/ml_node_count', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { // check for basic license first for consistency with other // security disabled checks - if (isSecurityDisabled(xpackMainPlugin)) { + if (getLicenseCheckResults().isSecurityDisabled) { return response.ok({ body: await getNodeCount(context), }); @@ -206,7 +203,7 @@ export function systemRoutes({ path: '/api/ml/info', validate: false, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { const info = await context.ml!.mlClient.callAsCurrentUser('ml.info'); const cloudId = cloud && cloud.cloudId; @@ -234,7 +231,7 @@ export function systemRoutes({ body: schema.maybe(schema.any()), }, }, - licensePreRoutingFactory(xpackMainPlugin, async (context, request, response) => { + licensePreRoutingFactory(getLicenseCheckResults, async (context, request, response) => { try { return response.ok({ body: await context.ml!.mlClient.callAsCurrentUser('search', request.body), diff --git a/x-pack/plugins/ml/server/types.ts b/x-pack/plugins/ml/server/types.ts new file mode 100644 index 00000000000000..550abadb3c06f3 --- /dev/null +++ b/x-pack/plugins/ml/server/types.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; +import { HomeServerPluginSetup } from 'src/plugins/home/server'; +import { IRouter } from 'src/core/server'; +import { CloudSetup } from '../../cloud/server'; +import { SecurityPluginSetup } from '../../security/server'; +import { PluginSetupContract as FeaturesPluginSetup } from '../../features/server'; +import { LicensingPluginSetup } from '../../licensing/server'; +import { SpacesPluginSetup } from '../../spaces/server'; + +export interface LicenseCheckResult { + isAvailable: boolean; + isActive: boolean; + isEnabled: boolean; + isSecurityDisabled: boolean; + status?: string; + type?: string; +} + +export interface SystemRouteDeps { + cloud: CloudSetup; + spacesPlugin: SpacesPluginSetup; +} + +export interface PluginsSetup { + cloud: CloudSetup; + features: FeaturesPluginSetup; + home: HomeServerPluginSetup; + licensing: LicensingPluginSetup; + security: SecurityPluginSetup; + spaces: SpacesPluginSetup; + usageCollection: UsageCollectionSetup; +} + +export interface RouteInitialization { + router: IRouter; + getLicenseCheckResults: () => LicenseCheckResult; +} From 0cede6a705db65ef450426db3c584fcabab42780 Mon Sep 17 00:00:00 2001 From: Luke Elmers Date: Thu, 27 Feb 2020 19:17:07 -0700 Subject: [PATCH 2/9] Prep agg types for new platform (#57064) --- packages/kbn-utility-types/README.md | 1 + packages/kbn-utility-types/index.ts | 2 +- .../actions/filters/brush_event.test.ts | 49 +- src/legacy/core_plugins/data/public/index.ts | 12 +- src/legacy/core_plugins/data/public/plugin.ts | 6 +- .../public/search/aggs/agg_config.test.ts | 497 ++++++ .../data/public/search/aggs/agg_config.ts | 61 +- .../public/search/aggs/agg_configs.test.ts | 503 ++++++ .../data/public/search/aggs/agg_configs.ts | 76 +- .../public/search/aggs/agg_params.test.ts | 2 - .../data/public/search/aggs/agg_type.test.ts | 16 +- .../data/public/search/aggs/agg_type.ts | 5 +- .../search/aggs/agg_types_registry.test.ts | 91 ++ .../public/search/aggs/agg_types_registry.ts | 68 + .../search/aggs/buckets/_bucket_agg_type.ts | 12 +- .../search/aggs/buckets/_interval_options.ts | 1 + .../create_filter/date_histogram.test.ts | 12 +- .../buckets/create_filter/date_range.test.ts | 7 +- .../buckets/create_filter/filters.test.ts | 13 +- .../buckets/create_filter/histogram.test.ts | 12 +- .../buckets/create_filter/ip_range.test.ts | 11 +- .../aggs/buckets/create_filter/range.test.ts | 12 +- .../aggs/buckets/create_filter/terms.test.ts | 11 +- .../search/aggs/buckets/date_histogram.ts | 8 +- .../search/aggs/buckets/date_range.test.ts | 25 +- .../public/search/aggs/buckets/date_range.ts | 12 +- .../data/public/search/aggs/buckets/filter.ts | 1 + .../public/search/aggs/buckets/filters.ts | 26 +- .../search/aggs/buckets/geo_hash.test.ts | 7 +- .../public/search/aggs/buckets/geo_tile.ts | 3 +- .../search/aggs/buckets/histogram.test.ts | 33 +- .../public/search/aggs/buckets/histogram.ts | 12 +- .../public/search/aggs/buckets/ip_range.ts | 12 +- .../buckets/migrate_include_exclude_format.ts | 4 +- .../public/search/aggs/buckets/range.test.ts | 12 +- .../aggs/buckets/significant_terms.test.ts | 9 +- .../public/search/aggs/buckets/terms.test.ts | 8 +- .../aggs/filter/agg_type_filters.test.ts | 5 +- .../search/aggs/filter/agg_type_filters.ts | 1 + .../search/aggs/filter/prop_filter.test.ts | 19 +- .../data/public/search/aggs/index.test.ts | 2 - .../data/public/search/aggs/index.ts | 9 +- .../public/search/aggs/metrics/bucket_avg.ts | 1 - .../public/search/aggs/metrics/bucket_max.ts | 1 - .../public/search/aggs/metrics/bucket_min.ts | 1 + .../public/search/aggs/metrics/cardinality.ts | 5 +- .../data/public/search/aggs/metrics/count.ts | 7 +- .../lib/get_response_agg_config_class.ts | 1 + .../metrics/lib/parent_pipeline_agg_helper.ts | 1 - .../lib/sibling_pipeline_agg_helper.ts | 1 - .../public/search/aggs/metrics/median.test.ts | 7 +- .../data/public/search/aggs/metrics/median.ts | 4 +- .../search/aggs/metrics/metric_agg_type.ts | 7 +- .../data/public/search/aggs/metrics/min.ts | 1 + .../aggs/metrics/parent_pipeline.test.ts | 18 +- .../aggs/metrics/percentile_ranks.test.ts | 8 +- .../search/aggs/metrics/percentile_ranks.ts | 7 +- .../search/aggs/metrics/percentiles.test.ts | 6 +- .../public/search/aggs/metrics/percentiles.ts | 4 - .../aggs/metrics/sibling_pipeline.test.ts | 22 +- .../search/aggs/metrics/std_deviation.test.ts | 6 +- .../search/aggs/metrics/top_hit.test.ts | 6 +- .../public/search/aggs/param_types/agg.ts | 4 +- .../public/search/aggs/param_types/base.ts | 4 +- .../search/aggs/param_types/field.test.ts | 2 - .../public/search/aggs/param_types/field.ts | 5 +- .../param_types/filter/field_filters.test.ts | 11 +- .../aggs/param_types/filter/field_filters.ts | 8 +- .../search/aggs/param_types/json.test.ts | 8 +- .../public/search/aggs/param_types/json.ts | 4 +- .../search/aggs/param_types/optioned.test.ts | 2 - .../search/aggs/param_types/optioned.ts | 6 +- .../search/aggs/param_types/string.test.ts | 8 +- .../public/search/aggs/param_types/string.ts | 4 +- .../public/search/aggs/test_helpers/index.ts} | 4 +- .../test_helpers/mock_agg_types_registry.ts | 57 + .../aggs/test_helpers/mock_data_services.ts | 54 + .../data/public/search/aggs/types.ts | 2 +- .../data/public/search/aggs/utils.test.tsx | 2 - .../data/public/search/aggs/utils.ts | 39 +- .../data/public/search/expressions/esaggs.ts | 4 +- .../data/public/search/expressions/utils.ts | 5 +- .../core_plugins/data/public/search/mocks.ts | 85 + .../data/public/search/search_service.ts | 60 +- .../data/public/search/tabify/buckets.test.ts | 2 - .../public/search/tabify/get_columns.test.ts | 22 +- .../search/tabify/response_writer.test.ts | 20 +- .../data/public/search/tabify/tabify.test.ts | 16 +- .../brush_event.test.mocks.ts => services.ts} | 13 +- .../components/sidebar/state/reducers.ts | 18 +- .../public/legacy_imports.ts | 2 +- .../public/table_vis_controller.test.ts | 4 +- .../visualizations/public/legacy_imports.ts | 2 +- .../public/np_ready/public/vis_impl.js | 6 +- src/legacy/ui/public/agg_types/index.ts | 9 +- .../ui/public/vis/__tests__/_agg_config.js | 485 ------ .../ui/public/vis/__tests__/_agg_configs.js | 420 ----- .../data/common/field_formats/mocks.ts | 49 + src/plugins/data/public/mocks.ts | 28 +- .../data/public/search/search_source/mocks.ts | 19 - .../editor_frame_service/service.test.tsx | 4 - .../__snapshots__/zeek_details.test.tsx.snap | 1448 ++++++++--------- 102 files changed, 2646 insertions(+), 2101 deletions(-) create mode 100644 src/legacy/core_plugins/data/public/search/aggs/agg_config.test.ts create mode 100644 src/legacy/core_plugins/data/public/search/aggs/agg_configs.test.ts create mode 100644 src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.test.ts create mode 100644 src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.ts rename src/legacy/{ui/public/vis/__tests__/index.js => core_plugins/data/public/search/aggs/test_helpers/index.ts} (86%) create mode 100644 src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts create mode 100644 src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_data_services.ts create mode 100644 src/legacy/core_plugins/data/public/search/mocks.ts rename src/legacy/core_plugins/data/public/{actions/filters/brush_event.test.mocks.ts => services.ts} (76%) delete mode 100644 src/legacy/ui/public/vis/__tests__/_agg_config.js delete mode 100644 src/legacy/ui/public/vis/__tests__/_agg_configs.js create mode 100644 src/plugins/data/common/field_formats/mocks.ts diff --git a/packages/kbn-utility-types/README.md b/packages/kbn-utility-types/README.md index 829fd21e143669..b57e98e379707e 100644 --- a/packages/kbn-utility-types/README.md +++ b/packages/kbn-utility-types/README.md @@ -18,6 +18,7 @@ type B = UnwrapPromise; // string ## Reference +- `Assign` — From `U` assign properties to `T` (just like object assign). - `Ensure` — Makes sure `T` is of type `X`. - `ObservableLike` — Minimal interface for an object resembling an `Observable`. - `PublicContract` — Returns an object with public keys only. diff --git a/packages/kbn-utility-types/index.ts b/packages/kbn-utility-types/index.ts index 808935ed4cb5b8..657d9f547de66e 100644 --- a/packages/kbn-utility-types/index.ts +++ b/packages/kbn-utility-types/index.ts @@ -18,7 +18,7 @@ */ import { PromiseType } from 'utility-types'; -export { $Values, Required, Optional, Class } from 'utility-types'; +export { $Values, Assign, Class, Optional, Required } from 'utility-types'; /** * A type that may or may not be a `Promise`. diff --git a/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.ts b/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.ts index 0e18c7c707fa3f..eb29530f92fee7 100644 --- a/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.ts +++ b/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.ts @@ -19,34 +19,14 @@ import moment from 'moment'; -jest.mock('../../search/aggs', () => ({ - AggConfigs: function AggConfigs() { - return { - createAggConfig: ({ params }: Record) => ({ - params, - getIndexPattern: () => ({ - timeFieldName: 'time', - }), - }), - }; - }, -})); - -jest.mock('../../../../../../plugins/data/public/services', () => ({ - getIndexPatterns: () => { - return { - get: async () => { - return { - id: 'logstash-*', - timeFieldName: 'time', - }; - }, - }; - }, -})); - import { onBrushEvent, BrushEvent } from './brush_event'; +import { mockDataServices } from '../../search/aggs/test_helpers'; +import { IndexPatternsContract } from '../../../../../../plugins/data/public'; +import { dataPluginMock } from '../../../../../../plugins/data/public/mocks'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { setIndexPatterns } from '../../../../../../plugins/data/public/services'; + describe('brushEvent', () => { const DAY_IN_MS = 24 * 60 * 60 * 1000; const JAN_01_2014 = 1388559600000; @@ -59,11 +39,28 @@ describe('brushEvent', () => { }, getIndexPattern: () => ({ timeFieldName: 'time', + fields: { + getByName: () => undefined, + filter: () => [], + }, }), }, ]; beforeEach(() => { + mockDataServices(); + setIndexPatterns(({ + ...dataPluginMock.createStartContract().indexPatterns, + get: async () => ({ + id: 'indexPatternId', + timeFieldName: 'time', + fields: { + getByName: () => undefined, + filter: () => [], + }, + }), + } as unknown) as IndexPatternsContract); + baseEvent = { data: { ordered: { diff --git a/src/legacy/core_plugins/data/public/index.ts b/src/legacy/core_plugins/data/public/index.ts index 8cde5d0a1fc115..8d730d18a17559 100644 --- a/src/legacy/core_plugins/data/public/index.ts +++ b/src/legacy/core_plugins/data/public/index.ts @@ -35,18 +35,18 @@ export { } from '../../../../plugins/data/public'; export { // agg_types - AggParam, - AggParamOption, - DateRangeKey, + AggParam, // only the type is used externally, only in vis editor + AggParamOption, // only the type is used externally + DateRangeKey, // only used in field formatter deserialization, which will live in data IAggConfig, IAggConfigs, IAggType, IFieldParamType, IMetricAggType, - IpRangeKey, + IpRangeKey, // only used in field formatter deserialization, which will live in data ISchemas, - OptionedParamEditorProps, - OptionedValueProp, + OptionedParamEditorProps, // only type is used externally + OptionedValueProp, // only type is used externally } from './search/types'; /** @public static code */ diff --git a/src/legacy/core_plugins/data/public/plugin.ts b/src/legacy/core_plugins/data/public/plugin.ts index e13e8e34eaebec..e2b8ca5dda78cf 100644 --- a/src/legacy/core_plugins/data/public/plugin.ts +++ b/src/legacy/core_plugins/data/public/plugin.ts @@ -36,6 +36,7 @@ import { setOverlays, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../../../plugins/data/public/services'; +import { setSearchServiceShim } from './services'; import { SELECT_RANGE_ACTION, selectRangeAction } from './actions/select_range_action'; import { VALUE_CLICK_ACTION, valueClickAction } from './actions/value_click_action'; import { @@ -112,6 +113,9 @@ export class DataPlugin } public start(core: CoreStart, { data, uiActions }: DataPluginStartDependencies): DataStart { + const search = this.search.start(core); + setSearchServiceShim(search); + setUiSettings(core.uiSettings); setQueryService(data.query); setIndexPatterns(data.indexPatterns); @@ -123,7 +127,7 @@ export class DataPlugin uiActions.attachAction(VALUE_CLICK_TRIGGER, VALUE_CLICK_ACTION); return { - search: this.search.start(core), + search, }; } diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_config.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_config.test.ts new file mode 100644 index 00000000000000..7769aa29184d3a --- /dev/null +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_config.test.ts @@ -0,0 +1,497 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { identity } from 'lodash'; + +import { AggConfig, IAggConfig } from './agg_config'; +import { AggConfigs, CreateAggConfigParams } from './agg_configs'; +import { AggType } from './agg_types'; +import { AggTypesRegistryStart } from './agg_types_registry'; +import { mockDataServices, mockAggTypesRegistry } from './test_helpers'; +import { IndexPatternField, IndexPattern } from '../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { stubIndexPatternWithFields } from '../../../../../../plugins/data/public/stubs'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { dataPluginMock } from '../../../../../../plugins/data/public/mocks'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { setFieldFormats } from '../../../../../../plugins/data/public/services'; + +describe('AggConfig', () => { + let indexPattern: IndexPattern; + let typesRegistry: AggTypesRegistryStart; + + beforeEach(() => { + jest.restoreAllMocks(); + mockDataServices(); + indexPattern = stubIndexPatternWithFields as IndexPattern; + typesRegistry = mockAggTypesRegistry(); + }); + + describe('#toDsl', () => { + it('calls #write()', () => { + const ac = new AggConfigs(indexPattern, [], { typesRegistry }); + const configStates = { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }; + const aggConfig = ac.createAggConfig(configStates); + + const spy = jest.spyOn(aggConfig, 'write').mockImplementation(() => ({ params: {} })); + aggConfig.toDsl(); + expect(spy).toHaveBeenCalledTimes(1); + }); + + it('uses the type name as the agg name', () => { + const ac = new AggConfigs(indexPattern, [], { typesRegistry }); + const configStates = { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }; + const aggConfig = ac.createAggConfig(configStates); + + jest.spyOn(aggConfig, 'write').mockImplementation(() => ({ params: {} })); + const dsl = aggConfig.toDsl(); + expect(dsl).toHaveProperty('date_histogram'); + }); + + it('uses the params from #write() output as the agg params', () => { + const ac = new AggConfigs(indexPattern, [], { typesRegistry }); + const configStates = { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }; + const aggConfig = ac.createAggConfig(configStates); + + const football = {}; + jest.spyOn(aggConfig, 'write').mockImplementation(() => ({ params: football })); + const dsl = aggConfig.toDsl(); + expect(dsl.date_histogram).toBe(football); + }); + + it('includes subAggs from #write() output', () => { + const configStates = [ + { + enabled: true, + type: 'avg', + schema: 'metric', + params: {}, + }, + { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }, + ]; + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + + const histoConfig = ac.byName('date_histogram')[0]; + const avgConfig = ac.byName('avg')[0]; + const football = {}; + + jest + .spyOn(histoConfig, 'write') + .mockImplementation(() => ({ params: {}, subAggs: [avgConfig] })); + jest.spyOn(avgConfig, 'write').mockImplementation(() => ({ params: football })); + + const dsl = histoConfig.toDsl(); + expect(dsl).toHaveProperty('aggs'); + expect(dsl.aggs).toHaveProperty(avgConfig.id); + expect(dsl.aggs[avgConfig.id]).toHaveProperty('avg'); + expect(dsl.aggs[avgConfig.id].avg).toBe(football); + }); + }); + + describe('::ensureIds', () => { + it('accepts an array of objects and assigns ids to them', () => { + const objs = [{}, {}, {}, {}]; + AggConfig.ensureIds(objs); + expect(objs[0]).toHaveProperty('id', '1'); + expect(objs[1]).toHaveProperty('id', '2'); + expect(objs[2]).toHaveProperty('id', '3'); + expect(objs[3]).toHaveProperty('id', '4'); + }); + + it('assigns ids relative to the other only item in the list', () => { + const objs = [{ id: '100' }, {}]; + AggConfig.ensureIds(objs); + expect(objs[0]).toHaveProperty('id', '100'); + expect(objs[1]).toHaveProperty('id', '101'); + }); + + it('assigns ids relative to the other items in the list', () => { + const objs = [{ id: '100' }, { id: '200' }, { id: '500' }, { id: '350' }, {}]; + AggConfig.ensureIds(objs); + expect(objs[0]).toHaveProperty('id', '100'); + expect(objs[1]).toHaveProperty('id', '200'); + expect(objs[2]).toHaveProperty('id', '500'); + expect(objs[3]).toHaveProperty('id', '350'); + expect(objs[4]).toHaveProperty('id', '501'); + }); + + it('uses ::nextId to get the starting value', () => { + jest.spyOn(AggConfig, 'nextId').mockImplementation(() => 534); + const objs = AggConfig.ensureIds([{}]); + expect(objs[0]).toHaveProperty('id', '534'); + }); + + it('only calls ::nextId once', () => { + const start = 420; + const spy = jest.spyOn(AggConfig, 'nextId').mockImplementation(() => start); + const objs = AggConfig.ensureIds([{}, {}, {}, {}, {}, {}, {}]); + + expect(spy).toHaveBeenCalledTimes(1); + objs.forEach((obj, i) => { + expect(obj).toHaveProperty('id', String(start + i)); + }); + }); + }); + + describe('::nextId', () => { + it('accepts a list of objects and picks the next id', () => { + const next = AggConfig.nextId([{ id: '100' }, { id: '500' }] as IAggConfig[]); + expect(next).toBe(501); + }); + + it('handles an empty list', () => { + const next = AggConfig.nextId([]); + expect(next).toBe(1); + }); + + it('fails when the list is not defined', () => { + expect(() => { + AggConfig.nextId((undefined as unknown) as IAggConfig[]); + }).toThrowError(); + }); + }); + + describe('#toJsonDataEquals', () => { + const testsIdentical = [ + [ + { + enabled: true, + type: 'count', + schema: 'metric', + params: { field: '@timestamp' }, + }, + ], + [ + { + enabled: true, + type: 'avg', + schema: 'metric', + params: {}, + }, + { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }, + ], + ]; + + testsIdentical.forEach((configState, index) => { + it(`identical aggregations (${index})`, () => { + const ac1 = new AggConfigs(indexPattern, configState, { typesRegistry }); + const ac2 = new AggConfigs(indexPattern, configState, { typesRegistry }); + expect(ac1.jsonDataEquals(ac2.aggs)).toBe(true); + }); + }); + + const testsIdenticalDifferentOrder = [ + { + config1: [ + { + enabled: true, + type: 'avg', + schema: 'metric', + params: {}, + }, + { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }, + ], + config2: [ + { + enabled: true, + schema: 'metric', + type: 'avg', + params: {}, + }, + { + enabled: true, + schema: 'segment', + type: 'date_histogram', + params: {}, + }, + ], + }, + ]; + + testsIdenticalDifferentOrder.forEach((test, index) => { + it(`identical aggregations (${index}) - init json is in different order`, () => { + const ac1 = new AggConfigs(indexPattern, test.config1, { typesRegistry }); + const ac2 = new AggConfigs(indexPattern, test.config2, { typesRegistry }); + expect(ac1.jsonDataEquals(ac2.aggs)).toBe(true); + }); + }); + + const testsDifferent = [ + { + config1: [ + { + enabled: true, + type: 'avg', + schema: 'metric', + params: {}, + }, + { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }, + ], + config2: [ + { + enabled: true, + type: 'max', + schema: 'metric', + params: {}, + }, + { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }, + ], + }, + { + config1: [ + { + enabled: true, + type: 'count', + schema: 'metric', + params: { field: '@timestamp' }, + }, + ], + config2: [ + { + enabled: true, + type: 'count', + schema: 'metric', + params: { field: '@timestamp' }, + }, + { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }, + ], + }, + ]; + + testsDifferent.forEach((test, index) => { + it(`different aggregations (${index})`, () => { + const ac1 = new AggConfigs(indexPattern, test.config1, { typesRegistry }); + const ac2 = new AggConfigs(indexPattern, test.config2, { typesRegistry }); + expect(ac1.jsonDataEquals(ac2.aggs)).toBe(false); + }); + }); + }); + + describe('#toJSON', () => { + it('includes the aggs id, params, type and schema', () => { + const ac = new AggConfigs(indexPattern, [], { typesRegistry }); + const configStates = { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }; + const aggConfig = ac.createAggConfig(configStates); + + expect(aggConfig.id).toBe('1'); + expect(typeof aggConfig.params).toBe('object'); + expect(aggConfig.type).toBeInstanceOf(AggType); + expect(aggConfig.type).toHaveProperty('name', 'date_histogram'); + expect(typeof aggConfig.schema).toBe('object'); + expect(aggConfig.schema).toHaveProperty('name', 'segment'); + + const state = aggConfig.toJSON(); + expect(state).toHaveProperty('id', '1'); + expect(typeof state.params).toBe('object'); + expect(state).toHaveProperty('type', 'date_histogram'); + expect(state).toHaveProperty('schema', 'segment'); + }); + + it('test serialization order is identical (for visual consistency)', () => { + const configStates = [ + { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: {}, + }, + ]; + const ac1 = new AggConfigs(indexPattern, configStates, { typesRegistry }); + const ac2 = new AggConfigs(indexPattern, configStates, { typesRegistry }); + + // this relies on the assumption that js-engines consistently loop over properties in insertion order. + // most likely the case, but strictly speaking not guaranteed by the JS and JSON specifications. + expect(JSON.stringify(ac1.aggs) === JSON.stringify(ac2.aggs)).toBe(true); + }); + }); + + describe('#makeLabel', () => { + let aggConfig: AggConfig; + + beforeEach(() => { + const ac = new AggConfigs(indexPattern, [], { typesRegistry }); + aggConfig = ac.createAggConfig({ type: 'count' } as CreateAggConfigParams); + }); + + it('uses the custom label if it is defined', () => { + aggConfig.params.customLabel = 'Custom label'; + const label = aggConfig.makeLabel(); + expect(label).toBe(aggConfig.params.customLabel); + }); + + it('default label should be "Count"', () => { + const label = aggConfig.makeLabel(); + expect(label).toBe('Count'); + }); + + it('default label should be "Percentage of Count" when percentageMode is set to true', () => { + const label = aggConfig.makeLabel(true); + expect(label).toBe('Percentage of Count'); + }); + + it('empty label if the type is not defined', () => { + aggConfig.type = (undefined as unknown) as AggType; + const label = aggConfig.makeLabel(); + expect(label).toBe(''); + }); + }); + + describe('#fieldFormatter - custom getFormat handler', () => { + it('returns formatter from getFormat handler', () => { + setFieldFormats({ + ...dataPluginMock.createStartContract().fieldFormats, + getDefaultInstance: jest.fn().mockImplementation(() => ({ + getConverterFor: jest.fn().mockImplementation(() => (t: string) => t), + })) as any, + }); + + const ac = new AggConfigs(indexPattern, [], { typesRegistry }); + const configStates = { + enabled: true, + type: 'count', + schema: 'metric', + params: { field: '@timestamp' }, + }; + const aggConfig = ac.createAggConfig(configStates); + + const fieldFormatter = aggConfig.fieldFormatter(); + expect(fieldFormatter).toBeDefined(); + expect(fieldFormatter('text')).toBe('text'); + }); + }); + + // TODO: Converting these field formatter tests from browser tests to unit + // tests makes them much less helpful due to the extensive use of mocking. + // We should revisit these and rewrite them into something more useful. + describe('#fieldFormatter - no custom getFormat handler', () => { + let aggConfig: AggConfig; + + beforeEach(() => { + setFieldFormats({ + ...dataPluginMock.createStartContract().fieldFormats, + getDefaultInstance: jest.fn().mockImplementation(() => ({ + getConverterFor: (t?: string) => t || identity, + })) as any, + }); + indexPattern.fields.getByName = name => + ({ + format: { + getConverterFor: (t?: string) => t || identity, + }, + } as IndexPatternField); + + const configStates = { + enabled: true, + type: 'histogram', + schema: 'bucket', + params: { + field: { + format: { + getConverterFor: (t?: string) => t || identity, + }, + }, + }, + }; + const ac = new AggConfigs(indexPattern, [configStates], { typesRegistry }); + aggConfig = ac.createAggConfig(configStates); + }); + + it("returns the field's formatter", () => { + expect(aggConfig.fieldFormatter().toString()).toBe( + aggConfig + .getField() + .format.getConverterFor() + .toString() + ); + }); + + it('returns the string format if the field does not have a format', () => { + const agg = aggConfig; + agg.params.field = { type: 'number', format: null }; + const fieldFormatter = agg.fieldFormatter(); + expect(fieldFormatter).toBeDefined(); + expect(fieldFormatter('text')).toBe('text'); + }); + + it('returns the string format if there is no field', () => { + const agg = aggConfig; + delete agg.params.field; + const fieldFormatter = agg.fieldFormatter(); + expect(fieldFormatter).toBeDefined(); + expect(fieldFormatter('text')).toBe('text'); + }); + + it('returns the html converter if "html" is passed in', () => { + const field = indexPattern.fields.getByName('bytes'); + expect(aggConfig.fieldFormatter('html').toString()).toBe( + field!.format.getConverterFor('html').toString() + ); + }); + }); +}); diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_config.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_config.ts index 2b21c5c4868a52..659bec3f702e37 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_config.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_config.ts @@ -17,16 +17,8 @@ * under the License. */ -/** - * @name AggConfig - * - * @description This class represents an aggregation, which is displayed in the left-hand nav of - * the Visualize app. - */ - import _ from 'lodash'; import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; import { IAggType } from './agg_type'; import { AggGroupNames } from './agg_groups'; import { writeParams } from './agg_params'; @@ -38,18 +30,20 @@ import { FieldFormatsContentType, KBN_FIELD_TYPES, } from '../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getFieldFormats } from '../../../../../../plugins/data/public/services'; export interface AggConfigOptions { - enabled: boolean; - type: string; - params: any; + type: IAggType; + enabled?: boolean; id?: string; - schema?: string; + params?: Record; + schema?: string | Schema; } const unknownSchema: Schema = { name: 'unknown', - title: 'Unknown', + title: 'Unknown', // only here for illustrative purposes hideCustomLabel: true, aggFilter: [], min: 1, @@ -65,21 +59,6 @@ const unknownSchema: Schema = { }, }; -const getTypeFromRegistry = (type: string): IAggType => { - // We need to inline require here, since we're having a cyclic dependency - // from somewhere inside agg_types back to AggConfig. - const aggTypes = require('../aggs').aggTypes; - const registeredType = - aggTypes.metrics.find((agg: IAggType) => agg.name === type) || - aggTypes.buckets.find((agg: IAggType) => agg.name === type); - - if (!registeredType) { - throw new Error('unknown type'); - } - - return registeredType; -}; - const getSchemaFromRegistry = (schemas: any, schema: string): Schema => { let registeredSchema = schemas ? schemas.byName[schema] : null; if (!registeredSchema) { @@ -90,6 +69,13 @@ const getSchemaFromRegistry = (schemas: any, schema: string): Schema => { return registeredSchema; }; +/** + * @name AggConfig + * + * @description This class represents an aggregation, which is displayed in the left-hand nav of + * the Visualize app. + */ + // TODO need to make a more explicit interface for this export type IAggConfig = AggConfig; @@ -101,9 +87,9 @@ export class AggConfig { * @param {array[object]} list - a list of objects, objects can be anything really * @return {array} - the list that was passed in */ - static ensureIds(list: AggConfig[]) { - const have: AggConfig[] = []; - const haveNot: AggConfig[] = []; + static ensureIds(list: any[]) { + const have: IAggConfig[] = []; + const haveNot: AggConfigOptions[] = []; list.forEach(function(obj) { (obj.id ? have : haveNot).push(obj); }); @@ -121,7 +107,7 @@ export class AggConfig { * * @return {array} list - a list of objects with id properties */ - static nextId(list: AggConfig[]) { + static nextId(list: IAggConfig[]) { return ( 1 + list.reduce(function(max, obj) { @@ -161,10 +147,10 @@ export class AggConfig { // set the params to the values from opts, or just to the defaults this.setParams(opts.params || {}); - // @ts-ignore - this.__type = this.__type; // @ts-ignore this.__schema = this.__schema; + // @ts-ignore + this.__type = this.__type; } /** @@ -394,7 +380,8 @@ export class AggConfig { } fieldOwnFormatter(contentType?: FieldFormatsContentType, defaultFormat?: any) { - const fieldFormatsService = npStart.plugins.data.fieldFormats; + const fieldFormatsService = getFieldFormats(); + const field = this.getField(); let format = field && field.format; if (!format) format = defaultFormat; @@ -456,8 +443,8 @@ export class AggConfig { }); } - public setType(type: string | IAggType) { - this.type = typeof type === 'string' ? getTypeFromRegistry(type) : type; + public setType(type: IAggType) { + this.type = type; } public get schema() { diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_configs.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_configs.test.ts new file mode 100644 index 00000000000000..29f16b1e4f0bf2 --- /dev/null +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_configs.test.ts @@ -0,0 +1,503 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { indexBy } from 'lodash'; +import { AggConfig } from './agg_config'; +import { AggConfigs } from './agg_configs'; +import { AggTypesRegistryStart } from './agg_types_registry'; +import { Schemas } from './schemas'; +import { AggGroupNames } from './agg_groups'; +import { mockDataServices, mockAggTypesRegistry } from './test_helpers'; +import { IndexPatternField, IndexPattern } from '../../../../../../plugins/data/public'; +import { + stubIndexPattern, + stubIndexPatternWithFields, + // eslint-disable-next-line @kbn/eslint/no-restricted-paths +} from '../../../../../../plugins/data/public/stubs'; + +describe('AggConfigs', () => { + let indexPattern: IndexPattern; + let typesRegistry: AggTypesRegistryStart; + + beforeEach(() => { + indexPattern = stubIndexPatternWithFields as IndexPattern; + typesRegistry = mockAggTypesRegistry(); + }); + + describe('constructor', () => { + it('handles passing just a type', () => { + const configStates = [ + { + enabled: true, + type: 'histogram', + params: {}, + }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + expect(ac.aggs).toHaveLength(1); + }); + + it('attempts to ensure that all states have an id', () => { + const configStates = [ + { + enabled: true, + type: 'histogram', + params: {}, + }, + { + enabled: true, + type: 'date_histogram', + params: {}, + }, + { + enabled: true, + type: 'terms', + params: {}, + schema: 'split', + }, + ]; + + const spy = jest.spyOn(AggConfig, 'ensureIds'); + new AggConfigs(indexPattern, configStates, { typesRegistry }); + expect(spy).toHaveBeenCalledTimes(1); + expect(spy.mock.calls[0]).toEqual([configStates]); + spy.mockRestore(); + }); + + describe('defaults', () => { + const schemas = new Schemas([ + { + group: AggGroupNames.Metrics, + name: 'metric', + title: 'Simple', + min: 1, + max: 2, + defaults: [ + { schema: 'metric', type: 'count' }, + { schema: 'metric', type: 'avg' }, + { schema: 'metric', type: 'sum' }, + ], + }, + { + group: AggGroupNames.Buckets, + name: 'segment', + title: 'Example', + min: 0, + max: 1, + defaults: [ + { schema: 'segment', type: 'terms' }, + { schema: 'segment', type: 'filters' }, + ], + }, + ]); + + it('should only set the number of defaults defined by the max', () => { + const ac = new AggConfigs(indexPattern, [], { + schemas: schemas.all, + typesRegistry, + }); + expect(ac.bySchemaName('metric')).toHaveLength(2); + }); + + it('should set the defaults defined in the schema when none exist', () => { + const ac = new AggConfigs(indexPattern, [], { + schemas: schemas.all, + typesRegistry, + }); + expect(ac.aggs).toHaveLength(3); + }); + + it('should NOT set the defaults defined in the schema when some exist', () => { + const configStates = [ + { + enabled: true, + type: 'date_histogram', + params: {}, + schema: 'segment', + }, + ]; + const ac = new AggConfigs(indexPattern, configStates, { + schemas: schemas.all, + typesRegistry, + }); + expect(ac.aggs).toHaveLength(3); + expect(ac.bySchemaName('segment')[0].type.name).toEqual('date_histogram'); + }); + }); + }); + + describe('#createAggConfig', () => { + it('accepts a configState which is provided as an AggConfig object', () => { + const configStates = [ + { + enabled: true, + type: 'histogram', + params: {}, + }, + { + enabled: true, + type: 'date_histogram', + params: {}, + }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + expect(ac.aggs).toHaveLength(2); + + ac.createAggConfig( + new AggConfig(ac, { + enabled: true, + type: typesRegistry.get('terms'), + params: {}, + schema: 'split', + }) + ); + expect(ac.aggs).toHaveLength(3); + }); + + it('adds new AggConfig entries to AggConfigs by default', () => { + const configStates = [ + { + enabled: true, + type: 'histogram', + params: {}, + }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + expect(ac.aggs).toHaveLength(1); + + ac.createAggConfig({ + enabled: true, + type: 'terms', + params: {}, + schema: 'split', + }); + expect(ac.aggs).toHaveLength(2); + }); + + it('does not add an agg to AggConfigs if addToAggConfigs: false', () => { + const configStates = [ + { + enabled: true, + type: 'histogram', + params: {}, + }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + expect(ac.aggs).toHaveLength(1); + + ac.createAggConfig( + { + enabled: true, + type: 'terms', + params: {}, + schema: 'split', + }, + { addToAggConfigs: false } + ); + expect(ac.aggs).toHaveLength(1); + }); + }); + + describe('#getRequestAggs', () => { + it('performs a stable sort, but moves metrics to the bottom', () => { + const configStates = [ + { type: 'avg', enabled: true, params: {}, schema: 'metric' }, + { type: 'terms', enabled: true, params: {}, schema: 'split' }, + { type: 'histogram', enabled: true, params: {}, schema: 'split' }, + { type: 'sum', enabled: true, params: {}, schema: 'metric' }, + { type: 'date_histogram', enabled: true, params: {}, schema: 'segment' }, + { type: 'filters', enabled: true, params: {}, schema: 'split' }, + { type: 'percentiles', enabled: true, params: {}, schema: 'metric' }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + const sorted = ac.getRequestAggs(); + const aggs = indexBy(ac.aggs, agg => agg.type.name); + + expect(sorted.shift()).toBe(aggs.terms); + expect(sorted.shift()).toBe(aggs.histogram); + expect(sorted.shift()).toBe(aggs.date_histogram); + expect(sorted.shift()).toBe(aggs.filters); + expect(sorted.shift()).toBe(aggs.avg); + expect(sorted.shift()).toBe(aggs.sum); + expect(sorted.shift()).toBe(aggs.percentiles); + expect(sorted).toHaveLength(0); + }); + }); + + describe('#getResponseAggs', () => { + it('returns all request aggs for basic aggs', () => { + const configStates = [ + { type: 'terms', enabled: true, params: {}, schema: 'split' }, + { type: 'date_histogram', enabled: true, params: {}, schema: 'segment' }, + { type: 'count', enabled: true, params: {}, schema: 'metric' }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + const sorted = ac.getResponseAggs(); + const aggs = indexBy(ac.aggs, agg => agg.type.name); + + expect(sorted.shift()).toBe(aggs.terms); + expect(sorted.shift()).toBe(aggs.date_histogram); + expect(sorted.shift()).toBe(aggs.count); + expect(sorted).toHaveLength(0); + }); + + it('expands aggs that have multiple responses', () => { + const configStates = [ + { type: 'terms', enabled: true, params: {}, schema: 'split' }, + { type: 'date_histogram', enabled: true, params: {}, schema: 'segment' }, + { type: 'percentiles', enabled: true, params: { percents: [1, 2, 3] }, schema: 'metric' }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + const sorted = ac.getResponseAggs(); + const aggs = indexBy(ac.aggs, agg => agg.type.name); + + expect(sorted.shift()).toBe(aggs.terms); + expect(sorted.shift()).toBe(aggs.date_histogram); + expect(sorted.shift()!.id!).toBe(aggs.percentiles.id + '.' + 1); + expect(sorted.shift()!.id!).toBe(aggs.percentiles.id + '.' + 2); + expect(sorted.shift()!.id!).toBe(aggs.percentiles.id + '.' + 3); + expect(sorted).toHaveLength(0); + }); + }); + + describe('#toDsl', () => { + const schemas = new Schemas([ + { + group: AggGroupNames.Buckets, + name: 'segment', + }, + { + group: AggGroupNames.Buckets, + name: 'split', + }, + ]); + + beforeEach(() => { + mockDataServices(); + indexPattern = stubIndexPattern as IndexPattern; + indexPattern.fields.getByName = name => (name as unknown) as IndexPatternField; + }); + + it('uses the sorted aggs', () => { + const configStates = [{ enabled: true, type: 'avg', params: { field: 'bytes' } }]; + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + const spy = jest.spyOn(AggConfigs.prototype, 'getRequestAggs'); + ac.toDsl(); + expect(spy).toHaveBeenCalledTimes(1); + spy.mockRestore(); + }); + + it('calls aggConfig#toDsl() on each aggConfig and compiles the nested output', () => { + const configStates = [ + { enabled: true, type: 'date_histogram', params: {}, schema: 'segment' }, + { enabled: true, type: 'terms', params: {}, schema: 'split' }, + { enabled: true, type: 'count', params: {} }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { + typesRegistry, + schemas: schemas.all, + }); + + const aggInfos = ac.aggs.map(aggConfig => { + const football = {}; + aggConfig.toDsl = jest.fn().mockImplementation(() => football); + + return { + id: aggConfig.id, + football, + }; + }); + + (function recurse(lvl: Record): void { + const info = aggInfos.shift(); + if (!info) return; + + expect(lvl).toHaveProperty(info.id); + expect(lvl[info.id]).toBe(info.football); + + if (lvl[info.id].aggs) { + return recurse(lvl[info.id].aggs); + } + })(ac.toDsl()); + + expect(aggInfos).toHaveLength(1); + }); + + it("skips aggs that don't have a dsl representation", () => { + const configStates = [ + { + enabled: true, + type: 'date_histogram', + params: { field: '@timestamp', interval: '10s' }, + schema: 'segment', + }, + { + enabled: true, + type: 'count', + params: {}, + schema: 'metric', + }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + const dsl = ac.toDsl(); + const histo = ac.byName('date_histogram')[0]; + const count = ac.byName('count')[0]; + + expect(dsl).toHaveProperty(histo.id); + expect(typeof dsl[histo.id]).toBe('object'); + expect(dsl[histo.id]).not.toHaveProperty('aggs'); + expect(dsl).not.toHaveProperty(count.id); + }); + + it('writes multiple metric aggregations at the same level', () => { + const configStates = [ + { + enabled: true, + type: 'date_histogram', + schema: 'segment', + params: { field: '@timestamp', interval: '10s' }, + }, + { enabled: true, type: 'avg', schema: 'metric', params: { field: 'bytes' } }, + { enabled: true, type: 'sum', schema: 'metric', params: { field: 'bytes' } }, + { enabled: true, type: 'min', schema: 'metric', params: { field: 'bytes' } }, + { enabled: true, type: 'max', schema: 'metric', params: { field: 'bytes' } }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { + typesRegistry, + schemas: schemas.all, + }); + const dsl = ac.toDsl(); + const histo = ac.byName('date_histogram')[0]; + const metrics = ac.bySchemaGroup('metrics'); + + expect(dsl).toHaveProperty(histo.id); + expect(typeof dsl[histo.id]).toBe('object'); + expect(dsl[histo.id]).toHaveProperty('aggs'); + + metrics.forEach(metric => { + expect(dsl[histo.id].aggs).toHaveProperty(metric.id); + expect(dsl[histo.id].aggs[metric.id]).not.toHaveProperty('aggs'); + }); + }); + + it('writes multiple metric aggregations at every level if the vis is hierarchical', () => { + const configStates = [ + { enabled: true, type: 'terms', schema: 'segment', params: { field: 'bytes', orderBy: 1 } }, + { enabled: true, type: 'terms', schema: 'segment', params: { field: 'bytes', orderBy: 1 } }, + { enabled: true, id: '1', type: 'avg', schema: 'metric', params: { field: 'bytes' } }, + { enabled: true, type: 'sum', schema: 'metric', params: { field: 'bytes' } }, + { enabled: true, type: 'min', schema: 'metric', params: { field: 'bytes' } }, + { enabled: true, type: 'max', schema: 'metric', params: { field: 'bytes' } }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + const topLevelDsl = ac.toDsl(true); + const buckets = ac.bySchemaGroup('buckets'); + const metrics = ac.bySchemaGroup('metrics'); + + (function checkLevel(dsl) { + const bucket = buckets.shift(); + if (!bucket) return; + + expect(dsl).toHaveProperty(bucket.id); + + expect(typeof dsl[bucket.id]).toBe('object'); + expect(dsl[bucket.id]).toHaveProperty('aggs'); + + metrics.forEach((metric: AggConfig) => { + expect(dsl[bucket.id].aggs).toHaveProperty(metric.id); + expect(dsl[bucket.id].aggs[metric.id]).not.toHaveProperty('aggs'); + }); + + if (buckets.length) { + checkLevel(dsl[bucket.id].aggs); + } + })(topLevelDsl); + }); + + it('adds the parent aggs of nested metrics at every level if the vis is hierarchical', () => { + const configStates = [ + { + enabled: true, + id: '1', + type: 'avg_bucket', + schema: 'metric', + params: { + customBucket: { + id: '1-bucket', + type: 'date_histogram', + schema: 'bucketAgg', + params: { + field: '@timestamp', + interval: '10s', + }, + }, + customMetric: { + id: '1-metric', + type: 'count', + schema: 'metricAgg', + params: {}, + }, + }, + }, + { + enabled: true, + id: '2', + type: 'terms', + schema: 'bucket', + params: { + field: 'clientip', + }, + }, + { + enabled: true, + id: '3', + type: 'terms', + schema: 'bucket', + params: { + field: 'machine.os.raw', + }, + }, + ]; + + const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); + const topLevelDsl = ac.toDsl(true)['2']; + + expect(Object.keys(topLevelDsl.aggs)).toContain('1'); + expect(Object.keys(topLevelDsl.aggs)).toContain('1-bucket'); + expect(topLevelDsl.aggs['1'].avg_bucket).toHaveProperty('buckets_path', '1-bucket>_count'); + expect(Object.keys(topLevelDsl.aggs['3'].aggs)).toContain('1'); + expect(Object.keys(topLevelDsl.aggs['3'].aggs)).toContain('1-bucket'); + expect(topLevelDsl.aggs['3'].aggs['1'].avg_bucket).toHaveProperty( + 'buckets_path', + '1-bucket>_count' + ); + }); + }); +}); diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_configs.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_configs.ts index 8e091ed5f21ae0..ab70e66b1e138c 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_configs.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_configs.ts @@ -17,17 +17,12 @@ * under the License. */ -/** - * @name AggConfig - * - * @extends IndexedArray - * - * @description A "data structure"-like class with methods for indexing and - * accessing instances of AggConfig. - */ - import _ from 'lodash'; +import { Assign } from '@kbn/utility-types'; + import { AggConfig, AggConfigOptions, IAggConfig } from './agg_config'; +import { IAggType } from './agg_type'; +import { AggTypesRegistryStart } from './agg_types_registry'; import { Schema } from './schemas'; import { AggGroupNames } from './agg_groups'; import { @@ -55,6 +50,24 @@ function parseParentAggs(dslLvlCursor: any, dsl: any) { } } +export interface AggConfigsOptions { + schemas?: Schemas; + typesRegistry: AggTypesRegistryStart; +} + +export type CreateAggConfigParams = Assign; + +/** + * @name AggConfigs + * + * @description A "data structure"-like class with methods for indexing and + * accessing instances of AggConfig. This should never be instantiated directly + * outside of this plugin. Rather, downstream plugins should do this via + * `createAggConfigs()` + * + * @internal + */ + // TODO need to make a more explicit interface for this export type IAggConfigs = AggConfigs; @@ -62,23 +75,31 @@ export class AggConfigs { public indexPattern: IndexPattern; public schemas: any; public timeRange?: TimeRange; + private readonly typesRegistry: AggTypesRegistryStart; aggs: IAggConfig[]; - constructor(indexPattern: IndexPattern, configStates = [] as any, schemas?: any) { + constructor( + indexPattern: IndexPattern, + configStates: CreateAggConfigParams[] = [], + opts: AggConfigsOptions + ) { + this.typesRegistry = opts.typesRegistry; + configStates = AggConfig.ensureIds(configStates); this.aggs = []; this.indexPattern = indexPattern; - this.schemas = schemas; + this.schemas = opts.schemas; configStates.forEach((params: any) => this.createAggConfig(params)); - if (schemas) { - this.initializeDefaultsFromSchemas(schemas); + if (this.schemas) { + this.initializeDefaultsFromSchemas(this.schemas); } } + // do this wherever the schemas were passed in, & pass in state defaults instead initializeDefaultsFromSchemas(schemas: Schemas) { // Set the defaults for any schema which has them. If the defaults // for some reason has more then the max only set the max number @@ -91,10 +112,11 @@ export class AggConfigs { }) .each((schema: any) => { if (!this.aggs.find((agg: AggConfig) => agg.schema && agg.schema.name === schema.name)) { + // the result here should be passable as a configState const defaults = schema.defaults.slice(0, schema.max); _.each(defaults, defaultState => { const state = _.defaults({ id: AggConfig.nextId(this.aggs) }, defaultState); - this.aggs.push(new AggConfig(this, state as AggConfigOptions)); + this.createAggConfig(state as AggConfigOptions); }); } }) @@ -124,28 +146,36 @@ export class AggConfigs { if (!enabledOnly) return true; return agg.enabled; }; - const aggConfigs = new AggConfigs( - this.indexPattern, - this.aggs.filter(filterAggs), - this.schemas - ); + + const aggConfigs = new AggConfigs(this.indexPattern, this.aggs.filter(filterAggs), { + schemas: this.schemas, + typesRegistry: this.typesRegistry, + }); + return aggConfigs; } createAggConfig = ( - params: AggConfig | AggConfigOptions, + params: CreateAggConfigParams, { addToAggConfigs = true } = {} ) => { + const { type } = params; let aggConfig; + if (params instanceof AggConfig) { aggConfig = params; params.parent = this; } else { - aggConfig = new AggConfig(this, params); + aggConfig = new AggConfig(this, { + ...params, + type: typeof type === 'string' ? this.typesRegistry.get(type) : type, + }); } + if (addToAggConfigs) { this.aggs.push(aggConfig); } + return aggConfig as T; }; @@ -166,10 +196,10 @@ export class AggConfigs { return true; } - toDsl(hierarchical: boolean = false) { + toDsl(hierarchical: boolean = false): Record { const dslTopLvl = {}; let dslLvlCursor: Record; - let nestedMetrics: Array<{ config: AggConfig; dsl: any }> | []; + let nestedMetrics: Array<{ config: AggConfig; dsl: Record }> | []; if (hierarchical) { // collect all metrics, and filter out the ones that we won't be copying diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_params.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_params.test.ts index 30ab272537dad1..b08fcf309e9ed6 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_params.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_params.test.ts @@ -23,8 +23,6 @@ import { FieldParamType } from './param_types/field'; import { OptionedParamType } from './param_types/optioned'; import { AggParamType } from '../aggs/param_types/agg'; -jest.mock('ui/new_platform'); - describe('AggParams class', () => { describe('constructor args', () => { it('accepts an array of param defs', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_type.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_type.test.ts index 6d4c2d1317f505..c78e56dd25887d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_type.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_type.test.ts @@ -19,11 +19,16 @@ import { AggType, AggTypeConfig } from './agg_type'; import { IAggConfig } from './agg_config'; -import { npStart } from 'ui/new_platform'; - -jest.mock('ui/new_platform'); +import { mockDataServices } from './test_helpers'; +import { dataPluginMock } from '../../../../../../plugins/data/public/mocks'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { setFieldFormats } from '../../../../../../plugins/data/public/services'; describe('AggType Class', () => { + beforeEach(() => { + mockDataServices(); + }); + describe('constructor', () => { it("requires a valid config object as it's first param", () => { expect(() => { @@ -153,7 +158,10 @@ describe('AggType Class', () => { }); it('returns default formatter', () => { - npStart.plugins.data.fieldFormats.getDefaultInstance = jest.fn(() => 'default') as any; + setFieldFormats({ + ...dataPluginMock.createStartContract().fieldFormats, + getDefaultInstance: jest.fn(() => 'default') as any, + }); const aggType = new AggType({ name: 'name', diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_type.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_type.ts index 5ccf0f65c0e921..3cd9496d3f23d0 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_type.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_type.ts @@ -19,7 +19,6 @@ import { constant, noop, identity } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; import { initParams } from './agg_params'; import { AggConfig } from './agg_config'; @@ -32,6 +31,8 @@ import { IFieldFormat, ISearchSource, } from '../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getFieldFormats } from '../../../../../../plugins/data/public/services'; export interface AggTypeConfig< TAggConfig extends AggConfig = AggConfig, @@ -65,7 +66,7 @@ export interface AggTypeConfig< const getFormat = (agg: AggConfig) => { const field = agg.getField(); - const fieldFormatsService = npStart.plugins.data.fieldFormats; + const fieldFormatsService = getFieldFormats(); return field ? field.format : fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.STRING); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.test.ts new file mode 100644 index 00000000000000..405f83e237de83 --- /dev/null +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.test.ts @@ -0,0 +1,91 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + AggTypesRegistry, + AggTypesRegistrySetup, + AggTypesRegistryStart, +} from './agg_types_registry'; +import { BucketAggType } from './buckets/_bucket_agg_type'; +import { MetricAggType } from './metrics/metric_agg_type'; + +const bucketType = { name: 'terms', type: 'bucket' } as BucketAggType; +const metricType = { name: 'count', type: 'metric' } as MetricAggType; + +describe('AggTypesRegistry', () => { + let registry: AggTypesRegistry; + let setup: AggTypesRegistrySetup; + let start: AggTypesRegistryStart; + + beforeEach(() => { + registry = new AggTypesRegistry(); + setup = registry.setup(); + start = registry.start(); + }); + + it('registerBucket adds new buckets', () => { + setup.registerBucket(bucketType); + expect(start.getBuckets()).toEqual([bucketType]); + }); + + it('registerBucket throws error when registering duplicate bucket', () => { + expect(() => { + setup.registerBucket(bucketType); + setup.registerBucket(bucketType); + }).toThrow(/already been registered with name: terms/); + }); + + it('registerMetric adds new metrics', () => { + setup.registerMetric(metricType); + expect(start.getMetrics()).toEqual([metricType]); + }); + + it('registerMetric throws error when registering duplicate metric', () => { + expect(() => { + setup.registerMetric(metricType); + setup.registerMetric(metricType); + }).toThrow(/already been registered with name: count/); + }); + + it('gets either buckets or metrics by id', () => { + setup.registerBucket(bucketType); + setup.registerMetric(metricType); + expect(start.get('terms')).toEqual(bucketType); + expect(start.get('count')).toEqual(metricType); + }); + + it('getBuckets retrieves only buckets', () => { + setup.registerBucket(bucketType); + expect(start.getBuckets()).toEqual([bucketType]); + }); + + it('getMetrics retrieves only metrics', () => { + setup.registerMetric(metricType); + expect(start.getMetrics()).toEqual([metricType]); + }); + + it('getAll returns all buckets and metrics', () => { + setup.registerBucket(bucketType); + setup.registerMetric(metricType); + expect(start.getAll()).toEqual({ + buckets: [bucketType], + metrics: [metricType], + }); + }); +}); diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.ts new file mode 100644 index 00000000000000..8a8746106ae587 --- /dev/null +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.ts @@ -0,0 +1,68 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { BucketAggType } from './buckets/_bucket_agg_type'; +import { MetricAggType } from './metrics/metric_agg_type'; + +export type AggTypesRegistrySetup = ReturnType; +export type AggTypesRegistryStart = ReturnType; + +export class AggTypesRegistry { + private readonly bucketAggs = new Map(); + private readonly metricAggs = new Map(); + + setup = () => { + return { + registerBucket: >(type: T): void => { + const { name } = type; + if (this.bucketAggs.get(name)) { + throw new Error(`Bucket agg has already been registered with name: ${name}`); + } + this.bucketAggs.set(name, type); + }, + registerMetric: >(type: T): void => { + const { name } = type; + if (this.metricAggs.get(name)) { + throw new Error(`Metric agg has already been registered with name: ${name}`); + } + this.metricAggs.set(name, type); + }, + }; + }; + + start = () => { + return { + get: (name: string) => { + return this.bucketAggs.get(name) || this.metricAggs.get(name); + }, + getBuckets: () => { + return Array.from(this.bucketAggs.values()); + }, + getMetrics: () => { + return Array.from(this.metricAggs.values()); + }, + getAll: () => { + return { + buckets: Array.from(this.bucketAggs.values()), + metrics: Array.from(this.metricAggs.values()), + }; + }, + }; + }; +} diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/_bucket_agg_type.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/_bucket_agg_type.ts index 546d054c5af978..d6ab58d5250a8c 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/_bucket_agg_type.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/_bucket_agg_type.ts @@ -17,16 +17,16 @@ * under the License. */ -import { AggConfig } from '../agg_config'; +import { IAggConfig } from '../agg_config'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; import { AggType, AggTypeConfig } from '../agg_type'; import { AggParamType } from '../param_types/agg'; -export interface IBucketAggConfig extends AggConfig { +export interface IBucketAggConfig extends IAggConfig { type: InstanceType; } -export interface BucketAggParam +export interface BucketAggParam extends AggParamType { scriptable?: boolean; filterFieldTypes?: KBN_FIELD_TYPES | KBN_FIELD_TYPES[] | '*'; @@ -34,12 +34,12 @@ export interface BucketAggParam const bucketType = 'buckets'; -interface BucketAggTypeConfig +interface BucketAggTypeConfig extends AggTypeConfig> { - getKey?: (bucket: any, key: any, agg: AggConfig) => any; + getKey?: (bucket: any, key: any, agg: IAggConfig) => any; } -export class BucketAggType extends AggType< +export class BucketAggType extends AggType< TBucketAggConfig, BucketAggParam > { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/_interval_options.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/_interval_options.ts index e196687607d198..393d3b745250f4 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/_interval_options.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/_interval_options.ts @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + import { i18n } from '@kbn/i18n'; import { IBucketAggConfig } from './_bucket_agg_type'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts index 0d3f58c50a42e7..2b47dc384bca2f 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts @@ -21,14 +21,22 @@ import moment from 'moment'; import { createFilterDateHistogram } from './date_histogram'; import { intervalOptions } from '../_interval_options'; import { AggConfigs } from '../../agg_configs'; -import { IBucketDateHistogramAggConfig } from '../date_histogram'; +import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; +import { dateHistogramBucketAgg, IBucketDateHistogramAggConfig } from '../date_histogram'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { RangeFilter } from '../../../../../../../../plugins/data/public'; +// TODO: remove this once time buckets is migrated jest.mock('ui/new_platform'); describe('AggConfig Filters', () => { describe('date_histogram', () => { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry([dateHistogramBucketAgg]); + let agg: IBucketDateHistogramAggConfig; let filter: RangeFilter; let bucketStart: any; @@ -56,7 +64,7 @@ describe('AggConfig Filters', () => { params: { field: field.name, interval, customInterval: '5d' }, }, ], - null + { typesRegistry } ); const bucketKey = 1422579600000; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts index 41e806668337e2..c594c7718e58bb 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts @@ -18,16 +18,17 @@ */ import moment from 'moment'; +import { dateRangeBucketAgg } from '../date_range'; import { createFilterDateRange } from './date_range'; import { fieldFormats, FieldFormatsGetConfigFn } from '../../../../../../../../plugins/data/public'; import { AggConfigs } from '../../agg_configs'; +import { mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; -jest.mock('ui/new_platform'); - describe('AggConfig Filters', () => { describe('Date range', () => { + const typesRegistry = mockAggTypesRegistry([dateRangeBucketAgg]); const getConfig = (() => {}) as FieldFormatsGetConfigFn; const getAggConfigs = () => { const field = { @@ -55,7 +56,7 @@ describe('AggConfig Filters', () => { }, }, ], - null + { typesRegistry } ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts index 34cf996826865f..3b9c771e0f15f9 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts @@ -16,14 +16,21 @@ * specific language governing permissions and limitations * under the License. */ + +import { filtersBucketAgg } from '../filters'; import { createFilterFilters } from './filters'; import { AggConfigs } from '../../agg_configs'; +import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; import { IBucketAggConfig } from '../_bucket_agg_type'; -jest.mock('ui/new_platform'); - describe('AggConfig Filters', () => { describe('filters', () => { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry([filtersBucketAgg]); + const getAggConfigs = () => { const field = { name: 'bytes', @@ -52,7 +59,7 @@ describe('AggConfig Filters', () => { }, }, ], - null + { typesRegistry } ); }; it('should return a filters filter', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/histogram.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/histogram.test.ts index 9f845847df5d9d..b046c802c58c15 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/histogram.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/histogram.test.ts @@ -16,16 +16,22 @@ * specific language governing permissions and limitations * under the License. */ + import { createFilterHistogram } from './histogram'; import { AggConfigs } from '../../agg_configs'; +import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; import { fieldFormats, FieldFormatsGetConfigFn } from '../../../../../../../../plugins/data/public'; -jest.mock('ui/new_platform'); - describe('AggConfig Filters', () => { describe('histogram', () => { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry(); + const getConfig = (() => {}) as FieldFormatsGetConfigFn; const getAggConfigs = () => { const field = { @@ -55,7 +61,7 @@ describe('AggConfig Filters', () => { }, }, ], - null + { typesRegistry } ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts index e92ba5cb2852a1..7572c48390dc25 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts @@ -17,17 +17,18 @@ * under the License. */ +import { ipRangeBucketAgg } from '../ip_range'; import { createFilterIpRange } from './ip_range'; -import { AggConfigs } from '../../agg_configs'; +import { AggConfigs, CreateAggConfigParams } from '../../agg_configs'; +import { mockAggTypesRegistry } from '../../test_helpers'; import { fieldFormats } from '../../../../../../../../plugins/data/public'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; -jest.mock('ui/new_platform'); - describe('AggConfig Filters', () => { describe('IP range', () => { - const getAggConfigs = (aggs: Array>) => { + const typesRegistry = mockAggTypesRegistry([ipRangeBucketAgg]); + const getAggConfigs = (aggs: CreateAggConfigParams[]) => { const field = { name: 'ip', format: fieldFormats.IpFormat, @@ -42,7 +43,7 @@ describe('AggConfig Filters', () => { }, } as any; - return new AggConfigs(indexPattern, aggs, null); + return new AggConfigs(indexPattern, aggs, { typesRegistry }); }; it('should return a range filter for ip_range agg', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/range.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/range.test.ts index 33344ca0a34845..324d4252908324 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/range.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/range.test.ts @@ -17,16 +17,22 @@ * under the License. */ +import { rangeBucketAgg } from '../range'; import { createFilterRange } from './range'; import { fieldFormats, FieldFormatsGetConfigFn } from '../../../../../../../../plugins/data/public'; import { AggConfigs } from '../../agg_configs'; +import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; -jest.mock('ui/new_platform'); - describe('AggConfig Filters', () => { describe('range', () => { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry([rangeBucketAgg]); + const getConfig = (() => {}) as FieldFormatsGetConfigFn; const getAggConfigs = () => { const field = { @@ -56,7 +62,7 @@ describe('AggConfig Filters', () => { }, }, ], - null + { typesRegistry } ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts index 7c6e769437ca1d..6db6eb11a5f527 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts @@ -17,17 +17,18 @@ * under the License. */ +import { termsBucketAgg } from '../terms'; import { createFilterTerms } from './terms'; -import { AggConfigs } from '../../agg_configs'; +import { AggConfigs, CreateAggConfigParams } from '../../agg_configs'; +import { mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; import { Filter, ExistsFilter } from '../../../../../../../../plugins/data/public'; -jest.mock('ui/new_platform'); - describe('AggConfig Filters', () => { describe('terms', () => { - const getAggConfigs = (aggs: Array>) => { + const typesRegistry = mockAggTypesRegistry([termsBucketAgg]); + const getAggConfigs = (aggs: CreateAggConfigParams[]) => { const indexPattern = { id: '1234', title: 'logstash-*', @@ -42,7 +43,7 @@ describe('AggConfig Filters', () => { indexPattern, }; - return new AggConfigs(indexPattern, aggs, null); + return new AggConfigs(indexPattern, aggs, { typesRegistry }); }; it('should return a match_phrase filter for terms', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/date_histogram.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/date_histogram.ts index dc0f9baa6d0cc7..a5368135728d49 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/date_histogram.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/date_histogram.ts @@ -21,8 +21,7 @@ import _ from 'lodash'; import moment from 'moment-timezone'; import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; -import { timefilter } from 'ui/timefilter'; +// TODO need to move TimeBuckets import { TimeBuckets } from 'ui/time_buckets'; import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; @@ -33,6 +32,8 @@ import { writeParams } from '../agg_params'; import { isMetricAggType } from '../metrics/metric_agg_type'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getQueryService, getUiSettings } from '../../../../../../../plugins/data/public/services'; const detectedTimezone = moment.tz.guess(); const tzOffset = moment().format('Z'); @@ -40,6 +41,7 @@ const tzOffset = moment().format('Z'); const getInterval = (agg: IBucketAggConfig): string => _.get(agg, ['params', 'interval']); export const setBounds = (agg: IBucketDateHistogramAggConfig, force?: boolean) => { + const { timefilter } = getQueryService().timefilter; if (agg.buckets._alreadySet && !force) return; agg.buckets._alreadySet = true; const bounds = agg.params.timeRange ? timefilter.calculateBounds(agg.params.timeRange) : null; @@ -221,7 +223,7 @@ export const dateHistogramBucketAgg = new BucketAggType { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry([dateRangeBucketAgg]); + const getAggConfigs = (params: Record = {}, hasIncludeTypeMeta: boolean = true) => { const field = { name: 'bytes', @@ -58,7 +67,7 @@ describe('date_range params', () => { params, }, ], - null + { typesRegistry } ); }; @@ -95,7 +104,11 @@ describe('date_range params', () => { }); it('should use the Kibana time_zone if no parameter specified', () => { - npStart.core.uiSettings.get = jest.fn(() => 'kibanaTimeZone' as any); + const core = coreMock.createStart(); + setUiSettings({ + ...core.uiSettings, + get: () => 'kibanaTimeZone' as any, + }); const aggConfigs = getAggConfigs( { @@ -106,6 +119,8 @@ describe('date_range params', () => { const dateRange = aggConfigs.aggs[0]; const params = dateRange.toDsl()[BUCKET_TYPES.DATE_RANGE]; + setUiSettings(core.uiSettings); // clean up + expect(params.time_zone).toBe('kibanaTimeZone'); }); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/date_range.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/date_range.ts index 1dc24ca80035c0..933cdd0577f8da 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/date_range.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/date_range.ts @@ -16,18 +16,20 @@ * specific language governing permissions and limitations * under the License. */ + import { get } from 'lodash'; import moment from 'moment-timezone'; import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; -import { convertDateRangeToString, DateRangeKey } from './lib/date_range'; import { BUCKET_TYPES } from './bucket_agg_types'; import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type'; import { createFilterDateRange } from './create_filter/date_range'; import { KBN_FIELD_TYPES, fieldFormats } from '../../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getFieldFormats, getUiSettings } from '../../../../../../../plugins/data/public/services'; -export { convertDateRangeToString, DateRangeKey }; +import { convertDateRangeToString, DateRangeKey } from './lib/date_range'; +export { convertDateRangeToString, DateRangeKey }; // for BWC const dateRangeTitle = i18n.translate('data.search.aggs.buckets.dateRangeTitle', { defaultMessage: 'Date Range', @@ -41,7 +43,7 @@ export const dateRangeBucketAgg = new BucketAggType({ return { from, to }; }, getFormat(agg) { - const fieldFormatsService = npStart.plugins.data.fieldFormats; + const fieldFormatsService = getFieldFormats(); const formatter = agg.fieldOwnFormatter( fieldFormats.TEXT_CONTEXT_TYPE, @@ -92,7 +94,7 @@ export const dateRangeBucketAgg = new BucketAggType({ ]); } if (!tz) { - const config = npStart.core.uiSettings; + const config = getUiSettings(); const detectedTimezone = moment.tz.guess(); const tzOffset = moment().format('Z'); const isDefaultTimezone = config.isDefault('dateFormat:tz'); diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/filter.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/filter.ts index b52e2d6cfd4df4..80efc0cf92071d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/filter.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/filter.ts @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + import { i18n } from '@kbn/i18n'; import { BucketAggType } from './_bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/filters.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/filters.ts index 6eaf788b83c04a..2852f3e4bdf464 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/filters.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/filters.ts @@ -18,19 +18,21 @@ */ import _ from 'lodash'; -import angular from 'angular'; - import { i18n } from '@kbn/i18n'; import chrome from 'ui/chrome'; + import { createFilterFilters } from './create_filter/filters'; +import { toAngularJSON } from '../utils'; import { BucketAggType } from './_bucket_agg_type'; +import { BUCKET_TYPES } from './bucket_agg_types'; import { Storage } from '../../../../../../../plugins/kibana_utils/public'; + import { getQueryLog, esQuery, Query } from '../../../../../../../plugins/data/public'; -import { BUCKET_TYPES } from './bucket_agg_types'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getUiSettings } from '../../../../../../../plugins/data/public/services'; const config = chrome.getUiSettingsClient(); -const storage = new Storage(window.localStorage); const filtersTitle = i18n.translate('data.search.aggs.buckets.filtersTitle', { defaultMessage: 'Filters', @@ -52,15 +54,17 @@ export const filtersBucketAgg = new BucketAggType({ params: [ { name: 'filters', + // TODO need to get rid of reference to `config` below default: [{ input: { query: '', language: config.get('search:queryLanguage') }, label: '' }], write(aggConfig, output) { + const uiSettings = getUiSettings(); const inFilters: FilterValue[] = aggConfig.params.filters; if (!_.size(inFilters)) return; inFilters.forEach(filter => { const persistedLog = getQueryLog( - config, - storage, + uiSettings, + new Storage(window.localStorage), 'vis_default_editor', filter.input.language ); @@ -77,7 +81,13 @@ export const filtersBucketAgg = new BucketAggType({ return; } - const query = esQuery.buildEsQuery(aggConfig.getIndexPattern(), [input], [], config); + const esQueryConfigs = esQuery.getEsQueryConfig(uiSettings); + const query = esQuery.buildEsQuery( + aggConfig.getIndexPattern(), + [input], + [], + esQueryConfigs + ); if (!query) { console.log('malformed filter agg params, missing "query" on input'); // eslint-disable-line no-console @@ -90,7 +100,7 @@ export const filtersBucketAgg = new BucketAggType({ matchAllLabel || (typeof filter.input.query === 'string' ? filter.input.query - : angular.toJson(filter.input.query)); + : toAngularJSON(filter.input.query)); filters[label] = { query }; }, {} diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_hash.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_hash.test.ts index f0ad5954764867..09dd03c759155e 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_hash.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_hash.test.ts @@ -19,12 +19,13 @@ import { geoHashBucketAgg } from './geo_hash'; import { AggConfigs, IAggConfigs } from '../agg_configs'; +import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; import { IBucketAggConfig } from './_bucket_agg_type'; -jest.mock('ui/new_platform'); - describe('Geohash Agg', () => { + // const typesRegistry = mockAggTypesRegistry([geoHashBucketAgg]); + const typesRegistry = mockAggTypesRegistry(); const getAggConfigs = (params?: Record) => { const indexPattern = { id: '1234', @@ -62,7 +63,7 @@ describe('Geohash Agg', () => { }, }, ], - null + { typesRegistry } ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_tile.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_tile.ts index 57e8f6e8c5ded4..9142a30338163c 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_tile.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_tile.ts @@ -19,7 +19,6 @@ import { i18n } from '@kbn/i18n'; import { noop } from 'lodash'; -import { AggConfigOptions } from '../agg_config'; import { BucketAggType } from './_bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; @@ -57,7 +56,7 @@ export const geoTileBucketAgg = new BucketAggType({ aggs.push(agg); if (useGeocentroid) { - const aggConfig: AggConfigOptions = { + const aggConfig = { type: METRIC_TYPES.GEO_CENTROID, enabled: true, params: { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.test.ts index 4e89d7db1ff647..11dc8e42fd6538 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.test.ts @@ -17,16 +17,23 @@ * under the License. */ -import { npStart } from 'ui/new_platform'; -import { AggConfigs } from '../index'; +import { AggConfigs } from '../agg_configs'; +import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; import { IBucketHistogramAggConfig, histogramBucketAgg, AutoBounds } from './histogram'; import { BucketAggType } from './_bucket_agg_type'; - -jest.mock('ui/new_platform'); +import { coreMock } from '../../../../../../../../src/core/public/mocks'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { setUiSettings } from '../../../../../../../plugins/data/public/services'; describe('Histogram Agg', () => { - const getAggConfigs = (params: Record = {}) => { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry([histogramBucketAgg]); + + const getAggConfigs = (params: Record) => { const indexPattern = { id: '1234', title: 'logstash-*', @@ -45,16 +52,13 @@ describe('Histogram Agg', () => { indexPattern, [ { - field: { - name: 'field', - }, id: 'test', type: BUCKET_TYPES.HISTOGRAM, schema: 'segment', params, }, ], - null + { typesRegistry } ); }; @@ -158,10 +162,15 @@ describe('Histogram Agg', () => { aggConfig.setAutoBounds(autoBounds); } - // mock histogram:maxBars value; - npStart.core.uiSettings.get = jest.fn(() => maxBars as any); + const core = coreMock.createStart(); + setUiSettings({ + ...core.uiSettings, + get: () => maxBars as any, + }); - return aggConfig.write(aggConfigs).params; + const interval = aggConfig.write(aggConfigs).params; + setUiSettings(core.uiSettings); // clean up + return interval; }; it('will respect the histogram:maxBars setting', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.ts index f7e9ef45961e04..70df2f230db094 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.ts @@ -19,13 +19,13 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; -import { toastNotifications } from 'ui/notify'; -import { npStart } from 'ui/new_platform'; import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type'; import { createFilterHistogram } from './create_filter/histogram'; -import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; import { BUCKET_TYPES } from './bucket_agg_types'; +import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getNotifications, getUiSettings } from '../../../../../../../plugins/data/public/services'; export interface AutoBounds { min: number; @@ -37,8 +37,6 @@ export interface IBucketHistogramAggConfig extends IBucketAggConfig { getAutoBounds: () => AutoBounds; } -const getUIConfig = () => npStart.core.uiSettings; - export const histogramBucketAgg = new BucketAggType({ name: BUCKET_TYPES.HISTOGRAM, title: i18n.translate('data.search.aggs.buckets.histogramTitle', { @@ -116,7 +114,7 @@ export const histogramBucketAgg = new BucketAggType({ }) .catch((e: Error) => { if (e.name === 'AbortError') return; - toastNotifications.addWarning( + getNotifications().toasts.addWarning( i18n.translate('data.search.aggs.histogram.missingMaxMinValuesWarning', { defaultMessage: 'Unable to retrieve max and min values to auto-scale histogram buckets. This may lead to poor visualization performance.', @@ -136,7 +134,7 @@ export const histogramBucketAgg = new BucketAggType({ const range = autoBounds.max - autoBounds.min; const bars = range / interval; - const config = getUIConfig(); + const config = getUiSettings(); if (bars > config.get('histogram:maxBars')) { const minInterval = range / config.get('histogram:maxBars'); diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/ip_range.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/ip_range.ts index 91bdf53e7f8091..3fb464d8fa7a8b 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/ip_range.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/ip_range.ts @@ -19,15 +19,17 @@ import { noop, map, omit, isNull } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; -import { IpRangeKey, convertIPRangeToString } from './lib/ip_range'; import { BucketAggType } from './_bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; -// @ts-ignore import { createFilterIpRange } from './create_filter/ip_range'; import { KBN_FIELD_TYPES, fieldFormats } from '../../../../../../../plugins/data/public'; -export { IpRangeKey, convertIPRangeToString }; + +import { IpRangeKey, convertIPRangeToString } from './lib/ip_range'; +export { IpRangeKey, convertIPRangeToString }; // for BWC + +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; const ipRangeTitle = i18n.translate('data.search.aggs.buckets.ipRangeTitle', { defaultMessage: 'IPv4 Range', @@ -44,7 +46,7 @@ export const ipRangeBucketAgg = new BucketAggType({ return { type: 'range', from: bucket.from, to: bucket.to }; }, getFormat(agg) { - const fieldFormatsService = npStart.plugins.data.fieldFormats; + const fieldFormatsService = getFieldFormats(); const formatter = agg.fieldOwnFormatter( fieldFormats.TEXT_CONTEXT_TYPE, fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.IP) diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts index 77e84e044de55a..d94477b588f8d1 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts @@ -19,10 +19,10 @@ import { isString, isObject } from 'lodash'; import { IBucketAggConfig, BucketAggType, BucketAggParam } from './_bucket_agg_type'; -import { AggConfig } from '../agg_config'; +import { IAggConfig } from '../agg_config'; export const isType = (type: string) => { - return (agg: AggConfig): boolean => { + return (agg: IAggConfig): boolean => { const field = agg.params.field; return field && field.type === type; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/range.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/range.test.ts index b1b0c4bc30a58e..096b19fe7de66d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/range.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/range.test.ts @@ -17,12 +17,12 @@ * under the License. */ +import { rangeBucketAgg } from './range'; import { AggConfigs } from '../agg_configs'; +import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; import { FieldFormatsGetConfigFn, fieldFormats } from '../../../../../../../plugins/data/public'; -jest.mock('ui/new_platform'); - const buckets = [ { to: 1024, @@ -44,6 +44,12 @@ const buckets = [ ]; describe('Range Agg', () => { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry([rangeBucketAgg]); + const getConfig = (() => {}) as FieldFormatsGetConfigFn; const getAggConfigs = () => { const field = { @@ -80,7 +86,7 @@ describe('Range Agg', () => { }, }, ], - null + { typesRegistry } ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/significant_terms.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/significant_terms.test.ts index 37b829bfc20fb2..cee3ed506c29c4 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/significant_terms.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/significant_terms.test.ts @@ -17,17 +17,16 @@ * under the License. */ -import { AggConfigs } from '../index'; -import { IAggConfigs } from '../types'; +import { AggConfigs, IAggConfigs } from '../agg_configs'; +import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; import { significantTermsBucketAgg } from './significant_terms'; import { IBucketAggConfig } from './_bucket_agg_type'; -jest.mock('ui/new_platform'); - describe('Significant Terms Agg', () => { describe('order agg editor UI', () => { describe('convert include/exclude from old format', () => { + const typesRegistry = mockAggTypesRegistry([significantTermsBucketAgg]); const getAggConfigs = (params: Record = {}) => { const indexPattern = { id: '1234', @@ -53,7 +52,7 @@ describe('Significant Terms Agg', () => { params, }, ], - null + { typesRegistry } ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/terms.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/terms.test.ts index 24ac332ae4d55c..9a4f28afd3edf2 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/terms.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/terms.test.ts @@ -17,13 +17,13 @@ * under the License. */ -import { AggConfigs } from '../index'; +import { AggConfigs } from '../agg_configs'; +import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; -jest.mock('ui/new_platform'); - describe('Terms Agg', () => { describe('order agg editor UI', () => { + const typesRegistry = mockAggTypesRegistry(); const getAggConfigs = (params: Record = {}) => { const indexPattern = { id: '1234', @@ -48,7 +48,7 @@ describe('Terms Agg', () => { type: BUCKET_TYPES.TERMS, }, ], - null + { typesRegistry } ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.test.ts b/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.test.ts index cc1288d339692f..0de1c31d02f961 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.test.ts @@ -19,13 +19,12 @@ import { IndexPattern } from '../../../../../../../plugins/data/public'; import { AggTypeFilters } from './agg_type_filters'; -import { AggConfig } from '..'; -import { IAggType } from '../types'; +import { IAggConfig, IAggType } from '../types'; describe('AggTypeFilters', () => { let registry: AggTypeFilters; const indexPattern = ({ id: '1234', fields: [], title: 'foo' } as unknown) as IndexPattern; - const aggConfig = {} as AggConfig; + const aggConfig = {} as IAggConfig; beforeEach(() => { registry = new AggTypeFilters(); diff --git a/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.ts b/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.ts index d3b38ce041d7ee..13a4cc0856b090 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.ts @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + import { IndexPattern } from 'src/plugins/data/public'; import { IAggConfig, IAggType } from '../types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/filter/prop_filter.test.ts b/src/legacy/core_plugins/data/public/search/aggs/filter/prop_filter.test.ts index 431e1161e0dbdf..32cda7b950e93d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/filter/prop_filter.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/filter/prop_filter.test.ts @@ -17,7 +17,6 @@ * under the License. */ -import expect from '@kbn/expect'; import { propFilter } from './prop_filter'; describe('prop filter', () => { @@ -47,48 +46,48 @@ describe('prop filter', () => { it('returns list when no filters are provided', () => { const objects = getObjects('table', 'table', 'pie'); - expect(nameFilter(objects)).to.eql(objects); + expect(nameFilter(objects)).toEqual(objects); }); it('returns list when empty list of filters is provided', () => { const objects = getObjects('table', 'table', 'pie'); - expect(nameFilter(objects, [])).to.eql(objects); + expect(nameFilter(objects, [])).toEqual(objects); }); it('should keep only the tables', () => { const objects = getObjects('table', 'table', 'pie'); - expect(nameFilter(objects, 'table')).to.eql(getObjects('table', 'table')); + expect(nameFilter(objects, 'table')).toEqual(getObjects('table', 'table')); }); it('should support comma-separated values', () => { const objects = getObjects('table', 'line', 'pie'); - expect(nameFilter(objects, 'table,line')).to.eql(getObjects('table', 'line')); + expect(nameFilter(objects, 'table,line')).toEqual(getObjects('table', 'line')); }); it('should support an array of values', () => { const objects = getObjects('table', 'line', 'pie'); - expect(nameFilter(objects, ['table', 'line'])).to.eql(getObjects('table', 'line')); + expect(nameFilter(objects, ['table', 'line'])).toEqual(getObjects('table', 'line')); }); it('should return all objects', () => { const objects = getObjects('table', 'line', 'pie'); - expect(nameFilter(objects, '*')).to.eql(objects); + expect(nameFilter(objects, '*')).toEqual(objects); }); it('should allow negation', () => { const objects = getObjects('table', 'line', 'pie'); - expect(nameFilter(objects, ['!line'])).to.eql(getObjects('table', 'pie')); + expect(nameFilter(objects, ['!line'])).toEqual(getObjects('table', 'pie')); }); it('should support a function for specifying what should be kept', () => { const objects = getObjects('table', 'line', 'pie'); const line = (value: string) => value === 'line'; - expect(nameFilter(objects, line)).to.eql(getObjects('line')); + expect(nameFilter(objects, line)).toEqual(getObjects('line')); }); it('gracefully handles a filter function with zero arity', () => { const objects = getObjects('table', 'line', 'pie'); const rejectEverything = () => false; - expect(nameFilter(objects, rejectEverything)).to.eql([]); + expect(nameFilter(objects, rejectEverything)).toEqual([]); }); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/index.test.ts b/src/legacy/core_plugins/data/public/search/aggs/index.test.ts index a867769a77fc1d..4d0cd55b09d533 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/index.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/index.test.ts @@ -25,8 +25,6 @@ import { isMetricAggType } from './metrics/metric_agg_type'; const bucketAggs = aggTypes.buckets; const metricAggs = aggTypes.metrics; -jest.mock('ui/new_platform'); - describe('AggTypesComponent', () => { describe('bucket aggs', () => { it('all extend BucketAggType', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/index.ts b/src/legacy/core_plugins/data/public/search/aggs/index.ts index 0bdb92b8de65e8..f6914c36f6c05c 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/index.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/index.ts @@ -17,8 +17,13 @@ * under the License. */ -export { aggTypes } from './agg_types'; +export { + AggTypesRegistry, + AggTypesRegistrySetup, + AggTypesRegistryStart, +} from './agg_types_registry'; export { AggType } from './agg_type'; +export { aggTypes } from './agg_types'; export { AggConfig } from './agg_config'; export { AggConfigs } from './agg_configs'; export { FieldParamType } from './param_types'; @@ -52,4 +57,4 @@ export { METRIC_TYPES } from './metrics/metric_agg_types'; export { ISchemas, Schema, Schemas } from './schemas'; // types -export { IAggConfig, IAggConfigs } from './types'; +export { CreateAggConfigParams, IAggConfig, IAggConfigs } from './types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_avg.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_avg.ts index 9fb28f8631bc63..11bb5592747297 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_avg.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_avg.ts @@ -19,7 +19,6 @@ import { i18n } from '@kbn/i18n'; import { get } from 'lodash'; - import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_max.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_max.ts index 83837f0de51146..0668a9bcf57a8f 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_max.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_max.ts @@ -18,7 +18,6 @@ */ import { i18n } from '@kbn/i18n'; - import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_min.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_min.ts index d96197693dc2ee..8f728cb5e7e426 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_min.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_min.ts @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/cardinality.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/cardinality.ts index 147e9255210887..4f7b6e555ca33e 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/cardinality.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/cardinality.ts @@ -18,10 +18,11 @@ */ import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; const uniqueCountTitle = i18n.translate('data.search.aggs.metrics.uniqueCountTitle', { defaultMessage: 'Unique Count', @@ -37,7 +38,7 @@ export const cardinalityMetricAgg = new MetricAggType({ }); }, getFormat() { - const fieldFormatsService = npStart.plugins.data.fieldFormats; + const fieldFormatsService = getFieldFormats(); return fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); }, diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/count.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/count.ts index 14a9bd073ff2bc..8b3e0a488c68a1 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/count.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/count.ts @@ -18,10 +18,11 @@ */ import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; -import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; +import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; export const countMetricAgg = new MetricAggType({ name: METRIC_TYPES.COUNT, @@ -35,7 +36,7 @@ export const countMetricAgg = new MetricAggType({ }); }, getFormat() { - const fieldFormatsService = npStart.plugins.data.fieldFormats; + const fieldFormatsService = getFieldFormats(); return fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); }, diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/get_response_agg_config_class.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/get_response_agg_config_class.ts index 054543de3dd067..00d866e6f2b3ed 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/get_response_agg_config_class.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/get_response_agg_config_class.ts @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + import { assign } from 'lodash'; import { IMetricAggConfig } from '../metric_agg_type'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts index e24aca08271c72..88549ee3019ee6 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts @@ -23,7 +23,6 @@ import { noop, identity } from 'lodash'; import { forwardModifyAggConfigOnSearchRequestStart } from './nested_agg_helpers'; import { IMetricAggConfig, MetricAggParam } from '../metric_agg_type'; import { parentPipelineAggWriter } from './parent_pipeline_agg_writer'; - import { Schemas } from '../../schemas'; import { fieldFormats } from '../../../../../../../../plugins/data/public'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts index e7c98e575fdb4f..05e009cc9da30e 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts @@ -21,7 +21,6 @@ import { identity } from 'lodash'; import { i18n } from '@kbn/i18n'; import { siblingPipelineAggWriter } from './sibling_pipeline_agg_writer'; import { forwardModifyAggConfigOnSearchRequestStart } from './nested_agg_helpers'; - import { IMetricAggConfig, MetricAggParam } from '../metric_agg_type'; import { Schemas } from '../../schemas'; import { fieldFormats } from '../../../../../../../../plugins/data/public'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/median.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/median.test.ts index 4755a873e69779..ad55837ec9a300 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/median.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/median.test.ts @@ -17,15 +17,16 @@ * under the License. */ +import { medianMetricAgg } from './median'; import { AggConfigs, IAggConfigs } from '../agg_configs'; +import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; -jest.mock('ui/new_platform'); - describe('AggTypeMetricMedianProvider class', () => { let aggConfigs: IAggConfigs; beforeEach(() => { + const typesRegistry = mockAggTypesRegistry([medianMetricAgg]); const field = { name: 'bytes', }; @@ -50,7 +51,7 @@ describe('AggTypeMetricMedianProvider class', () => { }, }, ], - null + { typesRegistry } ); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/median.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/median.ts index 53a5ffff418f10..68fc98261118c2 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/median.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/median.ts @@ -16,12 +16,10 @@ * specific language governing permissions and limitations * under the License. */ + import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; - -// @ts-ignore -import { percentilesMetricAgg } from './percentiles'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; const medianTitle = i18n.translate('data.search.aggs.metrics.medianTitle', { diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/metric_agg_type.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/metric_agg_type.ts index 3bae7b92618dcd..952dcc96de8330 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/metric_agg_type.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/metric_agg_type.ts @@ -18,13 +18,14 @@ */ import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; import { AggType, AggTypeConfig } from '../agg_type'; import { AggParamType } from '../param_types/agg'; import { AggConfig } from '../agg_config'; +import { FilterFieldTypes } from '../param_types/field'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; -import { FilterFieldTypes } from '../param_types/field'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; export interface IMetricAggConfig extends AggConfig { type: InstanceType; @@ -78,7 +79,7 @@ export class MetricAggType { - const fieldFormatsService = npStart.plugins.data.fieldFormats; + const fieldFormatsService = getFieldFormats(); const field = agg.getField(); return field ? field.format diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/min.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/min.ts index 48851051634356..1806c6d9d77107 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/min.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/min.ts @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts index 11fc39c20bdc42..58b4ee530a8c2d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts @@ -17,12 +17,12 @@ * under the License. */ -import sinon from 'sinon'; import { derivativeMetricAgg } from './derivative'; import { cumulativeSumMetricAgg } from './cumulative_sum'; import { movingAvgMetricAgg } from './moving_avg'; import { serialDiffMetricAgg } from './serial_diff'; import { AggConfigs } from '../agg_configs'; +import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; jest.mock('../schemas', () => { @@ -34,9 +34,13 @@ jest.mock('../schemas', () => { }; }); -jest.mock('ui/new_platform'); - describe('parent pipeline aggs', function() { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry(); + const metrics = [ { name: 'derivative', title: 'Derivative', provider: derivativeMetricAgg }, { name: 'cumulative_sum', title: 'Cumulative Sum', provider: cumulativeSumMetricAgg }, @@ -94,7 +98,7 @@ describe('parent pipeline aggs', function() { schema: 'metric', }, ], - null + { typesRegistry } ); // Grab the aggConfig off the vis (we don't actually use the vis for anything else) @@ -220,16 +224,16 @@ describe('parent pipeline aggs', function() { }); const searchSource: any = {}; - const customMetricSpy = sinon.spy(); + const customMetricSpy = jest.fn(); const customMetric = aggConfig.params.customMetric; // Attach a modifyAggConfigOnSearchRequestStart with a spy to the first parameter customMetric.type.params[0].modifyAggConfigOnSearchRequestStart = customMetricSpy; aggConfig.type.params.forEach(param => { - param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource); + param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource, {}); }); - expect(customMetricSpy.calledWith(customMetric, searchSource)).toBe(true); + expect(customMetricSpy.mock.calls[0]).toEqual([customMetric, searchSource, {}]); }); }); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts index 655e918ce07deb..628f1cd204ee5e 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts @@ -19,14 +19,16 @@ import { IPercentileRanksAggConfig, percentileRanksMetricAgg } from './percentile_ranks'; import { AggConfigs, IAggConfigs } from '../agg_configs'; +import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; -jest.mock('ui/new_platform'); - describe('AggTypesMetricsPercentileRanksProvider class', function() { let aggConfigs: IAggConfigs; beforeEach(() => { + mockDataServices(); + + const typesRegistry = mockAggTypesRegistry([percentileRanksMetricAgg]); const field = { name: 'bytes', }; @@ -58,7 +60,7 @@ describe('AggTypesMetricsPercentileRanksProvider class', function() { }, }, ], - null + { typesRegistry } ); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.ts index 38b47a7e97d2f2..1d640a9c1fa42f 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.ts @@ -18,20 +18,17 @@ */ import { i18n } from '@kbn/i18n'; -import { npStart } from 'ui/new_platform'; import { MetricAggType } from './metric_agg_type'; import { getResponseAggConfigClass, IResponseAggConfig } from './lib/get_response_agg_config_class'; - import { getPercentileValue } from './percentiles_get_value'; import { METRIC_TYPES } from './metric_agg_types'; import { fieldFormats, KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; // required by the values editor - export type IPercentileRanksAggConfig = IResponseAggConfig; -const getFieldFormats = () => npStart.plugins.data.fieldFormats; - const valueProps = { makeLabel(this: IPercentileRanksAggConfig) { const fieldFormatsService = getFieldFormats(); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.test.ts index dd1aaca973e473..e077bc0f8c7737 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.test.ts @@ -19,14 +19,14 @@ import { IPercentileAggConfig, percentilesMetricAgg } from './percentiles'; import { AggConfigs, IAggConfigs } from '../agg_configs'; +import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; -jest.mock('ui/new_platform'); - describe('AggTypesMetricsPercentilesProvider class', () => { let aggConfigs: IAggConfigs; beforeEach(() => { + const typesRegistry = mockAggTypesRegistry([percentilesMetricAgg]); const field = { name: 'bytes', }; @@ -58,7 +58,7 @@ describe('AggTypesMetricsPercentilesProvider class', () => { }, }, ], - null + { typesRegistry } ); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.ts index 39dc0d0f181e92..49e927d07d8dd0 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.ts @@ -18,15 +18,11 @@ */ import { i18n } from '@kbn/i18n'; - import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; - import { getResponseAggConfigClass, IResponseAggConfig } from './lib/get_response_agg_config_class'; import { getPercentileValue } from './percentiles_get_value'; - -// @ts-ignore import { ordinalSuffix } from './lib/ordinal_suffix'; export type IPercentileAggConfig = IResponseAggConfig; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts index d643cf0d2a4781..d3456bacceb6ab 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts @@ -17,7 +17,6 @@ * under the License. */ -import { spy } from 'sinon'; import { bucketSumMetricAgg } from './bucket_sum'; import { bucketAvgMetricAgg } from './bucket_avg'; import { bucketMinMetricAgg } from './bucket_min'; @@ -25,6 +24,7 @@ import { bucketMaxMetricAgg } from './bucket_max'; import { AggConfigs } from '../agg_configs'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; +import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; jest.mock('../schemas', () => { class MockedSchemas { @@ -35,9 +35,13 @@ jest.mock('../schemas', () => { }; }); -jest.mock('ui/new_platform'); - describe('sibling pipeline aggs', () => { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry(); + const metrics = [ { name: 'sum_bucket', title: 'Overall Sum', provider: bucketSumMetricAgg }, { name: 'avg_bucket', title: 'Overall Average', provider: bucketAvgMetricAgg }, @@ -96,7 +100,7 @@ describe('sibling pipeline aggs', () => { }, }, ], - null + { typesRegistry } ); // Grab the aggConfig off the vis (we don't actually use the vis for anything else) @@ -162,8 +166,8 @@ describe('sibling pipeline aggs', () => { init(); const searchSource: any = {}; - const customMetricSpy = spy(); - const customBucketSpy = spy(); + const customMetricSpy = jest.fn(); + const customBucketSpy = jest.fn(); const { customMetric, customBucket } = aggConfig.params; // Attach a modifyAggConfigOnSearchRequestStart with a spy to the first parameter @@ -171,11 +175,11 @@ describe('sibling pipeline aggs', () => { customBucket.type.params[0].modifyAggConfigOnSearchRequestStart = customBucketSpy; aggConfig.type.params.forEach(param => { - param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource); + param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource, {}); }); - expect(customMetricSpy.calledWith(customMetric, searchSource)).toBe(true); - expect(customBucketSpy.calledWith(customBucket, searchSource)).toBe(true); + expect(customMetricSpy.mock.calls[0]).toEqual([customMetric, searchSource, {}]); + expect(customBucketSpy.mock.calls[0]).toEqual([customBucket, searchSource, {}]); }); }); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/std_deviation.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/std_deviation.test.ts index 3125026a521854..0679831b1e6ac8 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/std_deviation.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/std_deviation.test.ts @@ -19,11 +19,11 @@ import { IStdDevAggConfig, stdDeviationMetricAgg } from './std_deviation'; import { AggConfigs } from '../agg_configs'; +import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; -jest.mock('ui/new_platform'); - describe('AggTypeMetricStandardDeviationProvider class', () => { + const typesRegistry = mockAggTypesRegistry([stdDeviationMetricAgg]); const getAggConfigs = (customLabel?: string) => { const field = { name: 'memory', @@ -52,7 +52,7 @@ describe('AggTypeMetricStandardDeviationProvider class', () => { }, }, ], - null + { typesRegistry } ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/top_hit.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/top_hit.test.ts index a973de4fe8659e..ad1f42f5c563e6 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/top_hit.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/top_hit.test.ts @@ -20,11 +20,10 @@ import { dropRight, last } from 'lodash'; import { topHitMetricAgg } from './top_hit'; import { AggConfigs } from '../agg_configs'; +import { mockAggTypesRegistry } from '../test_helpers'; import { IMetricAggConfig } from './metric_agg_type'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; -jest.mock('ui/new_platform'); - describe('Top hit metric', () => { let aggDsl: Record; let aggConfig: IMetricAggConfig; @@ -37,6 +36,7 @@ describe('Top hit metric', () => { fieldType = KBN_FIELD_TYPES.NUMBER, size = 1, }: any) => { + const typesRegistry = mockAggTypesRegistry([topHitMetricAgg]); const field = { name: fieldName, displayName: fieldName, @@ -81,7 +81,7 @@ describe('Top hit metric', () => { params, }, ], - null + { typesRegistry } ); // Grab the aggConfig off the vis (we don't actually use the vis for anything else) diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/agg.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/agg.ts index 2e7c11004b472e..d31abe64491d0d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/agg.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/agg.ts @@ -17,10 +17,10 @@ * under the License. */ -import { AggConfig } from '../agg_config'; +import { AggConfig, IAggConfig } from '../agg_config'; import { BaseParamType } from './base'; -export class AggParamType extends BaseParamType< +export class AggParamType extends BaseParamType< TAggConfig > { makeAgg: (agg: TAggConfig, state?: any) => TAggConfig; diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/base.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/base.ts index 1523cb03eb966c..95ad71a616ab27 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/base.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/base.ts @@ -18,10 +18,10 @@ */ import { IAggConfigs } from '../agg_configs'; -import { AggConfig } from '../agg_config'; +import { IAggConfig } from '../agg_config'; import { FetchOptions, ISearchSource } from '../../../../../../../plugins/data/public'; -export class BaseParamType { +export class BaseParamType { name: string; type: string; displayName: string; diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/field.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/field.test.ts index fa88754ac60b94..7338c41f920d72 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/field.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/field.test.ts @@ -25,8 +25,6 @@ import { IAggConfig } from '../agg_config'; import { IMetricAggConfig } from '../metrics/metric_agg_type'; import { Schema } from '../schemas'; -jest.mock('ui/new_platform'); - describe('Field', () => { const indexPattern = { id: '1234', diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/field.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/field.ts index 40c30f6210a833..bb5707cbb482ec 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/field.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/field.ts @@ -19,7 +19,6 @@ import { i18n } from '@kbn/i18n'; import { isFunction } from 'lodash'; -import { npStart } from 'ui/new_platform'; import { IAggConfig } from '../agg_config'; import { SavedObjectNotFound } from '../../../../../../../plugins/kibana_utils/public'; import { BaseParamType } from './base'; @@ -30,6 +29,8 @@ import { indexPatterns, KBN_FIELD_TYPES, } from '../../../../../../../plugins/data/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { getNotifications } from '../../../../../../../plugins/data/public/services'; const filterByType = propFilter('type'); @@ -93,7 +94,7 @@ export class FieldParamType extends BaseParamType { // @ts-ignore const validField = this.getAvailableFields(aggConfig).find((f: any) => f.name === fieldName); if (!validField) { - npStart.core.notifications.toasts.addDanger( + getNotifications().toasts.addDanger( i18n.translate( 'data.search.aggs.paramTypes.field.invalidSavedFieldParameterErrorMessage', { diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.test.ts index bc36bb46d3d166..1a453a225797db 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.test.ts @@ -17,27 +17,26 @@ * under the License. */ -import { IndexedArray } from 'ui/indexed_array'; import { AggTypeFieldFilters } from './field_filters'; -import { AggConfig } from '../../agg_config'; +import { IAggConfig } from '../../agg_config'; import { IndexPatternField } from '../../../../../../../../plugins/data/public'; describe('AggTypeFieldFilters', () => { let registry: AggTypeFieldFilters; - const aggConfig = {} as AggConfig; + const aggConfig = {} as IAggConfig; beforeEach(() => { registry = new AggTypeFieldFilters(); }); it('should filter nothing without registered filters', async () => { - const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexedArray; + const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexPatternField[]; const filtered = registry.filter(fields, aggConfig); expect(filtered).toEqual(fields); }); it('should pass all fields to the registered filter', async () => { - const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexedArray; + const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexPatternField[]; const filter = jest.fn(); registry.addFilter(filter); registry.filter(fields, aggConfig); @@ -46,7 +45,7 @@ describe('AggTypeFieldFilters', () => { }); it('should allow registered filters to filter out fields', async () => { - const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexedArray; + const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexPatternField[]; let filtered = registry.filter(fields, aggConfig); expect(filtered).toEqual(fields); diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.ts index 7d1348ab5423be..1cbf0c9ae36245 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.ts @@ -17,9 +17,9 @@ * under the License. */ import { IndexPatternField } from 'src/plugins/data/public'; -import { AggConfig } from '../../agg_config'; +import { IAggConfig } from '../../agg_config'; -type AggTypeFieldFilter = (field: IndexPatternField, aggConfig: AggConfig) => boolean; +type AggTypeFieldFilter = (field: IndexPatternField, aggConfig: IAggConfig) => boolean; /** * A registry to store {@link AggTypeFieldFilter} which are used to filter down @@ -41,11 +41,11 @@ class AggTypeFieldFilters { /** * Returns the {@link any|fields} filtered by all registered filters. * - * @param fields An IndexedArray of fields that will be filtered down by this registry. + * @param fields An array of fields that will be filtered down by this registry. * @param aggConfig The aggConfig for which the returning list will be used. * @return A filtered list of the passed fields. */ - public filter(fields: IndexPatternField[], aggConfig: AggConfig) { + public filter(fields: IndexPatternField[], aggConfig: IAggConfig) { const allFilters = Array.from(this.filters); const allowedAggTypeFields = fields.filter(field => { const isAggTypeFieldAllowed = allFilters.every(filter => filter(field, aggConfig)); diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/json.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/json.test.ts index 827299814c62aa..12fd29b3a14527 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/json.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/json.test.ts @@ -19,13 +19,11 @@ import { BaseParamType } from './base'; import { JsonParamType } from './json'; -import { AggConfig } from '../agg_config'; - -jest.mock('ui/new_platform'); +import { IAggConfig } from '../agg_config'; describe('JSON', function() { const paramName = 'json_test'; - let aggConfig: AggConfig; + let aggConfig: IAggConfig; let output: Record; const initAggParam = (config: Record = {}) => @@ -36,7 +34,7 @@ describe('JSON', function() { }); beforeEach(function() { - aggConfig = { params: {} } as AggConfig; + aggConfig = { params: {} } as IAggConfig; output = { params: {} }; }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/json.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/json.ts index 771919b0bb56b9..bf85b3b890c358 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/json.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/json.ts @@ -19,7 +19,7 @@ import _ from 'lodash'; -import { AggConfig } from '../agg_config'; +import { IAggConfig } from '../agg_config'; import { BaseParamType } from './base'; export class JsonParamType extends BaseParamType { @@ -29,7 +29,7 @@ export class JsonParamType extends BaseParamType { this.name = config.name || 'json'; if (!config.write) { - this.write = (aggConfig: AggConfig, output: Record) => { + this.write = (aggConfig: IAggConfig, output: Record) => { let paramJson; const param = aggConfig.params[this.name]; diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.test.ts index 6b58d81914097c..c03d6cdfa1c700 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.test.ts @@ -20,8 +20,6 @@ import { BaseParamType } from './base'; import { OptionedParamType } from './optioned'; -jest.mock('ui/new_platform'); - describe('Optioned', () => { describe('constructor', () => { it('it is an instance of BaseParamType', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.ts index 5ffda3740af49f..9eb7ceda607117 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.ts @@ -17,14 +17,14 @@ * under the License. */ -import { AggConfig } from '../agg_config'; +import { IAggConfig } from '../agg_config'; import { BaseParamType } from './base'; export interface OptionedValueProp { value: string; text: string; disabled?: boolean; - isCompatible: (agg: AggConfig) => boolean; + isCompatible: (agg: IAggConfig) => boolean; } export interface OptionedParamEditorProps { @@ -40,7 +40,7 @@ export class OptionedParamType extends BaseParamType { super(config); if (!config.write) { - this.write = (aggConfig: AggConfig, output: Record) => { + this.write = (aggConfig: IAggConfig, output: Record) => { output.params[this.name] = aggConfig.params[this.name].value; }; } diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/string.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/string.test.ts index fd5ccebde993eb..29ec9741611a37 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/string.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/string.test.ts @@ -19,13 +19,11 @@ import { BaseParamType } from './base'; import { StringParamType } from './string'; -import { AggConfig } from '../agg_config'; - -jest.mock('ui/new_platform'); +import { IAggConfig } from '../agg_config'; describe('String', function() { let paramName = 'json_test'; - let aggConfig: AggConfig; + let aggConfig: IAggConfig; let output: Record; const initAggParam = (config: Record = {}) => @@ -36,7 +34,7 @@ describe('String', function() { }); beforeEach(() => { - aggConfig = { params: {} } as AggConfig; + aggConfig = { params: {} } as IAggConfig; output = { params: {} }; }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/string.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/string.ts index 58ba99f8a6d636..750606eb8433bf 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/string.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/string.ts @@ -17,7 +17,7 @@ * under the License. */ -import { AggConfig } from '../agg_config'; +import { IAggConfig } from '../agg_config'; import { BaseParamType } from './base'; export class StringParamType extends BaseParamType { @@ -25,7 +25,7 @@ export class StringParamType extends BaseParamType { super(config); if (!config.write) { - this.write = (aggConfig: AggConfig, output: Record) => { + this.write = (aggConfig: IAggConfig, output: Record) => { if (aggConfig.params[this.name] && aggConfig.params[this.name].length) { output.params[this.name] = aggConfig.params[this.name]; } diff --git a/src/legacy/ui/public/vis/__tests__/index.js b/src/legacy/core_plugins/data/public/search/aggs/test_helpers/index.ts similarity index 86% rename from src/legacy/ui/public/vis/__tests__/index.js rename to src/legacy/core_plugins/data/public/search/aggs/test_helpers/index.ts index 46074f2c5197b7..131f921586144c 100644 --- a/src/legacy/ui/public/vis/__tests__/index.js +++ b/src/legacy/core_plugins/data/public/search/aggs/test_helpers/index.ts @@ -17,5 +17,5 @@ * under the License. */ -import './_agg_config'; -import './_agg_configs'; +export { mockAggTypesRegistry } from './mock_agg_types_registry'; +export { mockDataServices } from './mock_data_services'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts b/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts new file mode 100644 index 00000000000000..d6bb7938664932 --- /dev/null +++ b/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts @@ -0,0 +1,57 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { AggTypesRegistry, AggTypesRegistryStart } from '../agg_types_registry'; +import { aggTypes } from '../agg_types'; +import { BucketAggType } from '../buckets/_bucket_agg_type'; +import { MetricAggType } from '../metrics/metric_agg_type'; + +/** + * Testing utility which creates a new instance of AggTypesRegistry, + * registers the provided agg types, and returns AggTypesRegistry.start() + * + * This is useful if your test depends on a certain agg type to be present + * in the registry. + * + * @param [types] - Optional array of AggTypes to register. + * If no value is provided, all default types will be registered. + * + * @internal + */ +export function mockAggTypesRegistry | MetricAggType>( + types?: T[] +): AggTypesRegistryStart { + const registry = new AggTypesRegistry(); + const registrySetup = registry.setup(); + + if (types) { + types.forEach(type => { + if (type instanceof BucketAggType) { + registrySetup.registerBucket(type); + } else if (type instanceof MetricAggType) { + registrySetup.registerMetric(type); + } + }); + } else { + aggTypes.buckets.forEach(type => registrySetup.registerBucket(type)); + aggTypes.metrics.forEach(type => registrySetup.registerMetric(type)); + } + + return registry.start(); +} diff --git a/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_data_services.ts b/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_data_services.ts new file mode 100644 index 00000000000000..c4e78ab8f64226 --- /dev/null +++ b/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_data_services.ts @@ -0,0 +1,54 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { coreMock } from '../../../../../../../../src/core/public/mocks'; +import { dataPluginMock } from '../../../../../../../plugins/data/public/mocks'; +import { searchStartMock } from '../../mocks'; +import { setSearchServiceShim } from '../../../services'; +import { + setFieldFormats, + setIndexPatterns, + setNotifications, + setOverlays, + setQueryService, + setSearchService, + setUiSettings, + // eslint-disable-next-line @kbn/eslint/no-restricted-paths +} from '../../../../../../../plugins/data/public/services'; + +/** + * Testing helper which calls all of the service setters used in the + * data plugin. Services are added using their provided mocks. + * + * @internal + */ +export function mockDataServices() { + const core = coreMock.createStart(); + const data = dataPluginMock.createStartContract(); + const searchShim = searchStartMock(); + + setSearchServiceShim(searchShim); + setFieldFormats(data.fieldFormats); + setIndexPatterns(data.indexPatterns); + setNotifications(core.notifications); + setOverlays(core.overlays); + setQueryService(data.query); + setSearchService(data.search); + setUiSettings(core.uiSettings); +} diff --git a/src/legacy/core_plugins/data/public/search/aggs/types.ts b/src/legacy/core_plugins/data/public/search/aggs/types.ts index 2c918abf99fcaf..5d02f426b58967 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/types.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/types.ts @@ -18,7 +18,7 @@ */ export { IAggConfig } from './agg_config'; -export { IAggConfigs } from './agg_configs'; +export { CreateAggConfigParams, IAggConfigs } from './agg_configs'; export { IAggType } from './agg_type'; export { AggParam, AggParamOption } from './agg_params'; export { IFieldParamType } from './param_types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/utils.test.tsx b/src/legacy/core_plugins/data/public/search/aggs/utils.test.tsx index a3c7f24f3927d8..c0662c98755a3d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/utils.test.tsx +++ b/src/legacy/core_plugins/data/public/search/aggs/utils.test.tsx @@ -19,8 +19,6 @@ import { isValidJson } from './utils'; -jest.mock('ui/new_platform'); - const input = { valid: '{ "test": "json input" }', invalid: 'strings are not json', diff --git a/src/legacy/core_plugins/data/public/search/aggs/utils.ts b/src/legacy/core_plugins/data/public/search/aggs/utils.ts index 62f07ce44ab46e..67ea373f438fb8 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/utils.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/utils.ts @@ -26,7 +26,7 @@ import { isValidEsInterval } from '../../../common'; * @param {string} value a string that should be validated * @returns {boolean} true if value is a valid JSON or if value is an empty string, or a string with whitespaces, otherwise false */ -function isValidJson(value: string): boolean { +export function isValidJson(value: string): boolean { if (!value || value.length === 0) { return true; } @@ -49,7 +49,7 @@ function isValidJson(value: string): boolean { } } -function isValidInterval(value: string, baseInterval?: string) { +export function isValidInterval(value: string, baseInterval?: string) { if (baseInterval) { return _parseWithBase(value, baseInterval); } else { @@ -69,4 +69,37 @@ function _parseWithBase(value: string, baseInterval: string) { } } -export { isValidJson, isValidInterval }; +// An inlined version of angular.toJSON() +// source: https://github.com/angular/angular.js/blob/master/src/Angular.js#L1312 +// @internal +export function toAngularJSON(obj: any, pretty?: any): string { + if (obj === undefined) return ''; + if (typeof pretty === 'number') { + pretty = pretty ? 2 : null; + } + return JSON.stringify(obj, toJsonReplacer, pretty); +} + +function isWindow(obj: any) { + return obj && obj.window === obj; +} + +function isScope(obj: any) { + return obj && obj.$evalAsync && obj.$watch; +} + +function toJsonReplacer(key: any, value: any) { + let val = value; + + if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { + val = undefined; + } else if (isWindow(value)) { + val = '$WINDOW'; + } else if (value && window.document === value) { + val = '$DOCUMENT'; + } else if (isScope(value)) { + val = '$SCOPE'; + } + + return val; +} diff --git a/src/legacy/core_plugins/data/public/search/expressions/esaggs.ts b/src/legacy/core_plugins/data/public/search/expressions/esaggs.ts index 7a5d927d0f219a..24dd1c4944bfba 100644 --- a/src/legacy/core_plugins/data/public/search/expressions/esaggs.ts +++ b/src/legacy/core_plugins/data/public/search/expressions/esaggs.ts @@ -19,7 +19,7 @@ import { get, has } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { AggConfigs, IAggConfigs } from 'ui/agg_types'; +import { createAggConfigs, IAggConfigs } from 'ui/agg_types'; import { createFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; import { KibanaContext, @@ -258,7 +258,7 @@ export const esaggs = (): ExpressionFunctionDefinition { - const aggConfigs = new AggConfigs(indexPattern); + const { aggs } = getSearchServiceShim(); + const aggConfigs = aggs.createAggConfigs(indexPattern); const aggConfig = aggConfigs.createAggConfig({ enabled: true, type, diff --git a/src/legacy/core_plugins/data/public/search/mocks.ts b/src/legacy/core_plugins/data/public/search/mocks.ts new file mode 100644 index 00000000000000..86b6a928dc5b42 --- /dev/null +++ b/src/legacy/core_plugins/data/public/search/mocks.ts @@ -0,0 +1,85 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { SearchSetup, SearchStart } from './search_service'; +import { AggTypesRegistrySetup, AggTypesRegistryStart } from './aggs/agg_types_registry'; +import { AggConfigs } from './aggs/agg_configs'; +import { mockAggTypesRegistry } from './aggs/test_helpers'; + +const aggTypeBaseParamMock = () => ({ + name: 'some_param', + type: 'some_param_type', + displayName: 'some_agg_type_param', + required: false, + advanced: false, + default: {}, + write: jest.fn(), + serialize: jest.fn().mockImplementation(() => {}), + deserialize: jest.fn().mockImplementation(() => {}), + options: [], +}); + +const aggTypeConfigMock = () => ({ + name: 'some_name', + title: 'some_title', + params: [aggTypeBaseParamMock()], +}); + +export const aggTypesRegistrySetupMock = (): MockedKeys => ({ + registerBucket: jest.fn(), + registerMetric: jest.fn(), +}); + +export const aggTypesRegistryStartMock = (): MockedKeys => ({ + get: jest.fn().mockImplementation(aggTypeConfigMock), + getBuckets: jest.fn().mockImplementation(() => [aggTypeConfigMock()]), + getMetrics: jest.fn().mockImplementation(() => [aggTypeConfigMock()]), + getAll: jest.fn().mockImplementation(() => ({ + buckets: [aggTypeConfigMock()], + metrics: [aggTypeConfigMock()], + })), +}); + +export const searchSetupMock = (): MockedKeys => ({ + aggs: { + types: aggTypesRegistrySetupMock(), + }, +}); + +export const searchStartMock = (): MockedKeys => ({ + aggs: { + createAggConfigs: jest.fn().mockImplementation((indexPattern, configStates = [], schemas) => { + return new AggConfigs(indexPattern, configStates, { + schemas, + typesRegistry: mockAggTypesRegistry(), + }); + }), + types: mockAggTypesRegistry(), + __LEGACY: { + AggConfig: jest.fn() as any, + AggType: jest.fn(), + aggTypeFieldFilters: jest.fn() as any, + FieldParamType: jest.fn(), + MetricAggType: jest.fn(), + parentPipelineAggHelper: jest.fn() as any, + setBounds: jest.fn(), + siblingPipelineAggHelper: jest.fn() as any, + }, + }, +}); diff --git a/src/legacy/core_plugins/data/public/search/search_service.ts b/src/legacy/core_plugins/data/public/search/search_service.ts index 45f9ff17328adb..6754c0e3551af5 100644 --- a/src/legacy/core_plugins/data/public/search/search_service.ts +++ b/src/legacy/core_plugins/data/public/search/search_service.ts @@ -18,11 +18,16 @@ */ import { CoreSetup, CoreStart } from '../../../../../core/public'; +import { IndexPattern } from '../../../../../plugins/data/public'; import { aggTypes, AggType, + AggTypesRegistry, + AggTypesRegistrySetup, + AggTypesRegistryStart, AggConfig, AggConfigs, + CreateAggConfigParams, FieldParamType, MetricAggType, aggTypeFieldFilters, @@ -32,20 +37,28 @@ import { } from './aggs'; interface AggsSetup { - types: typeof aggTypes; + types: AggTypesRegistrySetup; } -interface AggsStart { - types: typeof aggTypes; +interface AggsStartLegacy { AggConfig: typeof AggConfig; - AggConfigs: typeof AggConfigs; AggType: typeof AggType; aggTypeFieldFilters: typeof aggTypeFieldFilters; FieldParamType: typeof FieldParamType; MetricAggType: typeof MetricAggType; parentPipelineAggHelper: typeof parentPipelineAggHelper; - siblingPipelineAggHelper: typeof siblingPipelineAggHelper; setBounds: typeof setBounds; + siblingPipelineAggHelper: typeof siblingPipelineAggHelper; +} + +interface AggsStart { + createAggConfigs: ( + indexPattern: IndexPattern, + configStates?: CreateAggConfigParams[], + schemas?: Record + ) => InstanceType; + types: AggTypesRegistryStart; + __LEGACY: AggsStartLegacy; } export interface SearchSetup { @@ -63,28 +76,41 @@ export interface SearchStart { * it will move into the existing search service in src/plugins/data/public/search */ export class SearchService { + private readonly aggTypesRegistry = new AggTypesRegistry(); + public setup(core: CoreSetup): SearchSetup { + const aggTypesSetup = this.aggTypesRegistry.setup(); + aggTypes.buckets.forEach(b => aggTypesSetup.registerBucket(b)); + aggTypes.metrics.forEach(m => aggTypesSetup.registerMetric(m)); + return { aggs: { - types: aggTypes, // TODO convert to registry - // TODO add other items as needed + types: aggTypesSetup, }, }; } public start(core: CoreStart): SearchStart { + const aggTypesStart = this.aggTypesRegistry.start(); return { aggs: { - types: aggTypes, // TODO convert to registry - AggConfig, // TODO make static - AggConfigs, - AggType, - aggTypeFieldFilters, - FieldParamType, - MetricAggType, - parentPipelineAggHelper, // TODO make static - siblingPipelineAggHelper, // TODO make static - setBounds, // TODO make static + createAggConfigs: (indexPattern, configStates = [], schemas) => { + return new AggConfigs(indexPattern, configStates, { + schemas, + typesRegistry: aggTypesStart, + }); + }, + types: aggTypesStart, + __LEGACY: { + AggConfig, // TODO make static + AggType, + aggTypeFieldFilters, + FieldParamType, + MetricAggType, + parentPipelineAggHelper, // TODO make static + setBounds, // TODO make static + siblingPipelineAggHelper, // TODO make static + }, }, }; } diff --git a/src/legacy/core_plugins/data/public/search/tabify/buckets.test.ts b/src/legacy/core_plugins/data/public/search/tabify/buckets.test.ts index ef2748102623ab..98048cb25db2fe 100644 --- a/src/legacy/core_plugins/data/public/search/tabify/buckets.test.ts +++ b/src/legacy/core_plugins/data/public/search/tabify/buckets.test.ts @@ -20,8 +20,6 @@ import { TabifyBuckets } from './buckets'; import { AggGroupNames } from '../aggs'; -jest.mock('ui/new_platform'); - describe('Buckets wrapper', () => { const check = (aggResp: any, count: number, keys: string[]) => { test('reads the length', () => { diff --git a/src/legacy/core_plugins/data/public/search/tabify/get_columns.test.ts b/src/legacy/core_plugins/data/public/search/tabify/get_columns.test.ts index cfd4cd7de640b2..6c5dc790ef9767 100644 --- a/src/legacy/core_plugins/data/public/search/tabify/get_columns.test.ts +++ b/src/legacy/core_plugins/data/public/search/tabify/get_columns.test.ts @@ -18,12 +18,17 @@ */ import { tabifyGetColumns } from './get_columns'; -import { AggConfigs, AggGroupNames, Schemas } from '../aggs'; import { TabbedAggColumn } from './types'; - -jest.mock('ui/new_platform'); +import { AggConfigs, AggGroupNames, Schemas } from '../aggs'; +import { mockAggTypesRegistry, mockDataServices } from '../aggs/test_helpers'; describe('get columns', () => { + beforeEach(() => { + mockDataServices(); + }); + + const typesRegistry = mockAggTypesRegistry(); + const createAggConfigs = (aggs: any[] = []) => { const field = { name: '@timestamp', @@ -38,18 +43,17 @@ describe('get columns', () => { }, } as any; - return new AggConfigs( - indexPattern, - aggs, - new Schemas([ + return new AggConfigs(indexPattern, aggs, { + typesRegistry, + schemas: new Schemas([ { group: AggGroupNames.Metrics, name: 'metric', min: 1, defaults: [{ schema: 'metric', type: 'count' }], }, - ]).all - ); + ]).all, + }); }; test('should inject a count metric if no aggs exist', () => { diff --git a/src/legacy/core_plugins/data/public/search/tabify/response_writer.test.ts b/src/legacy/core_plugins/data/public/search/tabify/response_writer.test.ts index f5df0a683ca00c..94301eedac74a7 100644 --- a/src/legacy/core_plugins/data/public/search/tabify/response_writer.test.ts +++ b/src/legacy/core_plugins/data/public/search/tabify/response_writer.test.ts @@ -19,14 +19,19 @@ import { TabbedAggResponseWriter } from './response_writer'; import { AggConfigs, AggGroupNames, Schemas, BUCKET_TYPES } from '../aggs'; +import { mockDataServices, mockAggTypesRegistry } from '../aggs/test_helpers'; import { TabbedResponseWriterOptions } from './types'; -jest.mock('ui/new_platform'); - describe('TabbedAggResponseWriter class', () => { + beforeEach(() => { + mockDataServices(); + }); + let responseWriter: TabbedAggResponseWriter; + const typesRegistry = mockAggTypesRegistry(); + const splitAggConfig = [ { type: BUCKET_TYPES.TERMS, @@ -66,18 +71,17 @@ describe('TabbedAggResponseWriter class', () => { } as any; return new TabbedAggResponseWriter( - new AggConfigs( - indexPattern, - aggs, - new Schemas([ + new AggConfigs(indexPattern, aggs, { + typesRegistry, + schemas: new Schemas([ { group: AggGroupNames.Metrics, name: 'metric', min: 1, defaults: [{ schema: 'metric', type: 'count' }], }, - ]).all - ), + ]).all, + }), { metricsAtAllLevels: false, partialRows: false, diff --git a/src/legacy/core_plugins/data/public/search/tabify/tabify.test.ts b/src/legacy/core_plugins/data/public/search/tabify/tabify.test.ts index 13fe7719b0a856..db4ad3bdea96bd 100644 --- a/src/legacy/core_plugins/data/public/search/tabify/tabify.test.ts +++ b/src/legacy/core_plugins/data/public/search/tabify/tabify.test.ts @@ -20,11 +20,12 @@ import { IndexPattern } from '../../../../../../plugins/data/public'; import { tabifyAggResponse } from './tabify'; import { IAggConfig, IAggConfigs, AggGroupNames, Schemas, AggConfigs } from '../aggs'; +import { mockAggTypesRegistry } from '../aggs/test_helpers'; import { metricOnly, threeTermBuckets } from 'fixtures/fake_hierarchical_data'; -jest.mock('ui/new_platform'); - describe('tabifyAggResponse Integration', () => { + const typesRegistry = mockAggTypesRegistry(); + const createAggConfigs = (aggs: IAggConfig[] = []) => { const field = { name: '@timestamp', @@ -39,18 +40,17 @@ describe('tabifyAggResponse Integration', () => { }, } as unknown) as IndexPattern; - return new AggConfigs( - indexPattern, - aggs, - new Schemas([ + return new AggConfigs(indexPattern, aggs, { + typesRegistry, + schemas: new Schemas([ { group: AggGroupNames.Metrics, name: 'metric', min: 1, defaults: [{ schema: 'metric', type: 'count' }], }, - ]).all - ); + ]).all, + }); }; const mockAggConfig = (agg: any): IAggConfig => (agg as unknown) as IAggConfig; diff --git a/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.mocks.ts b/src/legacy/core_plugins/data/public/services.ts similarity index 76% rename from src/legacy/core_plugins/data/public/actions/filters/brush_event.test.mocks.ts rename to src/legacy/core_plugins/data/public/services.ts index 2cecfd0fe8b767..7ecd041c70e22e 100644 --- a/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.mocks.ts +++ b/src/legacy/core_plugins/data/public/services.ts @@ -17,12 +17,9 @@ * under the License. */ -import { chromeServiceMock } from '../../../../../../core/public/mocks'; +import { createGetterSetter } from '../../../../plugins/kibana_utils/public'; +import { SearchStart } from './search/search_service'; -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +export const [getSearchServiceShim, setSearchServiceShim] = createGetterSetter( + 'searchShim' +); diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts index 6591aa5fb53d5f..6ae4e415f8caa8 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts @@ -20,7 +20,8 @@ import { cloneDeep } from 'lodash'; import { Vis, VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { AggConfigs, IAggConfig, AggGroupNames } from '../../../legacy_imports'; + +import { createAggConfigs, IAggConfig, AggGroupNames } from '../../../legacy_imports'; import { EditorStateActionTypes } from './constants'; import { getEnabledMetricAggsCount } from '../../agg_group_helper'; import { EditorAction } from './actions'; @@ -32,7 +33,8 @@ function initEditorState(vis: Vis) { function editorStateReducer(state: VisState, action: EditorAction): VisState { switch (action.type) { case EditorStateActionTypes.ADD_NEW_AGG: { - const aggConfig = state.aggs.createAggConfig(action.payload as IAggConfig, { + const payloadAggConfig = action.payload as IAggConfig; + const aggConfig = state.aggs.createAggConfig(payloadAggConfig, { addToAggConfigs: false, }); aggConfig.brandNew = true; @@ -40,7 +42,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -63,7 +65,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -88,7 +90,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -129,7 +131,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -141,7 +143,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -163,7 +165,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } diff --git a/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts b/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts index 832f73752a99b6..8aed263c4e4d1d 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts @@ -22,12 +22,12 @@ export { AggType, IAggType, IAggConfig, - AggConfigs, IAggConfigs, AggParam, AggGroupNames, aggGroupNamesMap, aggTypes, + createAggConfigs, FieldParamType, IFieldParamType, BUCKET_TYPES, diff --git a/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts b/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts index 0e1e48d00a1b27..736152c7014dc2 100644 --- a/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts +++ b/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts @@ -34,7 +34,7 @@ import { stubFields } from '../../../../plugins/data/public/stubs'; import { tableVisResponseHandler } from './table_vis_response_handler'; import { coreMock } from '../../../../core/public/mocks'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { AggConfigs } from 'ui/agg_types'; +import { createAggConfigs } from 'ui/agg_types'; import { tabifyAggResponse, IAggConfig } from './legacy_imports'; jest.mock('ui/new_platform'); @@ -113,7 +113,7 @@ describe('Table Vis - Controller', () => { return ({ type: tableVisTypeDefinition, params: Object.assign({}, tableVisTypeDefinition.visConfig.defaults, params), - aggs: new AggConfigs( + aggs: createAggConfigs( stubIndexPattern, [ { type: 'count', schema: 'metric' }, diff --git a/src/legacy/core_plugins/visualizations/public/legacy_imports.ts b/src/legacy/core_plugins/visualizations/public/legacy_imports.ts index fb7a157b53a9ac..0a3b1938436c0e 100644 --- a/src/legacy/core_plugins/visualizations/public/legacy_imports.ts +++ b/src/legacy/core_plugins/visualizations/public/legacy_imports.ts @@ -18,10 +18,10 @@ */ export { - AggConfigs, IAggConfig, IAggConfigs, isDateHistogramBucketAggConfig, setBounds, } from '../../data/public'; +export { createAggConfigs } from 'ui/agg_types'; export { createSavedSearchesLoader } from '../../../../plugins/discover/public'; diff --git a/src/legacy/core_plugins/visualizations/public/np_ready/public/vis_impl.js b/src/legacy/core_plugins/visualizations/public/np_ready/public/vis_impl.js index 2f36322c67256a..15a826cc6ddbe5 100644 --- a/src/legacy/core_plugins/visualizations/public/np_ready/public/vis_impl.js +++ b/src/legacy/core_plugins/visualizations/public/np_ready/public/vis_impl.js @@ -30,7 +30,7 @@ import { EventEmitter } from 'events'; import _ from 'lodash'; import { PersistedState } from '../../../../../../../src/plugins/visualizations/public'; -import { AggConfigs } from '../../legacy_imports'; +import { createAggConfigs } from '../../legacy_imports'; import { updateVisualizationConfig } from './legacy/vis_update'; import { getTypes } from './services'; @@ -83,7 +83,7 @@ class VisImpl extends EventEmitter { updateVisualizationConfig(state.params, this.params); if (state.aggs || !this.aggs) { - this.aggs = new AggConfigs( + this.aggs = createAggConfigs( this.indexPattern, state.aggs ? state.aggs.aggs || state.aggs : [], this.type.schemas.all @@ -125,7 +125,7 @@ class VisImpl extends EventEmitter { copyCurrentState(includeDisabled = false) { const state = this.getCurrentState(includeDisabled); - state.aggs = new AggConfigs( + state.aggs = createAggConfigs( this.indexPattern, state.aggs.aggs || state.aggs, this.type.schemas.all diff --git a/src/legacy/ui/public/agg_types/index.ts b/src/legacy/ui/public/agg_types/index.ts index ac5d0bed7ef153..ffc300251c4bb3 100644 --- a/src/legacy/ui/public/agg_types/index.ts +++ b/src/legacy/ui/public/agg_types/index.ts @@ -27,18 +27,19 @@ import { start as dataStart } from '../../../core_plugins/data/public/legacy'; // runtime contracts +const { types } = dataStart.search.aggs; +export const aggTypes = types.getAll(); +export const { createAggConfigs } = dataStart.search.aggs; export const { - types: aggTypes, AggConfig, - AggConfigs, AggType, aggTypeFieldFilters, FieldParamType, MetricAggType, parentPipelineAggHelper, - siblingPipelineAggHelper, setBounds, -} = dataStart.search.aggs; + siblingPipelineAggHelper, +} = dataStart.search.aggs.__LEGACY; // types export { diff --git a/src/legacy/ui/public/vis/__tests__/_agg_config.js b/src/legacy/ui/public/vis/__tests__/_agg_config.js deleted file mode 100644 index 9e53044f681baa..00000000000000 --- a/src/legacy/ui/public/vis/__tests__/_agg_config.js +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import sinon from 'sinon'; -import expect from '@kbn/expect'; -import ngMock from 'ng_mock'; -import { AggType, AggConfig } from '../../agg_types'; -import { start as visualizationsStart } from '../../../../core_plugins/visualizations/public/np_ready/public/legacy'; - -import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; - -describe('AggConfig', function() { - let indexPattern; - - beforeEach(ngMock.module('kibana')); - beforeEach( - ngMock.inject(function(Private) { - indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - }) - ); - - describe('#toDsl', function() { - it('calls #write()', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }); - - const aggConfig = vis.aggs.byName('date_histogram')[0]; - const stub = sinon.stub(aggConfig, 'write').returns({ params: {} }); - - aggConfig.toDsl(); - expect(stub.callCount).to.be(1); - }); - - it('uses the type name as the agg name', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }); - - const aggConfig = vis.aggs.byName('date_histogram')[0]; - sinon.stub(aggConfig, 'write').returns({ params: {} }); - - const dsl = aggConfig.toDsl(); - expect(dsl).to.have.property('date_histogram'); - }); - - it('uses the params from #write() output as the agg params', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }); - - const aggConfig = vis.aggs.byName('date_histogram')[0]; - const football = {}; - - sinon.stub(aggConfig, 'write').returns({ params: football }); - - const dsl = aggConfig.toDsl(); - expect(dsl.date_histogram).to.be(football); - }); - - it('includes subAggs from #write() output', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - type: 'avg', - schema: 'metric', - }, - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }); - - const histoConfig = vis.aggs.byName('date_histogram')[0]; - const avgConfig = vis.aggs.byName('avg')[0]; - const football = {}; - - sinon.stub(histoConfig, 'write').returns({ params: {}, subAggs: [avgConfig] }); - sinon.stub(avgConfig, 'write').returns({ params: football }); - - const dsl = histoConfig.toDsl(); - - // didn't use .eql() because of variable key names, and final check is strict - expect(dsl).to.have.property('aggs'); - expect(dsl.aggs).to.have.property(avgConfig.id); - expect(dsl.aggs[avgConfig.id]).to.have.property('avg'); - expect(dsl.aggs[avgConfig.id].avg).to.be(football); - }); - }); - - describe('::ensureIds', function() { - it('accepts an array of objects and assigns ids to them', function() { - const objs = [{}, {}, {}, {}]; - AggConfig.ensureIds(objs); - expect(objs[0]).to.have.property('id', '1'); - expect(objs[1]).to.have.property('id', '2'); - expect(objs[2]).to.have.property('id', '3'); - expect(objs[3]).to.have.property('id', '4'); - }); - - it('assigns ids relative to the other only item in the list', function() { - const objs = [{ id: '100' }, {}]; - AggConfig.ensureIds(objs); - expect(objs[0]).to.have.property('id', '100'); - expect(objs[1]).to.have.property('id', '101'); - }); - - it('assigns ids relative to the other items in the list', function() { - const objs = [{ id: '100' }, { id: '200' }, { id: '500' }, { id: '350' }, {}]; - AggConfig.ensureIds(objs); - expect(objs[0]).to.have.property('id', '100'); - expect(objs[1]).to.have.property('id', '200'); - expect(objs[2]).to.have.property('id', '500'); - expect(objs[3]).to.have.property('id', '350'); - expect(objs[4]).to.have.property('id', '501'); - }); - - it('uses ::nextId to get the starting value', function() { - sinon.stub(AggConfig, 'nextId').returns(534); - const objs = AggConfig.ensureIds([{}]); - AggConfig.nextId.restore(); - expect(objs[0]).to.have.property('id', '534'); - }); - - it('only calls ::nextId once', function() { - const start = 420; - sinon.stub(AggConfig, 'nextId').returns(start); - const objs = AggConfig.ensureIds([{}, {}, {}, {}, {}, {}, {}]); - - expect(AggConfig.nextId).to.have.property('callCount', 1); - - AggConfig.nextId.restore(); - objs.forEach(function(obj, i) { - expect(obj).to.have.property('id', String(start + i)); - }); - }); - }); - - describe('::nextId', function() { - it('accepts a list of objects and picks the next id', function() { - const next = AggConfig.nextId([{ id: 100 }, { id: 500 }]); - expect(next).to.be(501); - }); - - it('handles an empty list', function() { - const next = AggConfig.nextId([]); - expect(next).to.be(1); - }); - - it('fails when the list is not defined', function() { - expect(function() { - AggConfig.nextId(); - }).to.throwError(); - }); - }); - - describe('#toJsonDataEquals', function() { - const testsIdentical = [ - { - type: 'metric', - aggs: [ - { - type: 'count', - schema: 'metric', - params: { field: '@timestamp' }, - }, - ], - }, - { - type: 'histogram', - aggs: [ - { - type: 'avg', - schema: 'metric', - }, - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }, - ]; - - testsIdentical.forEach((visConfig, index) => { - it(`identical aggregations (${index})`, function() { - const vis1 = new visualizationsStart.Vis(indexPattern, visConfig); - const vis2 = new visualizationsStart.Vis(indexPattern, visConfig); - expect(vis1.aggs.jsonDataEquals(vis2.aggs.aggs)).to.be(true); - }); - }); - - const testsIdenticalDifferentOrder = [ - { - config1: { - type: 'histogram', - aggs: [ - { - type: 'avg', - schema: 'metric', - }, - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }, - config2: { - type: 'histogram', - aggs: [ - { - schema: 'metric', - type: 'avg', - }, - { - schema: 'segment', - type: 'date_histogram', - }, - ], - }, - }, - ]; - - testsIdenticalDifferentOrder.forEach((test, index) => { - it(`identical aggregations (${index}) - init json is in different order`, function() { - const vis1 = new visualizationsStart.Vis(indexPattern, test.config1); - const vis2 = new visualizationsStart.Vis(indexPattern, test.config2); - expect(vis1.aggs.jsonDataEquals(vis2.aggs.aggs)).to.be(true); - }); - }); - - const testsDifferent = [ - { - config1: { - type: 'histogram', - aggs: [ - { - type: 'avg', - schema: 'metric', - }, - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }, - config2: { - type: 'histogram', - aggs: [ - { - type: 'max', - schema: 'metric', - }, - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }, - }, - { - config1: { - type: 'metric', - aggs: [ - { - type: 'count', - schema: 'metric', - params: { field: '@timestamp' }, - }, - ], - }, - config2: { - type: 'metric', - aggs: [ - { - type: 'count', - schema: 'metric', - params: { field: '@timestamp' }, - }, - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }, - }, - ]; - - testsDifferent.forEach((test, index) => { - it(`different aggregations (${index})`, function() { - const vis1 = new visualizationsStart.Vis(indexPattern, test.config1); - const vis2 = new visualizationsStart.Vis(indexPattern, test.config2); - expect(vis1.aggs.jsonDataEquals(vis2.aggs.aggs)).to.be(false); - }); - }); - }); - - describe('#toJSON', function() { - it('includes the aggs id, params, type and schema', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }); - - const aggConfig = vis.aggs.byName('date_histogram')[0]; - expect(aggConfig.id).to.be('1'); - expect(aggConfig.params).to.be.an('object'); - expect(aggConfig.type) - .to.be.an(AggType) - .and.have.property('name', 'date_histogram'); - expect(aggConfig.schema) - .to.be.an('object') - .and.have.property('name', 'segment'); - - const state = aggConfig.toJSON(); - expect(state).to.have.property('id', '1'); - expect(state.params).to.be.an('object'); - expect(state).to.have.property('type', 'date_histogram'); - expect(state).to.have.property('schema', 'segment'); - }); - - it('test serialization order is identical (for visual consistency)', function() { - const vis1 = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - type: 'date_histogram', - schema: 'segment', - }, - ], - }); - const vis2 = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - schema: 'segment', - type: 'date_histogram', - }, - ], - }); - - //this relies on the assumption that js-engines consistently loop over properties in insertion order. - //most likely the case, but strictly speaking not guaranteed by the JS and JSON specifications. - expect(JSON.stringify(vis1.aggs.aggs) === JSON.stringify(vis2.aggs.aggs)).to.be(true); - }); - }); - - describe('#makeLabel', function() { - it('uses the custom label if it is defined', function() { - const vis = new visualizationsStart.Vis(indexPattern, {}); - const aggConfig = vis.aggs.aggs[0]; - aggConfig.params.customLabel = 'Custom label'; - const label = aggConfig.makeLabel(); - expect(label).to.be(aggConfig.params.customLabel); - }); - it('default label should be "Count"', function() { - const vis = new visualizationsStart.Vis(indexPattern, {}); - const aggConfig = vis.aggs.aggs[0]; - const label = aggConfig.makeLabel(); - expect(label).to.be('Count'); - }); - it('default label should be "Percentage of Count" when percentageMode is set to true', function() { - const vis = new visualizationsStart.Vis(indexPattern, {}); - const aggConfig = vis.aggs.aggs[0]; - const label = aggConfig.makeLabel(true); - expect(label).to.be('Percentage of Count'); - }); - it('empty label if the visualizationsStart.Vis type is not defined', function() { - const vis = new visualizationsStart.Vis(indexPattern, {}); - const aggConfig = vis.aggs.aggs[0]; - aggConfig.type = undefined; - const label = aggConfig.makeLabel(); - expect(label).to.be(''); - }); - }); - - describe('#fieldFormatter - custom getFormat handler', function() { - it('returns formatter from getFormat handler', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'metric', - aggs: [ - { - type: 'count', - schema: 'metric', - params: { field: '@timestamp' }, - }, - ], - }); - - const fieldFormatter = vis.aggs.aggs[0].fieldFormatter(); - - expect(fieldFormatter).to.be.defined; - expect(fieldFormatter('text')).to.be('text'); - }); - }); - - describe('#fieldFormatter - no custom getFormat handler', function() { - const visStateAggWithoutCustomGetFormat = { - aggs: [ - { - type: 'histogram', - schema: 'bucket', - params: { field: 'bytes' }, - }, - ], - }; - let vis; - - beforeEach(function() { - vis = new visualizationsStart.Vis(indexPattern, visStateAggWithoutCustomGetFormat); - }); - - it("returns the field's formatter", function() { - expect(vis.aggs.aggs[0].fieldFormatter().toString()).to.be( - vis.aggs.aggs[0] - .getField() - .format.getConverterFor() - .toString() - ); - }); - - it('returns the string format if the field does not have a format', function() { - const agg = vis.aggs.aggs[0]; - agg.params.field = { type: 'number', format: null }; - const fieldFormatter = agg.fieldFormatter(); - expect(fieldFormatter).to.be.defined; - expect(fieldFormatter('text')).to.be('text'); - }); - - it('returns the string format if their is no field', function() { - const agg = vis.aggs.aggs[0]; - delete agg.params.field; - const fieldFormatter = agg.fieldFormatter(); - expect(fieldFormatter).to.be.defined; - expect(fieldFormatter('text')).to.be('text'); - }); - - it('returns the html converter if "html" is passed in', function() { - const field = indexPattern.fields.getByName('bytes'); - expect(vis.aggs.aggs[0].fieldFormatter('html').toString()).to.be( - field.format.getConverterFor('html').toString() - ); - }); - }); -}); diff --git a/src/legacy/ui/public/vis/__tests__/_agg_configs.js b/src/legacy/ui/public/vis/__tests__/_agg_configs.js deleted file mode 100644 index 172523ec50c8b0..00000000000000 --- a/src/legacy/ui/public/vis/__tests__/_agg_configs.js +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import _ from 'lodash'; -import sinon from 'sinon'; -import expect from '@kbn/expect'; -import ngMock from 'ng_mock'; -import { AggConfig, AggConfigs, AggGroupNames, Schemas } from '../../agg_types'; -import { start as visualizationsStart } from '../../../../core_plugins/visualizations/public/np_ready/public/legacy'; -import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; - -describe('AggConfigs', function() { - let indexPattern; - - beforeEach(ngMock.module('kibana')); - beforeEach( - ngMock.inject(function(Private) { - // load main deps - indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); - }) - ); - - describe('constructor', function() { - it('handles passing just a vis', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [], - }); - - const ac = new AggConfigs(vis.indexPattern, [], vis.type.schemas.all); - expect(ac.aggs).to.have.length(1); - }); - - it('converts configStates into AggConfig objects if they are not already', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [], - }); - - const ac = new AggConfigs( - vis.indexPattern, - [ - { - type: 'date_histogram', - schema: 'segment', - }, - new AggConfig(vis.aggs, { - type: 'terms', - schema: 'split', - }), - ], - vis.type.schemas.all - ); - - expect(ac.aggs).to.have.length(3); - }); - - it('attempts to ensure that all states have an id', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [], - }); - - const states = [ - { - type: 'date_histogram', - schema: 'segment', - }, - { - type: 'terms', - schema: 'split', - }, - ]; - - const spy = sinon.spy(AggConfig, 'ensureIds'); - new AggConfigs(vis.indexPattern, states, vis.type.schemas.all); - expect(spy.callCount).to.be(1); - expect(spy.firstCall.args[0]).to.be(states); - AggConfig.ensureIds.restore(); - }); - - describe('defaults', function() { - let vis; - beforeEach(function() { - vis = { - indexPattern: indexPattern, - type: { - schemas: new Schemas([ - { - group: AggGroupNames.Metrics, - name: 'metric', - title: 'Simple', - min: 1, - max: 2, - defaults: [ - { schema: 'metric', type: 'count' }, - { schema: 'metric', type: 'avg' }, - { schema: 'metric', type: 'sum' }, - ], - }, - { - group: AggGroupNames.Buckets, - name: 'segment', - title: 'Example', - min: 0, - max: 1, - defaults: [ - { schema: 'segment', type: 'terms' }, - { schema: 'segment', type: 'filters' }, - ], - }, - ]), - }, - }; - }); - - it('should only set the number of defaults defined by the max', function() { - const ac = new AggConfigs(vis.indexPattern, [], vis.type.schemas.all); - expect(ac.bySchemaName('metric')).to.have.length(2); - }); - - it('should set the defaults defined in the schema when none exist', function() { - const ac = new AggConfigs(vis.indexPattern, [], vis.type.schemas.all); - expect(ac.aggs).to.have.length(3); - }); - - it('should NOT set the defaults defined in the schema when some exist', function() { - const ac = new AggConfigs( - vis.indexPattern, - [{ schema: 'segment', type: 'date_histogram' }], - vis.type.schemas.all - ); - expect(ac.aggs).to.have.length(3); - expect(ac.bySchemaName('segment')[0].type.name).to.equal('date_histogram'); - }); - }); - }); - - describe('#getRequestAggs', function() { - it('performs a stable sort, but moves metrics to the bottom', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { type: 'avg', schema: 'metric' }, - { type: 'terms', schema: 'split' }, - { type: 'histogram', schema: 'split' }, - { type: 'sum', schema: 'metric' }, - { type: 'date_histogram', schema: 'segment' }, - { type: 'filters', schema: 'split' }, - { type: 'percentiles', schema: 'metric' }, - ], - }); - - const sorted = vis.aggs.getRequestAggs(); - const aggs = _.indexBy(vis.aggs.aggs, function(agg) { - return agg.type.name; - }); - - expect(sorted.shift()).to.be(aggs.terms); - expect(sorted.shift()).to.be(aggs.histogram); - expect(sorted.shift()).to.be(aggs.date_histogram); - expect(sorted.shift()).to.be(aggs.filters); - expect(sorted.shift()).to.be(aggs.avg); - expect(sorted.shift()).to.be(aggs.sum); - expect(sorted.shift()).to.be(aggs.percentiles); - expect(sorted).to.have.length(0); - }); - }); - - describe('#getResponseAggs', function() { - it('returns all request aggs for basic aggs', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { type: 'terms', schema: 'split' }, - { type: 'date_histogram', schema: 'segment' }, - { type: 'count', schema: 'metric' }, - ], - }); - - const sorted = vis.aggs.getResponseAggs(); - const aggs = _.indexBy(vis.aggs.aggs, function(agg) { - return agg.type.name; - }); - - expect(sorted.shift()).to.be(aggs.terms); - expect(sorted.shift()).to.be(aggs.date_histogram); - expect(sorted.shift()).to.be(aggs.count); - expect(sorted).to.have.length(0); - }); - - it('expands aggs that have multiple responses', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { type: 'terms', schema: 'split' }, - { type: 'date_histogram', schema: 'segment' }, - { type: 'percentiles', schema: 'metric', params: { percents: [1, 2, 3] } }, - ], - }); - - const sorted = vis.aggs.getResponseAggs(); - const aggs = _.indexBy(vis.aggs.aggs, function(agg) { - return agg.type.name; - }); - - expect(sorted.shift()).to.be(aggs.terms); - expect(sorted.shift()).to.be(aggs.date_histogram); - expect(sorted.shift().id).to.be(aggs.percentiles.id + '.' + 1); - expect(sorted.shift().id).to.be(aggs.percentiles.id + '.' + 2); - expect(sorted.shift().id).to.be(aggs.percentiles.id + '.' + 3); - expect(sorted).to.have.length(0); - }); - }); - - describe('#toDsl', function() { - it('uses the sorted aggs', function() { - const vis = new visualizationsStart.Vis(indexPattern, { type: 'histogram' }); - sinon.spy(vis.aggs, 'getRequestAggs'); - vis.aggs.toDsl(); - expect(vis.aggs.getRequestAggs).to.have.property('callCount', 1); - }); - - it('calls aggConfig#toDsl() on each aggConfig and compiles the nested output', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { type: 'date_histogram', schema: 'segment' }, - { type: 'filters', schema: 'split' }, - ], - }); - - const aggInfos = vis.aggs.aggs.map(function(aggConfig) { - const football = {}; - - sinon.stub(aggConfig, 'toDsl').returns(football); - - return { - id: aggConfig.id, - football: football, - }; - }); - - (function recurse(lvl) { - const info = aggInfos.shift(); - - expect(lvl).to.have.property(info.id); - expect(lvl[info.id]).to.be(info.football); - - if (lvl[info.id].aggs) { - return recurse(lvl[info.id].aggs); - } - })(vis.aggs.toDsl()); - - expect(aggInfos).to.have.length(1); - }); - - it("skips aggs that don't have a dsl representation", function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - type: 'date_histogram', - schema: 'segment', - params: { field: '@timestamp', interval: '10s' }, - }, - { type: 'count', schema: 'metric' }, - ], - }); - - const dsl = vis.aggs.toDsl(); - const histo = vis.aggs.byName('date_histogram')[0]; - const count = vis.aggs.byName('count')[0]; - - expect(dsl).to.have.property(histo.id); - expect(dsl[histo.id]).to.be.an('object'); - expect(dsl[histo.id]).to.not.have.property('aggs'); - expect(dsl).to.not.have.property(count.id); - }); - - it('writes multiple metric aggregations at the same level', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - type: 'date_histogram', - schema: 'segment', - params: { field: '@timestamp', interval: '10s' }, - }, - { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, - { type: 'sum', schema: 'metric', params: { field: 'bytes' } }, - { type: 'min', schema: 'metric', params: { field: 'bytes' } }, - { type: 'max', schema: 'metric', params: { field: 'bytes' } }, - ], - }); - - const dsl = vis.aggs.toDsl(); - - const histo = vis.aggs.byName('date_histogram')[0]; - const metrics = vis.aggs.bySchemaGroup('metrics'); - - expect(dsl).to.have.property(histo.id); - expect(dsl[histo.id]).to.be.an('object'); - expect(dsl[histo.id]).to.have.property('aggs'); - - metrics.forEach(function(metric) { - expect(dsl[histo.id].aggs).to.have.property(metric.id); - expect(dsl[histo.id].aggs[metric.id]).to.not.have.property('aggs'); - }); - }); - - it('writes multiple metric aggregations at every level if the vis is hierarchical', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { type: 'terms', schema: 'segment', params: { field: 'ip', orderBy: 1 } }, - { type: 'terms', schema: 'segment', params: { field: 'extension', orderBy: 1 } }, - { id: 1, type: 'avg', schema: 'metric', params: { field: 'bytes' } }, - { type: 'sum', schema: 'metric', params: { field: 'bytes' } }, - { type: 'min', schema: 'metric', params: { field: 'bytes' } }, - { type: 'max', schema: 'metric', params: { field: 'bytes' } }, - ], - }); - vis.isHierarchical = _.constant(true); - - const topLevelDsl = vis.aggs.toDsl(vis.isHierarchical()); - const buckets = vis.aggs.bySchemaGroup('buckets'); - const metrics = vis.aggs.bySchemaGroup('metrics'); - - (function checkLevel(dsl) { - const bucket = buckets.shift(); - expect(dsl).to.have.property(bucket.id); - - expect(dsl[bucket.id]).to.be.an('object'); - expect(dsl[bucket.id]).to.have.property('aggs'); - - metrics.forEach(function(metric) { - expect(dsl[bucket.id].aggs).to.have.property(metric.id); - expect(dsl[bucket.id].aggs[metric.id]).to.not.have.property('aggs'); - }); - - if (buckets.length) { - checkLevel(dsl[bucket.id].aggs); - } - })(topLevelDsl); - }); - - it('adds the parent aggs of nested metrics at every level if the vis is hierarchical', function() { - const vis = new visualizationsStart.Vis(indexPattern, { - type: 'histogram', - aggs: [ - { - id: '1', - type: 'avg_bucket', - schema: 'metric', - params: { - customBucket: { - id: '1-bucket', - type: 'date_histogram', - schema: 'bucketAgg', - params: { - field: '@timestamp', - interval: '10s', - }, - }, - customMetric: { - id: '1-metric', - type: 'count', - schema: 'metricAgg', - params: {}, - }, - }, - }, - { - id: '2', - type: 'terms', - schema: 'bucket', - params: { - field: 'geo.src', - }, - }, - { - id: '3', - type: 'terms', - schema: 'bucket', - params: { - field: 'machine.os', - }, - }, - ], - }); - vis.isHierarchical = _.constant(true); - - const topLevelDsl = vis.aggs.toDsl(vis.isHierarchical())['2']; - expect(topLevelDsl.aggs).to.have.keys(['1', '1-bucket']); - expect(topLevelDsl.aggs['1'].avg_bucket).to.have.property('buckets_path', '1-bucket>_count'); - expect(topLevelDsl.aggs['3'].aggs).to.have.keys(['1', '1-bucket']); - expect(topLevelDsl.aggs['3'].aggs['1'].avg_bucket).to.have.property( - 'buckets_path', - '1-bucket>_count' - ); - }); - }); -}); diff --git a/src/plugins/data/common/field_formats/mocks.ts b/src/plugins/data/common/field_formats/mocks.ts new file mode 100644 index 00000000000000..bc38374e147cf6 --- /dev/null +++ b/src/plugins/data/common/field_formats/mocks.ts @@ -0,0 +1,49 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { FieldFormat, IFieldFormatsRegistry } from '.'; + +const fieldFormatMock = ({ + convert: jest.fn(), + getConverterFor: jest.fn(), + getParamDefaults: jest.fn(), + param: jest.fn(), + params: jest.fn(), + toJSON: jest.fn(), + type: jest.fn(), + setupContentType: jest.fn(), +} as unknown) as FieldFormat; + +export const fieldFormatsMock: IFieldFormatsRegistry = { + getByFieldType: jest.fn(), + getDefaultConfig: jest.fn(), + getDefaultInstance: jest.fn().mockImplementation(() => fieldFormatMock) as any, + getDefaultInstanceCacheResolver: jest.fn(), + getDefaultInstancePlain: jest.fn(), + getDefaultType: jest.fn(), + getDefaultTypeName: jest.fn(), + getInstance: jest.fn() as any, + getType: jest.fn(), + getTypeNameByEsTypes: jest.fn(), + init: jest.fn(), + register: jest.fn(), + parseDefaultTypeMap: jest.fn(), + deserialize: jest.fn(), + getTypeWithoutMetaParams: jest.fn(), +}; diff --git a/src/plugins/data/public/mocks.ts b/src/plugins/data/public/mocks.ts index 6a0a33096eaac1..27de3b5a29bfd0 100644 --- a/src/plugins/data/public/mocks.ts +++ b/src/plugins/data/public/mocks.ts @@ -16,13 +16,9 @@ * specific language governing permissions and limitations * under the License. */ -import { - Plugin, - DataPublicPluginSetup, - DataPublicPluginStart, - IndexPatternsContract, - IFieldFormatsRegistry, -} from '.'; + +import { Plugin, DataPublicPluginSetup, DataPublicPluginStart, IndexPatternsContract } from '.'; +import { fieldFormatsMock } from '../common/field_formats/mocks'; import { searchSetupMock } from './search/mocks'; import { queryServiceMock } from './query/mocks'; @@ -35,24 +31,6 @@ const autocompleteMock: any = { hasQuerySuggestions: jest.fn(), }; -const fieldFormatsMock: IFieldFormatsRegistry = { - getByFieldType: jest.fn(), - getDefaultConfig: jest.fn(), - getDefaultInstance: jest.fn() as any, - getDefaultInstanceCacheResolver: jest.fn(), - getDefaultInstancePlain: jest.fn(), - getDefaultType: jest.fn(), - getDefaultTypeName: jest.fn(), - getInstance: jest.fn() as any, - getType: jest.fn(), - getTypeNameByEsTypes: jest.fn(), - init: jest.fn(), - register: jest.fn(), - parseDefaultTypeMap: jest.fn(), - deserialize: jest.fn(), - getTypeWithoutMetaParams: jest.fn(), -}; - const createSetupContract = (): Setup => { const querySetupMock = queryServiceMock.createSetupContract(); const setupContract = { diff --git a/src/plugins/data/public/search/search_source/mocks.ts b/src/plugins/data/public/search/search_source/mocks.ts index fd72158012de6f..700bea741bd6ae 100644 --- a/src/plugins/data/public/search/search_source/mocks.ts +++ b/src/plugins/data/public/search/search_source/mocks.ts @@ -17,25 +17,6 @@ * under the License. */ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"), you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - import { ISearchSource } from './search_source'; export const searchSourceMock: MockedKeys = { diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_service/service.test.tsx b/x-pack/legacy/plugins/lens/public/editor_frame_service/service.test.tsx index ef4b5f6d7b834f..2e1645c816140c 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_service/service.test.tsx +++ b/x-pack/legacy/plugins/lens/public/editor_frame_service/service.test.tsx @@ -17,10 +17,6 @@ jest.mock('ui/new_platform'); // mock away actual dependencies to prevent all of it being loaded jest.mock('../../../../../../src/legacy/core_plugins/interpreter/public/registries', () => {}); -jest.mock('../../../../../../src/legacy/core_plugins/data/public/legacy', () => ({ - start: {}, - setup: {}, -})); jest.mock('./embeddable/embeddable_factory', () => ({ EmbeddableFactory: class Mock {}, })); diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/zeek/__snapshots__/zeek_details.test.tsx.snap b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/zeek/__snapshots__/zeek_details.test.tsx.snap index c883983f8cf010..da04b970a494b8 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/zeek/__snapshots__/zeek_details.test.tsx.snap +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/zeek/__snapshots__/zeek_details.test.tsx.snap @@ -2803,7 +2803,7 @@ tr:hover .c3:focus::before {
- - - -
- - -
- - - - + - - -
- - - - - - + - + title="Cu0n232QMyvNtzb75j" + > - - Cu0n232QMyvNtzb75j - - + + - - - - - + viewBox="0 0 16 16" + width={16} + xmlns="http://www.w3.org/2000/svg" + /> + + - - - - - - - -
-
-
-
-
-
-
- -
-
-
-
-
-
-
+ + + + + + + + +
+ + + + + + + + + + + + + @@ -3105,7 +3087,7 @@ tr:hover .c3:focus::before {
- - - -
- - -
- - - - + - - -
- - - - - - + - + title="files" + > - - files - - + + - - - - - + viewBox="0 0 16 16" + width={16} + xmlns="http://www.w3.org/2000/svg" + /> + + - - - - - - - -
-
-
-
-
-
-
- -
-
-
-
-
-
-
+ + + + + + + + +
+ + + + + + + + + + + + + @@ -3407,7 +3371,7 @@ tr:hover .c3:focus::before {
- - - -
- - -
- - - - + - - -
- - - - - - + - + title="sha1: fa5195a..." + > - - sha1: fa5195a... - - + + - - - - - + viewBox="0 0 16 16" + width={16} + xmlns="http://www.w3.org/2000/svg" + /> + + - - - - - - - -
-
-
-
-
-
-
- -
-
-
-
-
-
-
+ + + + + + + + +
+ + + + + + + + + + + + + @@ -3709,7 +3655,7 @@ tr:hover .c3:focus::before {
- - - -
- - -
- - - - + - - -
- - - - - - + - + title="md5: f7653f1..." + > - - md5: f7653f1... - - + + - - - - - + viewBox="0 0 16 16" + width={16} + xmlns="http://www.w3.org/2000/svg" + /> + + - - - - - - - -
-
-
-
-
-
-
- -
-
-
-
-
-
-
+ + + + + + + + +
+ + + + + + + + + + + + + From b6dfcc7ad790cd85dd0071124dc23203281f3f87 Mon Sep 17 00:00:00 2001 From: igoristic Date: Thu, 27 Feb 2020 21:46:45 -0500 Subject: [PATCH 3/9] Removed unused indices (#57903) Co-authored-by: Elastic Machine --- .../plugins/monitoring/common/constants.ts | 23 +++++-------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/x-pack/legacy/plugins/monitoring/common/constants.ts b/x-pack/legacy/plugins/monitoring/common/constants.ts index 1fb6acdb915b88..9a4030f3eb2147 100644 --- a/x-pack/legacy/plugins/monitoring/common/constants.ts +++ b/x-pack/legacy/plugins/monitoring/common/constants.ts @@ -141,23 +141,12 @@ export const CLUSTER_ALERTS_ADDRESS_CONFIG_KEY = 'cluster_alerts.email_notificat export const STANDALONE_CLUSTER_CLUSTER_UUID = '__standalone_cluster__'; -const INDEX_PATTERN_NEW = ',monitoring-*-7-*,monitoring-*-8-*'; -const INDEX_PATTERN_KIBANA_NEW = ',monitoring-kibana-7-*,monitoring-kibana-8-*'; -const INDEX_PATTERN_LOGSTASH_NEW = ',monitoring-logstash-7-*,monitoring-logstash-8-*'; -const INDEX_PATTERN_BEATS_NEW = ',monitoring-beats-7-*,monitoring-beats-8-*'; -const INDEX_ALERTS_NEW = ',monitoring-alerts-7,monitoring-alerts-8'; -const INDEX_PATTERN_ELASTICSEARCH_NEW = ',monitoring-es-7-*,monitoring-es-8-*'; - -export const INDEX_PATTERN = '.monitoring-*-6-*,.monitoring-*-7-*' + INDEX_PATTERN_NEW; -export const INDEX_PATTERN_KIBANA = - '.monitoring-kibana-6-*,.monitoring-kibana-7-*' + INDEX_PATTERN_KIBANA_NEW; -export const INDEX_PATTERN_LOGSTASH = - '.monitoring-logstash-6-*,.monitoring-logstash-7-*' + INDEX_PATTERN_LOGSTASH_NEW; -export const INDEX_PATTERN_BEATS = - '.monitoring-beats-6-*,.monitoring-beats-7-*' + INDEX_PATTERN_BEATS_NEW; -export const INDEX_ALERTS = '.monitoring-alerts-6,.monitoring-alerts-7' + INDEX_ALERTS_NEW; -export const INDEX_PATTERN_ELASTICSEARCH = - '.monitoring-es-6-*,.monitoring-es-7-*' + INDEX_PATTERN_ELASTICSEARCH_NEW; +export const INDEX_PATTERN = '.monitoring-*-6-*,.monitoring-*-7-*'; +export const INDEX_PATTERN_KIBANA = '.monitoring-kibana-6-*,.monitoring-kibana-7-*'; +export const INDEX_PATTERN_LOGSTASH = '.monitoring-logstash-6-*,.monitoring-logstash-7-*'; +export const INDEX_PATTERN_BEATS = '.monitoring-beats-6-*,.monitoring-beats-7-*'; +export const INDEX_ALERTS = '.monitoring-alerts-6,.monitoring-alerts-7'; +export const INDEX_PATTERN_ELASTICSEARCH = '.monitoring-es-6-*,.monitoring-es-7-*'; // This is the unique token that exists in monitoring indices collected by metricbeat export const METRICBEAT_INDEX_NAME_UNIQUE_TOKEN = '-mb-'; From 4fd3b45b44fb213c3c1251d3ccbcb471a434caf9 Mon Sep 17 00:00:00 2001 From: Spencer Date: Thu, 27 Feb 2020 20:22:42 -0700 Subject: [PATCH 4/9] fix some missing awaits in functional tests (#58807) --- test/functional/apps/context/_filters.js | 2 +- test/functional/apps/dashboard/panel_expand_toggle.js | 2 +- test/functional/apps/visualize/_tsvb_markdown.ts | 4 ++-- x-pack/test/functional/page_objects/uptime_page.ts | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/functional/apps/context/_filters.js b/test/functional/apps/context/_filters.js index c9499f5a805ab3..721f8a50d0e464 100644 --- a/test/functional/apps/context/_filters.js +++ b/test/functional/apps/context/_filters.js @@ -64,7 +64,7 @@ export default function({ getService, getPageObjects }) { await filterBar.toggleFilterEnabled(TEST_ANCHOR_FILTER_FIELD); await PageObjects.context.waitUntilContextLoadingHasFinished(); - retry.try(async () => { + await retry.try(async () => { expect( await filterBar.hasFilter(TEST_ANCHOR_FILTER_FIELD, TEST_ANCHOR_FILTER_VALUE, false) ).to.be(true); diff --git a/test/functional/apps/dashboard/panel_expand_toggle.js b/test/functional/apps/dashboard/panel_expand_toggle.js index 930445a67aa203..5e7d55706968de 100644 --- a/test/functional/apps/dashboard/panel_expand_toggle.js +++ b/test/functional/apps/dashboard/panel_expand_toggle.js @@ -56,7 +56,7 @@ export default function({ getService, getPageObjects }) { // Add a retry to fix https://github.com/elastic/kibana/issues/14574. Perhaps the recent changes to this // being a CSS update is causing the UI to change slower than grabbing the panels? - retry.try(async () => { + await retry.try(async () => { const panelCountAfterMaxThenMinimize = await PageObjects.dashboard.getPanelCount(); expect(panelCountAfterMaxThenMinimize).to.be(panelCount); }); diff --git a/test/functional/apps/visualize/_tsvb_markdown.ts b/test/functional/apps/visualize/_tsvb_markdown.ts index b7307ac9c6cabc..d37404a3d60cb2 100644 --- a/test/functional/apps/visualize/_tsvb_markdown.ts +++ b/test/functional/apps/visualize/_tsvb_markdown.ts @@ -121,7 +121,7 @@ export default function({ getPageObjects, getService }: FtrProviderContext) { await visualBuilder.markdownSwitchSubTab('data'); await visualBuilder.cloneSeries(); - retry.try(async function seriesCountCheck() { + await retry.try(async function seriesCountCheck() { const seriesLength = (await visualBuilder.getSeries()).length; expect(seriesLength).to.be.equal(2); }); @@ -131,7 +131,7 @@ export default function({ getPageObjects, getService }: FtrProviderContext) { await visualBuilder.markdownSwitchSubTab('data'); await visualBuilder.createNewAgg(); - retry.try(async function aggregationCountCheck() { + await retry.try(async function aggregationCountCheck() { const aggregationLength = await visualBuilder.getAggregationCount(); expect(aggregationLength).to.be.equal(2); }); diff --git a/x-pack/test/functional/page_objects/uptime_page.ts b/x-pack/test/functional/page_objects/uptime_page.ts index a5bd4cc4802873..f6e93cd14e4971 100644 --- a/x-pack/test/functional/page_objects/uptime_page.ts +++ b/x-pack/test/functional/page_objects/uptime_page.ts @@ -57,7 +57,7 @@ export function UptimePageProvider({ getPageObjects, getService }: FtrProviderCo } public async pageUrlContains(value: string, expected: boolean = true) { - retry.try(async () => { + await retry.try(async () => { expect(await uptimeService.urlContains(value)).to.eql(expected); }); } From 015c7abbca81887d6d2d18c3dc44613d8f9c4c71 Mon Sep 17 00:00:00 2001 From: Nathan Reese Date: Thu, 27 Feb 2020 21:49:33 -0700 Subject: [PATCH 5/9] [Maps] remove getMetricFields from AbstractESSource (#58667) * [Maps] remove getMetricFields from AbstractESSource * do not use formaters for count and unique count * fix jest test --- .../maps/public/layers/fields/es_agg_field.js | 21 +++++++--- .../maps/public/layers/fields/field.js | 8 ++++ .../public/layers/sources/es_agg_source.js | 17 ++++++-- .../maps/public/layers/sources/es_source.js | 42 ++++--------------- .../public/layers/sources/es_term_source.js | 22 ++++------ .../layers/sources/es_term_source.test.js | 2 +- .../maps/public/layers/sources/source.js | 4 +- .../properties/dynamic_color_property.test.js | 3 ++ .../properties/dynamic_style_property.js | 20 +++------ .../tooltips/es_aggmetric_tooltip_property.js | 4 +- .../maps/public/layers/vector_layer.js | 11 +++-- 11 files changed, 72 insertions(+), 82 deletions(-) diff --git a/x-pack/legacy/plugins/maps/public/layers/fields/es_agg_field.js b/x-pack/legacy/plugins/maps/public/layers/fields/es_agg_field.js index 28c199b64d3ef4..27ab8fc5bfb3ae 100644 --- a/x-pack/legacy/plugins/maps/public/layers/fields/es_agg_field.js +++ b/x-pack/legacy/plugins/maps/public/layers/fields/es_agg_field.js @@ -21,13 +21,17 @@ export class ESAggMetricField extends AbstractField { } getName() { - return this._source.formatMetricKey(this.getAggType(), this.getESDocFieldName()); + return this._source.getAggKey(this.getAggType(), this.getRootName()); + } + + getRootName() { + return this._getESDocFieldName(); } async getLabel() { return this._label - ? await this._label - : this._source.formatMetricLabel(this.getAggType(), this.getESDocFieldName()); + ? this._label + : this._source.getAggLabel(this.getAggType(), this.getRootName()); } getAggType() { @@ -42,13 +46,13 @@ export class ESAggMetricField extends AbstractField { return this.getAggType() === AGG_TYPE.TERMS ? 'string' : 'number'; } - getESDocFieldName() { + _getESDocFieldName() { return this._esDocField ? this._esDocField.getName() : ''; } getRequestDescription() { return this.getAggType() !== AGG_TYPE.COUNT - ? `${this.getAggType()} ${this.getESDocFieldName()}` + ? `${this.getAggType()} ${this.getRootName()}` : AGG_TYPE.COUNT; } @@ -64,7 +68,7 @@ export class ESAggMetricField extends AbstractField { } getValueAggDsl(indexPattern) { - const field = getField(indexPattern, this.getESDocFieldName()); + const field = getField(indexPattern, this.getRootName()); const aggType = this.getAggType(); const aggBody = aggType === AGG_TYPE.TERMS ? { size: 1, shard_size: 1 } : {}; return { @@ -77,6 +81,11 @@ export class ESAggMetricField extends AbstractField { return !isMetricCountable(this.getAggType()); } + canValueBeFormatted() { + // Do not use field formatters for counting metrics + return ![AGG_TYPE.COUNT, AGG_TYPE.UNIQUE_COUNT].includes(this.getAggType()); + } + async getOrdinalFieldMetaRequest(config) { return this._esDocField.getOrdinalFieldMetaRequest(config); } diff --git a/x-pack/legacy/plugins/maps/public/layers/fields/field.js b/x-pack/legacy/plugins/maps/public/layers/fields/field.js index b5d157ad1697aa..2dd553f66755fc 100644 --- a/x-pack/legacy/plugins/maps/public/layers/fields/field.js +++ b/x-pack/legacy/plugins/maps/public/layers/fields/field.js @@ -17,6 +17,14 @@ export class AbstractField { return this._fieldName; } + getRootName() { + return this.getName(); + } + + canValueBeFormatted() { + return true; + } + getSource() { return this._source; } diff --git a/x-pack/legacy/plugins/maps/public/layers/sources/es_agg_source.js b/x-pack/legacy/plugins/maps/public/layers/sources/es_agg_source.js index bee35216f59dab..775535d9e2299c 100644 --- a/x-pack/legacy/plugins/maps/public/layers/sources/es_agg_source.js +++ b/x-pack/legacy/plugins/maps/public/layers/sources/es_agg_source.js @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { i18n } from '@kbn/i18n'; import { AbstractESSource } from './es_source'; import { ESAggMetricField } from '../fields/es_agg_field'; import { ESDocField } from '../fields/es_doc_field'; @@ -72,12 +73,22 @@ export class AbstractESAggSource extends AbstractESSource { return metrics; } - formatMetricKey(aggType, fieldName) { + getAggKey(aggType, fieldName) { return aggType !== AGG_TYPE.COUNT ? `${aggType}${AGG_DELIMITER}${fieldName}` : COUNT_PROP_NAME; } - formatMetricLabel(aggType, fieldName) { - return aggType !== AGG_TYPE.COUNT ? `${aggType} of ${fieldName}` : COUNT_PROP_LABEL; + getAggLabel(aggType, fieldName) { + switch (aggType) { + case AGG_TYPE.COUNT: + return COUNT_PROP_LABEL; + case AGG_TYPE.TERMS: + return i18n.translate('xpack.maps.source.esAggSource.topTermLabel', { + defaultMessage: `Top {fieldName}`, + values: { fieldName }, + }); + default: + return `${aggType} ${fieldName}`; + } } getValueAggsDsl(indexPattern) { diff --git a/x-pack/legacy/plugins/maps/public/layers/sources/es_source.js b/x-pack/legacy/plugins/maps/public/layers/sources/es_source.js index 5074b218dd615a..f575fd05c80613 100644 --- a/x-pack/legacy/plugins/maps/public/layers/sources/es_source.js +++ b/x-pack/legacy/plugins/maps/public/layers/sources/es_source.js @@ -17,7 +17,7 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; import uuid from 'uuid/v4'; import { copyPersistentState } from '../../reducers/util'; -import { ES_GEO_FIELD_TYPE, AGG_TYPE } from '../../../common/constants'; +import { ES_GEO_FIELD_TYPE } from '../../../common/constants'; import { DataRequestAbortError } from '../util/data_request'; import { expandToTileBoundaries } from './es_geo_grid_source/geo_tile_utils'; @@ -72,10 +72,6 @@ export class AbstractESSource extends AbstractVectorSource { return clonedDescriptor; } - getMetricFields() { - return []; - } - async _runEsQuery({ requestId, requestName, @@ -254,23 +250,7 @@ export class AbstractESSource extends AbstractVectorSource { return this._descriptor.id; } - async getFieldFormatter(fieldName) { - const metricField = this.getMetricFields().find(field => field.getName() === fieldName); - - // Do not use field formatters for counting metrics - if ( - metricField && - (metricField.type === AGG_TYPE.COUNT || metricField.type === AGG_TYPE.UNIQUE_COUNT) - ) { - return null; - } - - // fieldName could be an aggregation so it needs to be unpacked to expose raw field. - const realFieldName = metricField ? metricField.getESDocFieldName() : fieldName; - if (!realFieldName) { - return null; - } - + async createFieldFormatter(field) { let indexPattern; try { indexPattern = await this.getIndexPattern(); @@ -278,7 +258,7 @@ export class AbstractESSource extends AbstractVectorSource { return null; } - const fieldFromIndexPattern = indexPattern.fields.getByName(realFieldName); + const fieldFromIndexPattern = indexPattern.fields.getByName(field.getRootName()); if (!fieldFromIndexPattern) { return null; } @@ -336,25 +316,19 @@ export class AbstractESSource extends AbstractVectorSource { return resp.aggregations; } - getValueSuggestions = async (fieldName, query) => { - // fieldName could be an aggregation so it needs to be unpacked to expose raw field. - const metricField = this.getMetricFields().find(field => field.getName() === fieldName); - const realFieldName = metricField ? metricField.getESDocFieldName() : fieldName; - if (!realFieldName) { - return []; - } - + getValueSuggestions = async (field, query) => { try { const indexPattern = await this.getIndexPattern(); - const field = indexPattern.fields.getByName(realFieldName); return await autocompleteService.getValueSuggestions({ indexPattern, - field, + field: indexPattern.fields.getByName(field.getRootName()), query, }); } catch (error) { console.warn( - `Unable to fetch suggestions for field: ${fieldName}, query: ${query}, error: ${error.message}` + `Unable to fetch suggestions for field: ${field.getRootName()}, query: ${query}, error: ${ + error.message + }` ); return []; } diff --git a/x-pack/legacy/plugins/maps/public/layers/sources/es_term_source.js b/x-pack/legacy/plugins/maps/public/layers/sources/es_term_source.js index 9cc2919404a940..30f60f543d38df 100644 --- a/x-pack/legacy/plugins/maps/public/layers/sources/es_term_source.js +++ b/x-pack/legacy/plugins/maps/public/layers/sources/es_term_source.js @@ -67,7 +67,7 @@ export class ESTermSource extends AbstractESAggSource { return this._descriptor.whereQuery; } - formatMetricKey(aggType, fieldName) { + getAggKey(aggType, fieldName) { const metricKey = aggType !== AGG_TYPE.COUNT ? `${aggType}${AGG_DELIMITER}${fieldName}` : aggType; return `${FIELD_NAME_PREFIX}${metricKey}${GROUP_BY_DELIMITER}${ @@ -75,21 +75,13 @@ export class ESTermSource extends AbstractESAggSource { }.${this._termField.getName()}`; } - formatMetricLabel(type, fieldName) { - switch (type) { - case AGG_TYPE.COUNT: - return i18n.translate('xpack.maps.source.esJoin.countLabel', { + getAggLabel(aggType, fieldName) { + return aggType === AGG_TYPE.COUNT + ? i18n.translate('xpack.maps.source.esJoin.countLabel', { defaultMessage: `Count of {indexPatternTitle}`, values: { indexPatternTitle: this._descriptor.indexPatternTitle }, - }); - case AGG_TYPE.TERMS: - return i18n.translate('xpack.maps.source.esJoin.topTermLabel', { - defaultMessage: `Top {fieldName}`, - values: { fieldName }, - }); - default: - return `${type} ${fieldName}`; - } + }) + : super.getAggLabel(aggType, fieldName); } async getPropertiesMap(searchFilters, leftSourceName, leftFieldName, registerCancelCallback) { @@ -116,7 +108,7 @@ export class ESTermSource extends AbstractESAggSource { requestDescription: this._getRequestDescription(leftSourceName, leftFieldName), }); - const countPropertyName = this.formatMetricKey(AGG_TYPE.COUNT); + const countPropertyName = this.getAggKey(AGG_TYPE.COUNT); return { propertiesMap: extractPropertiesMap(rawEsData, countPropertyName), }; diff --git a/x-pack/legacy/plugins/maps/public/layers/sources/es_term_source.test.js b/x-pack/legacy/plugins/maps/public/layers/sources/es_term_source.test.js index 39cc301d458cbe..d6f9f6d2911e91 100644 --- a/x-pack/legacy/plugins/maps/public/layers/sources/es_term_source.test.js +++ b/x-pack/legacy/plugins/maps/public/layers/sources/es_term_source.test.js @@ -54,7 +54,7 @@ describe('getMetricFields', () => { expect(metrics.length).toBe(2); expect(metrics[0].getAggType()).toEqual('sum'); - expect(metrics[0].getESDocFieldName()).toEqual(sumFieldName); + expect(metrics[0].getRootName()).toEqual(sumFieldName); expect(metrics[0].getName()).toEqual( '__kbnjoin__sum_of_myFieldGettingSummed_groupby_myIndex.myTermField' ); diff --git a/x-pack/legacy/plugins/maps/public/layers/sources/source.js b/x-pack/legacy/plugins/maps/public/layers/sources/source.js index 3c6ddb74bedeba..4fef52e731f9b2 100644 --- a/x-pack/legacy/plugins/maps/public/layers/sources/source.js +++ b/x-pack/legacy/plugins/maps/public/layers/sources/source.js @@ -132,7 +132,7 @@ export class AbstractSource { } // Returns function used to format value - async getFieldFormatter(/* fieldName */) { + async createFieldFormatter(/* field */) { return null; } @@ -140,7 +140,7 @@ export class AbstractSource { throw new Error(`Source#loadStylePropsMeta not implemented`); } - async getValueSuggestions(/* fieldName, query */) { + async getValueSuggestions(/* field, query */) { return []; } } diff --git a/x-pack/legacy/plugins/maps/public/layers/styles/vector/properties/dynamic_color_property.test.js b/x-pack/legacy/plugins/maps/public/layers/styles/vector/properties/dynamic_color_property.test.js index 6b08fc2a105c3a..8648b073a7b79a 100644 --- a/x-pack/legacy/plugins/maps/public/layers/styles/vector/properties/dynamic_color_property.test.js +++ b/x-pack/legacy/plugins/maps/public/layers/styles/vector/properties/dynamic_color_property.test.js @@ -25,6 +25,9 @@ const mockField = { getName() { return 'foobar'; }, + getRootName() { + return 'foobar'; + }, supportsFieldMeta() { return true; }, diff --git a/x-pack/legacy/plugins/maps/public/layers/styles/vector/properties/dynamic_style_property.js b/x-pack/legacy/plugins/maps/public/layers/styles/vector/properties/dynamic_style_property.js index af78c4c0e461e8..e40c82e6276c7e 100644 --- a/x-pack/legacy/plugins/maps/public/layers/styles/vector/properties/dynamic_style_property.js +++ b/x-pack/legacy/plugins/maps/public/layers/styles/vector/properties/dynamic_style_property.js @@ -13,7 +13,6 @@ import React from 'react'; import { OrdinalLegend } from './components/ordinal_legend'; import { CategoricalLegend } from './components/categorical_legend'; import { OrdinalFieldMetaOptionsPopover } from '../components/ordinal_field_meta_options_popover'; -import { ESAggMetricField } from '../../../fields/es_agg_field'; export class DynamicStyleProperty extends AbstractStyleProperty { static type = STYLE_TYPE.DYNAMIC; @@ -26,9 +25,9 @@ export class DynamicStyleProperty extends AbstractStyleProperty { } getValueSuggestions = query => { - const fieldName = this.getFieldName(); + const field = this.getField(); const fieldSource = this.getFieldSource(); - return fieldSource && fieldName ? fieldSource.getValueSuggestions(fieldName, query) : []; + return fieldSource && field ? fieldSource.getValueSuggestions(field, query) : []; }; getFieldMeta() { @@ -185,11 +184,7 @@ export class DynamicStyleProperty extends AbstractStyleProperty { } _pluckOrdinalStyleMetaFromFieldMetaData(fieldMetaData) { - const realFieldName = - this._field instanceof ESAggMetricField - ? this._field.getESDocFieldName() - : this._field.getName(); - const stats = fieldMetaData[realFieldName]; + const stats = fieldMetaData[this._field.getRootName()]; if (!stats) { return null; } @@ -209,15 +204,12 @@ export class DynamicStyleProperty extends AbstractStyleProperty { } _pluckCategoricalStyleMetaFromFieldMetaData(fieldMetaData) { - const realFieldName = - this._field instanceof ESAggMetricField - ? this._field.getESDocFieldName() - : this._field.getName(); - if (!fieldMetaData[realFieldName] || !fieldMetaData[realFieldName].buckets) { + const rootFieldName = this._field.getRootName(); + if (!fieldMetaData[rootFieldName] || !fieldMetaData[rootFieldName].buckets) { return null; } - const ordered = fieldMetaData[realFieldName].buckets.map(bucket => { + const ordered = fieldMetaData[rootFieldName].buckets.map(bucket => { return { key: bucket.key, count: bucket.doc_count, diff --git a/x-pack/legacy/plugins/maps/public/layers/tooltips/es_aggmetric_tooltip_property.js b/x-pack/legacy/plugins/maps/public/layers/tooltips/es_aggmetric_tooltip_property.js index 229c84fe234bd9..ea000a78331eb7 100644 --- a/x-pack/legacy/plugins/maps/public/layers/tooltips/es_aggmetric_tooltip_property.js +++ b/x-pack/legacy/plugins/maps/public/layers/tooltips/es_aggmetric_tooltip_property.js @@ -27,9 +27,7 @@ export class ESAggMetricTooltipProperty extends ESTooltipProperty { ) { return this._rawValue; } - const indexPatternField = this._indexPattern.fields.getByName( - this._metricField.getESDocFieldName() - ); + const indexPatternField = this._indexPattern.fields.getByName(this._metricField.getRootName()); if (!indexPatternField) { return this._rawValue; } diff --git a/x-pack/legacy/plugins/maps/public/layers/vector_layer.js b/x-pack/legacy/plugins/maps/public/layers/vector_layer.js index e1a30c8aef1d37..c515feecc15513 100644 --- a/x-pack/legacy/plugins/maps/public/layers/vector_layer.js +++ b/x-pack/legacy/plugins/maps/public/layers/vector_layer.js @@ -561,10 +561,13 @@ export class VectorLayer extends AbstractLayer { startLoading(dataRequestId, requestToken, nextMeta); const formatters = {}; - const promises = fields.map(async field => { - const fieldName = field.getName(); - formatters[fieldName] = await source.getFieldFormatter(fieldName); - }); + const promises = fields + .filter(field => { + return field.canValueBeFormatted(); + }) + .map(async field => { + formatters[field.getName()] = await source.createFieldFormatter(field); + }); await Promise.all(promises); stopLoading(dataRequestId, requestToken, formatters, nextMeta); From 511a9c2bee83890a874c124f30231482e6a5773e Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 27 Feb 2020 22:18:00 -0700 Subject: [PATCH 6/9] Revert "Prep agg types for new platform (#57064)" This reverts commit 0cede6a705db65ef450426db3c584fcabab42780. --- packages/kbn-utility-types/README.md | 1 - packages/kbn-utility-types/index.ts | 2 +- .../filters/brush_event.test.mocks.ts} | 13 +- .../actions/filters/brush_event.test.ts | 49 +- src/legacy/core_plugins/data/public/index.ts | 12 +- src/legacy/core_plugins/data/public/plugin.ts | 6 +- .../public/search/aggs/agg_config.test.ts | 497 ------ .../data/public/search/aggs/agg_config.ts | 61 +- .../public/search/aggs/agg_configs.test.ts | 503 ------ .../data/public/search/aggs/agg_configs.ts | 76 +- .../public/search/aggs/agg_params.test.ts | 2 + .../data/public/search/aggs/agg_type.test.ts | 16 +- .../data/public/search/aggs/agg_type.ts | 5 +- .../search/aggs/agg_types_registry.test.ts | 91 -- .../public/search/aggs/agg_types_registry.ts | 68 - .../search/aggs/buckets/_bucket_agg_type.ts | 12 +- .../search/aggs/buckets/_interval_options.ts | 1 - .../create_filter/date_histogram.test.ts | 12 +- .../buckets/create_filter/date_range.test.ts | 7 +- .../buckets/create_filter/filters.test.ts | 13 +- .../buckets/create_filter/histogram.test.ts | 12 +- .../buckets/create_filter/ip_range.test.ts | 11 +- .../aggs/buckets/create_filter/range.test.ts | 12 +- .../aggs/buckets/create_filter/terms.test.ts | 11 +- .../search/aggs/buckets/date_histogram.ts | 8 +- .../search/aggs/buckets/date_range.test.ts | 25 +- .../public/search/aggs/buckets/date_range.ts | 12 +- .../data/public/search/aggs/buckets/filter.ts | 1 - .../public/search/aggs/buckets/filters.ts | 26 +- .../search/aggs/buckets/geo_hash.test.ts | 7 +- .../public/search/aggs/buckets/geo_tile.ts | 3 +- .../search/aggs/buckets/histogram.test.ts | 33 +- .../public/search/aggs/buckets/histogram.ts | 12 +- .../public/search/aggs/buckets/ip_range.ts | 12 +- .../buckets/migrate_include_exclude_format.ts | 4 +- .../public/search/aggs/buckets/range.test.ts | 12 +- .../aggs/buckets/significant_terms.test.ts | 9 +- .../public/search/aggs/buckets/terms.test.ts | 8 +- .../aggs/filter/agg_type_filters.test.ts | 5 +- .../search/aggs/filter/agg_type_filters.ts | 1 - .../search/aggs/filter/prop_filter.test.ts | 19 +- .../data/public/search/aggs/index.test.ts | 2 + .../data/public/search/aggs/index.ts | 9 +- .../public/search/aggs/metrics/bucket_avg.ts | 1 + .../public/search/aggs/metrics/bucket_max.ts | 1 + .../public/search/aggs/metrics/bucket_min.ts | 1 - .../public/search/aggs/metrics/cardinality.ts | 5 +- .../data/public/search/aggs/metrics/count.ts | 7 +- .../lib/get_response_agg_config_class.ts | 1 - .../metrics/lib/parent_pipeline_agg_helper.ts | 1 + .../lib/sibling_pipeline_agg_helper.ts | 1 + .../public/search/aggs/metrics/median.test.ts | 7 +- .../data/public/search/aggs/metrics/median.ts | 4 +- .../search/aggs/metrics/metric_agg_type.ts | 7 +- .../data/public/search/aggs/metrics/min.ts | 1 - .../aggs/metrics/parent_pipeline.test.ts | 18 +- .../aggs/metrics/percentile_ranks.test.ts | 8 +- .../search/aggs/metrics/percentile_ranks.ts | 7 +- .../search/aggs/metrics/percentiles.test.ts | 6 +- .../public/search/aggs/metrics/percentiles.ts | 4 + .../aggs/metrics/sibling_pipeline.test.ts | 22 +- .../search/aggs/metrics/std_deviation.test.ts | 6 +- .../search/aggs/metrics/top_hit.test.ts | 6 +- .../public/search/aggs/param_types/agg.ts | 4 +- .../public/search/aggs/param_types/base.ts | 4 +- .../search/aggs/param_types/field.test.ts | 2 + .../public/search/aggs/param_types/field.ts | 5 +- .../param_types/filter/field_filters.test.ts | 11 +- .../aggs/param_types/filter/field_filters.ts | 8 +- .../search/aggs/param_types/json.test.ts | 8 +- .../public/search/aggs/param_types/json.ts | 4 +- .../search/aggs/param_types/optioned.test.ts | 2 + .../search/aggs/param_types/optioned.ts | 6 +- .../search/aggs/param_types/string.test.ts | 8 +- .../public/search/aggs/param_types/string.ts | 4 +- .../test_helpers/mock_agg_types_registry.ts | 57 - .../aggs/test_helpers/mock_data_services.ts | 54 - .../data/public/search/aggs/types.ts | 2 +- .../data/public/search/aggs/utils.test.tsx | 2 + .../data/public/search/aggs/utils.ts | 39 +- .../data/public/search/expressions/esaggs.ts | 4 +- .../data/public/search/expressions/utils.ts | 5 +- .../core_plugins/data/public/search/mocks.ts | 85 - .../data/public/search/search_service.ts | 60 +- .../data/public/search/tabify/buckets.test.ts | 2 + .../public/search/tabify/get_columns.test.ts | 22 +- .../search/tabify/response_writer.test.ts | 20 +- .../data/public/search/tabify/tabify.test.ts | 16 +- .../components/sidebar/state/reducers.ts | 18 +- .../public/legacy_imports.ts | 2 +- .../public/table_vis_controller.test.ts | 4 +- .../visualizations/public/legacy_imports.ts | 2 +- .../public/np_ready/public/vis_impl.js | 6 +- src/legacy/ui/public/agg_types/index.ts | 9 +- .../ui/public/vis/__tests__/_agg_config.js | 485 ++++++ .../ui/public/vis/__tests__/_agg_configs.js | 420 +++++ .../public/vis/__tests__/index.js} | 4 +- .../data/common/field_formats/mocks.ts | 49 - src/plugins/data/public/mocks.ts | 28 +- .../data/public/search/search_source/mocks.ts | 19 + .../editor_frame_service/service.test.tsx | 4 + .../__snapshots__/zeek_details.test.tsx.snap | 1448 +++++++++-------- 102 files changed, 2101 insertions(+), 2646 deletions(-) rename src/legacy/core_plugins/data/public/{services.ts => actions/filters/brush_event.test.mocks.ts} (76%) delete mode 100644 src/legacy/core_plugins/data/public/search/aggs/agg_config.test.ts delete mode 100644 src/legacy/core_plugins/data/public/search/aggs/agg_configs.test.ts delete mode 100644 src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.test.ts delete mode 100644 src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.ts delete mode 100644 src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts delete mode 100644 src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_data_services.ts delete mode 100644 src/legacy/core_plugins/data/public/search/mocks.ts create mode 100644 src/legacy/ui/public/vis/__tests__/_agg_config.js create mode 100644 src/legacy/ui/public/vis/__tests__/_agg_configs.js rename src/legacy/{core_plugins/data/public/search/aggs/test_helpers/index.ts => ui/public/vis/__tests__/index.js} (86%) delete mode 100644 src/plugins/data/common/field_formats/mocks.ts diff --git a/packages/kbn-utility-types/README.md b/packages/kbn-utility-types/README.md index b57e98e379707e..829fd21e143669 100644 --- a/packages/kbn-utility-types/README.md +++ b/packages/kbn-utility-types/README.md @@ -18,7 +18,6 @@ type B = UnwrapPromise
; // string ## Reference -- `Assign` — From `U` assign properties to `T` (just like object assign). - `Ensure` — Makes sure `T` is of type `X`. - `ObservableLike` — Minimal interface for an object resembling an `Observable`. - `PublicContract` — Returns an object with public keys only. diff --git a/packages/kbn-utility-types/index.ts b/packages/kbn-utility-types/index.ts index 657d9f547de66e..808935ed4cb5b8 100644 --- a/packages/kbn-utility-types/index.ts +++ b/packages/kbn-utility-types/index.ts @@ -18,7 +18,7 @@ */ import { PromiseType } from 'utility-types'; -export { $Values, Assign, Class, Optional, Required } from 'utility-types'; +export { $Values, Required, Optional, Class } from 'utility-types'; /** * A type that may or may not be a `Promise`. diff --git a/src/legacy/core_plugins/data/public/services.ts b/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.mocks.ts similarity index 76% rename from src/legacy/core_plugins/data/public/services.ts rename to src/legacy/core_plugins/data/public/actions/filters/brush_event.test.mocks.ts index 7ecd041c70e22e..2cecfd0fe8b767 100644 --- a/src/legacy/core_plugins/data/public/services.ts +++ b/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.mocks.ts @@ -17,9 +17,12 @@ * under the License. */ -import { createGetterSetter } from '../../../../plugins/kibana_utils/public'; -import { SearchStart } from './search/search_service'; +import { chromeServiceMock } from '../../../../../../core/public/mocks'; -export const [getSearchServiceShim, setSearchServiceShim] = createGetterSetter( - 'searchShim' -); +jest.doMock('ui/new_platform', () => ({ + npStart: { + core: { + chrome: chromeServiceMock.createStartContract(), + }, + }, +})); diff --git a/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.ts b/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.ts index eb29530f92fee7..0e18c7c707fa3f 100644 --- a/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.ts +++ b/src/legacy/core_plugins/data/public/actions/filters/brush_event.test.ts @@ -19,13 +19,33 @@ import moment from 'moment'; -import { onBrushEvent, BrushEvent } from './brush_event'; +jest.mock('../../search/aggs', () => ({ + AggConfigs: function AggConfigs() { + return { + createAggConfig: ({ params }: Record) => ({ + params, + getIndexPattern: () => ({ + timeFieldName: 'time', + }), + }), + }; + }, +})); + +jest.mock('../../../../../../plugins/data/public/services', () => ({ + getIndexPatterns: () => { + return { + get: async () => { + return { + id: 'logstash-*', + timeFieldName: 'time', + }; + }, + }; + }, +})); -import { mockDataServices } from '../../search/aggs/test_helpers'; -import { IndexPatternsContract } from '../../../../../../plugins/data/public'; -import { dataPluginMock } from '../../../../../../plugins/data/public/mocks'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { setIndexPatterns } from '../../../../../../plugins/data/public/services'; +import { onBrushEvent, BrushEvent } from './brush_event'; describe('brushEvent', () => { const DAY_IN_MS = 24 * 60 * 60 * 1000; @@ -39,28 +59,11 @@ describe('brushEvent', () => { }, getIndexPattern: () => ({ timeFieldName: 'time', - fields: { - getByName: () => undefined, - filter: () => [], - }, }), }, ]; beforeEach(() => { - mockDataServices(); - setIndexPatterns(({ - ...dataPluginMock.createStartContract().indexPatterns, - get: async () => ({ - id: 'indexPatternId', - timeFieldName: 'time', - fields: { - getByName: () => undefined, - filter: () => [], - }, - }), - } as unknown) as IndexPatternsContract); - baseEvent = { data: { ordered: { diff --git a/src/legacy/core_plugins/data/public/index.ts b/src/legacy/core_plugins/data/public/index.ts index 8d730d18a17559..8cde5d0a1fc115 100644 --- a/src/legacy/core_plugins/data/public/index.ts +++ b/src/legacy/core_plugins/data/public/index.ts @@ -35,18 +35,18 @@ export { } from '../../../../plugins/data/public'; export { // agg_types - AggParam, // only the type is used externally, only in vis editor - AggParamOption, // only the type is used externally - DateRangeKey, // only used in field formatter deserialization, which will live in data + AggParam, + AggParamOption, + DateRangeKey, IAggConfig, IAggConfigs, IAggType, IFieldParamType, IMetricAggType, - IpRangeKey, // only used in field formatter deserialization, which will live in data + IpRangeKey, ISchemas, - OptionedParamEditorProps, // only type is used externally - OptionedValueProp, // only type is used externally + OptionedParamEditorProps, + OptionedValueProp, } from './search/types'; /** @public static code */ diff --git a/src/legacy/core_plugins/data/public/plugin.ts b/src/legacy/core_plugins/data/public/plugin.ts index e2b8ca5dda78cf..e13e8e34eaebec 100644 --- a/src/legacy/core_plugins/data/public/plugin.ts +++ b/src/legacy/core_plugins/data/public/plugin.ts @@ -36,7 +36,6 @@ import { setOverlays, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../../../plugins/data/public/services'; -import { setSearchServiceShim } from './services'; import { SELECT_RANGE_ACTION, selectRangeAction } from './actions/select_range_action'; import { VALUE_CLICK_ACTION, valueClickAction } from './actions/value_click_action'; import { @@ -113,9 +112,6 @@ export class DataPlugin } public start(core: CoreStart, { data, uiActions }: DataPluginStartDependencies): DataStart { - const search = this.search.start(core); - setSearchServiceShim(search); - setUiSettings(core.uiSettings); setQueryService(data.query); setIndexPatterns(data.indexPatterns); @@ -127,7 +123,7 @@ export class DataPlugin uiActions.attachAction(VALUE_CLICK_TRIGGER, VALUE_CLICK_ACTION); return { - search, + search: this.search.start(core), }; } diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_config.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_config.test.ts deleted file mode 100644 index 7769aa29184d3a..00000000000000 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_config.test.ts +++ /dev/null @@ -1,497 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { identity } from 'lodash'; - -import { AggConfig, IAggConfig } from './agg_config'; -import { AggConfigs, CreateAggConfigParams } from './agg_configs'; -import { AggType } from './agg_types'; -import { AggTypesRegistryStart } from './agg_types_registry'; -import { mockDataServices, mockAggTypesRegistry } from './test_helpers'; -import { IndexPatternField, IndexPattern } from '../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { stubIndexPatternWithFields } from '../../../../../../plugins/data/public/stubs'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { dataPluginMock } from '../../../../../../plugins/data/public/mocks'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { setFieldFormats } from '../../../../../../plugins/data/public/services'; - -describe('AggConfig', () => { - let indexPattern: IndexPattern; - let typesRegistry: AggTypesRegistryStart; - - beforeEach(() => { - jest.restoreAllMocks(); - mockDataServices(); - indexPattern = stubIndexPatternWithFields as IndexPattern; - typesRegistry = mockAggTypesRegistry(); - }); - - describe('#toDsl', () => { - it('calls #write()', () => { - const ac = new AggConfigs(indexPattern, [], { typesRegistry }); - const configStates = { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }; - const aggConfig = ac.createAggConfig(configStates); - - const spy = jest.spyOn(aggConfig, 'write').mockImplementation(() => ({ params: {} })); - aggConfig.toDsl(); - expect(spy).toHaveBeenCalledTimes(1); - }); - - it('uses the type name as the agg name', () => { - const ac = new AggConfigs(indexPattern, [], { typesRegistry }); - const configStates = { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }; - const aggConfig = ac.createAggConfig(configStates); - - jest.spyOn(aggConfig, 'write').mockImplementation(() => ({ params: {} })); - const dsl = aggConfig.toDsl(); - expect(dsl).toHaveProperty('date_histogram'); - }); - - it('uses the params from #write() output as the agg params', () => { - const ac = new AggConfigs(indexPattern, [], { typesRegistry }); - const configStates = { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }; - const aggConfig = ac.createAggConfig(configStates); - - const football = {}; - jest.spyOn(aggConfig, 'write').mockImplementation(() => ({ params: football })); - const dsl = aggConfig.toDsl(); - expect(dsl.date_histogram).toBe(football); - }); - - it('includes subAggs from #write() output', () => { - const configStates = [ - { - enabled: true, - type: 'avg', - schema: 'metric', - params: {}, - }, - { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }, - ]; - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - - const histoConfig = ac.byName('date_histogram')[0]; - const avgConfig = ac.byName('avg')[0]; - const football = {}; - - jest - .spyOn(histoConfig, 'write') - .mockImplementation(() => ({ params: {}, subAggs: [avgConfig] })); - jest.spyOn(avgConfig, 'write').mockImplementation(() => ({ params: football })); - - const dsl = histoConfig.toDsl(); - expect(dsl).toHaveProperty('aggs'); - expect(dsl.aggs).toHaveProperty(avgConfig.id); - expect(dsl.aggs[avgConfig.id]).toHaveProperty('avg'); - expect(dsl.aggs[avgConfig.id].avg).toBe(football); - }); - }); - - describe('::ensureIds', () => { - it('accepts an array of objects and assigns ids to them', () => { - const objs = [{}, {}, {}, {}]; - AggConfig.ensureIds(objs); - expect(objs[0]).toHaveProperty('id', '1'); - expect(objs[1]).toHaveProperty('id', '2'); - expect(objs[2]).toHaveProperty('id', '3'); - expect(objs[3]).toHaveProperty('id', '4'); - }); - - it('assigns ids relative to the other only item in the list', () => { - const objs = [{ id: '100' }, {}]; - AggConfig.ensureIds(objs); - expect(objs[0]).toHaveProperty('id', '100'); - expect(objs[1]).toHaveProperty('id', '101'); - }); - - it('assigns ids relative to the other items in the list', () => { - const objs = [{ id: '100' }, { id: '200' }, { id: '500' }, { id: '350' }, {}]; - AggConfig.ensureIds(objs); - expect(objs[0]).toHaveProperty('id', '100'); - expect(objs[1]).toHaveProperty('id', '200'); - expect(objs[2]).toHaveProperty('id', '500'); - expect(objs[3]).toHaveProperty('id', '350'); - expect(objs[4]).toHaveProperty('id', '501'); - }); - - it('uses ::nextId to get the starting value', () => { - jest.spyOn(AggConfig, 'nextId').mockImplementation(() => 534); - const objs = AggConfig.ensureIds([{}]); - expect(objs[0]).toHaveProperty('id', '534'); - }); - - it('only calls ::nextId once', () => { - const start = 420; - const spy = jest.spyOn(AggConfig, 'nextId').mockImplementation(() => start); - const objs = AggConfig.ensureIds([{}, {}, {}, {}, {}, {}, {}]); - - expect(spy).toHaveBeenCalledTimes(1); - objs.forEach((obj, i) => { - expect(obj).toHaveProperty('id', String(start + i)); - }); - }); - }); - - describe('::nextId', () => { - it('accepts a list of objects and picks the next id', () => { - const next = AggConfig.nextId([{ id: '100' }, { id: '500' }] as IAggConfig[]); - expect(next).toBe(501); - }); - - it('handles an empty list', () => { - const next = AggConfig.nextId([]); - expect(next).toBe(1); - }); - - it('fails when the list is not defined', () => { - expect(() => { - AggConfig.nextId((undefined as unknown) as IAggConfig[]); - }).toThrowError(); - }); - }); - - describe('#toJsonDataEquals', () => { - const testsIdentical = [ - [ - { - enabled: true, - type: 'count', - schema: 'metric', - params: { field: '@timestamp' }, - }, - ], - [ - { - enabled: true, - type: 'avg', - schema: 'metric', - params: {}, - }, - { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }, - ], - ]; - - testsIdentical.forEach((configState, index) => { - it(`identical aggregations (${index})`, () => { - const ac1 = new AggConfigs(indexPattern, configState, { typesRegistry }); - const ac2 = new AggConfigs(indexPattern, configState, { typesRegistry }); - expect(ac1.jsonDataEquals(ac2.aggs)).toBe(true); - }); - }); - - const testsIdenticalDifferentOrder = [ - { - config1: [ - { - enabled: true, - type: 'avg', - schema: 'metric', - params: {}, - }, - { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }, - ], - config2: [ - { - enabled: true, - schema: 'metric', - type: 'avg', - params: {}, - }, - { - enabled: true, - schema: 'segment', - type: 'date_histogram', - params: {}, - }, - ], - }, - ]; - - testsIdenticalDifferentOrder.forEach((test, index) => { - it(`identical aggregations (${index}) - init json is in different order`, () => { - const ac1 = new AggConfigs(indexPattern, test.config1, { typesRegistry }); - const ac2 = new AggConfigs(indexPattern, test.config2, { typesRegistry }); - expect(ac1.jsonDataEquals(ac2.aggs)).toBe(true); - }); - }); - - const testsDifferent = [ - { - config1: [ - { - enabled: true, - type: 'avg', - schema: 'metric', - params: {}, - }, - { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }, - ], - config2: [ - { - enabled: true, - type: 'max', - schema: 'metric', - params: {}, - }, - { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }, - ], - }, - { - config1: [ - { - enabled: true, - type: 'count', - schema: 'metric', - params: { field: '@timestamp' }, - }, - ], - config2: [ - { - enabled: true, - type: 'count', - schema: 'metric', - params: { field: '@timestamp' }, - }, - { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }, - ], - }, - ]; - - testsDifferent.forEach((test, index) => { - it(`different aggregations (${index})`, () => { - const ac1 = new AggConfigs(indexPattern, test.config1, { typesRegistry }); - const ac2 = new AggConfigs(indexPattern, test.config2, { typesRegistry }); - expect(ac1.jsonDataEquals(ac2.aggs)).toBe(false); - }); - }); - }); - - describe('#toJSON', () => { - it('includes the aggs id, params, type and schema', () => { - const ac = new AggConfigs(indexPattern, [], { typesRegistry }); - const configStates = { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }; - const aggConfig = ac.createAggConfig(configStates); - - expect(aggConfig.id).toBe('1'); - expect(typeof aggConfig.params).toBe('object'); - expect(aggConfig.type).toBeInstanceOf(AggType); - expect(aggConfig.type).toHaveProperty('name', 'date_histogram'); - expect(typeof aggConfig.schema).toBe('object'); - expect(aggConfig.schema).toHaveProperty('name', 'segment'); - - const state = aggConfig.toJSON(); - expect(state).toHaveProperty('id', '1'); - expect(typeof state.params).toBe('object'); - expect(state).toHaveProperty('type', 'date_histogram'); - expect(state).toHaveProperty('schema', 'segment'); - }); - - it('test serialization order is identical (for visual consistency)', () => { - const configStates = [ - { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: {}, - }, - ]; - const ac1 = new AggConfigs(indexPattern, configStates, { typesRegistry }); - const ac2 = new AggConfigs(indexPattern, configStates, { typesRegistry }); - - // this relies on the assumption that js-engines consistently loop over properties in insertion order. - // most likely the case, but strictly speaking not guaranteed by the JS and JSON specifications. - expect(JSON.stringify(ac1.aggs) === JSON.stringify(ac2.aggs)).toBe(true); - }); - }); - - describe('#makeLabel', () => { - let aggConfig: AggConfig; - - beforeEach(() => { - const ac = new AggConfigs(indexPattern, [], { typesRegistry }); - aggConfig = ac.createAggConfig({ type: 'count' } as CreateAggConfigParams); - }); - - it('uses the custom label if it is defined', () => { - aggConfig.params.customLabel = 'Custom label'; - const label = aggConfig.makeLabel(); - expect(label).toBe(aggConfig.params.customLabel); - }); - - it('default label should be "Count"', () => { - const label = aggConfig.makeLabel(); - expect(label).toBe('Count'); - }); - - it('default label should be "Percentage of Count" when percentageMode is set to true', () => { - const label = aggConfig.makeLabel(true); - expect(label).toBe('Percentage of Count'); - }); - - it('empty label if the type is not defined', () => { - aggConfig.type = (undefined as unknown) as AggType; - const label = aggConfig.makeLabel(); - expect(label).toBe(''); - }); - }); - - describe('#fieldFormatter - custom getFormat handler', () => { - it('returns formatter from getFormat handler', () => { - setFieldFormats({ - ...dataPluginMock.createStartContract().fieldFormats, - getDefaultInstance: jest.fn().mockImplementation(() => ({ - getConverterFor: jest.fn().mockImplementation(() => (t: string) => t), - })) as any, - }); - - const ac = new AggConfigs(indexPattern, [], { typesRegistry }); - const configStates = { - enabled: true, - type: 'count', - schema: 'metric', - params: { field: '@timestamp' }, - }; - const aggConfig = ac.createAggConfig(configStates); - - const fieldFormatter = aggConfig.fieldFormatter(); - expect(fieldFormatter).toBeDefined(); - expect(fieldFormatter('text')).toBe('text'); - }); - }); - - // TODO: Converting these field formatter tests from browser tests to unit - // tests makes them much less helpful due to the extensive use of mocking. - // We should revisit these and rewrite them into something more useful. - describe('#fieldFormatter - no custom getFormat handler', () => { - let aggConfig: AggConfig; - - beforeEach(() => { - setFieldFormats({ - ...dataPluginMock.createStartContract().fieldFormats, - getDefaultInstance: jest.fn().mockImplementation(() => ({ - getConverterFor: (t?: string) => t || identity, - })) as any, - }); - indexPattern.fields.getByName = name => - ({ - format: { - getConverterFor: (t?: string) => t || identity, - }, - } as IndexPatternField); - - const configStates = { - enabled: true, - type: 'histogram', - schema: 'bucket', - params: { - field: { - format: { - getConverterFor: (t?: string) => t || identity, - }, - }, - }, - }; - const ac = new AggConfigs(indexPattern, [configStates], { typesRegistry }); - aggConfig = ac.createAggConfig(configStates); - }); - - it("returns the field's formatter", () => { - expect(aggConfig.fieldFormatter().toString()).toBe( - aggConfig - .getField() - .format.getConverterFor() - .toString() - ); - }); - - it('returns the string format if the field does not have a format', () => { - const agg = aggConfig; - agg.params.field = { type: 'number', format: null }; - const fieldFormatter = agg.fieldFormatter(); - expect(fieldFormatter).toBeDefined(); - expect(fieldFormatter('text')).toBe('text'); - }); - - it('returns the string format if there is no field', () => { - const agg = aggConfig; - delete agg.params.field; - const fieldFormatter = agg.fieldFormatter(); - expect(fieldFormatter).toBeDefined(); - expect(fieldFormatter('text')).toBe('text'); - }); - - it('returns the html converter if "html" is passed in', () => { - const field = indexPattern.fields.getByName('bytes'); - expect(aggConfig.fieldFormatter('html').toString()).toBe( - field!.format.getConverterFor('html').toString() - ); - }); - }); -}); diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_config.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_config.ts index 659bec3f702e37..2b21c5c4868a52 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_config.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_config.ts @@ -17,8 +17,16 @@ * under the License. */ +/** + * @name AggConfig + * + * @description This class represents an aggregation, which is displayed in the left-hand nav of + * the Visualize app. + */ + import _ from 'lodash'; import { i18n } from '@kbn/i18n'; +import { npStart } from 'ui/new_platform'; import { IAggType } from './agg_type'; import { AggGroupNames } from './agg_groups'; import { writeParams } from './agg_params'; @@ -30,20 +38,18 @@ import { FieldFormatsContentType, KBN_FIELD_TYPES, } from '../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getFieldFormats } from '../../../../../../plugins/data/public/services'; export interface AggConfigOptions { - type: IAggType; - enabled?: boolean; + enabled: boolean; + type: string; + params: any; id?: string; - params?: Record; - schema?: string | Schema; + schema?: string; } const unknownSchema: Schema = { name: 'unknown', - title: 'Unknown', // only here for illustrative purposes + title: 'Unknown', hideCustomLabel: true, aggFilter: [], min: 1, @@ -59,6 +65,21 @@ const unknownSchema: Schema = { }, }; +const getTypeFromRegistry = (type: string): IAggType => { + // We need to inline require here, since we're having a cyclic dependency + // from somewhere inside agg_types back to AggConfig. + const aggTypes = require('../aggs').aggTypes; + const registeredType = + aggTypes.metrics.find((agg: IAggType) => agg.name === type) || + aggTypes.buckets.find((agg: IAggType) => agg.name === type); + + if (!registeredType) { + throw new Error('unknown type'); + } + + return registeredType; +}; + const getSchemaFromRegistry = (schemas: any, schema: string): Schema => { let registeredSchema = schemas ? schemas.byName[schema] : null; if (!registeredSchema) { @@ -69,13 +90,6 @@ const getSchemaFromRegistry = (schemas: any, schema: string): Schema => { return registeredSchema; }; -/** - * @name AggConfig - * - * @description This class represents an aggregation, which is displayed in the left-hand nav of - * the Visualize app. - */ - // TODO need to make a more explicit interface for this export type IAggConfig = AggConfig; @@ -87,9 +101,9 @@ export class AggConfig { * @param {array[object]} list - a list of objects, objects can be anything really * @return {array} - the list that was passed in */ - static ensureIds(list: any[]) { - const have: IAggConfig[] = []; - const haveNot: AggConfigOptions[] = []; + static ensureIds(list: AggConfig[]) { + const have: AggConfig[] = []; + const haveNot: AggConfig[] = []; list.forEach(function(obj) { (obj.id ? have : haveNot).push(obj); }); @@ -107,7 +121,7 @@ export class AggConfig { * * @return {array} list - a list of objects with id properties */ - static nextId(list: IAggConfig[]) { + static nextId(list: AggConfig[]) { return ( 1 + list.reduce(function(max, obj) { @@ -147,10 +161,10 @@ export class AggConfig { // set the params to the values from opts, or just to the defaults this.setParams(opts.params || {}); - // @ts-ignore - this.__schema = this.__schema; // @ts-ignore this.__type = this.__type; + // @ts-ignore + this.__schema = this.__schema; } /** @@ -380,8 +394,7 @@ export class AggConfig { } fieldOwnFormatter(contentType?: FieldFormatsContentType, defaultFormat?: any) { - const fieldFormatsService = getFieldFormats(); - + const fieldFormatsService = npStart.plugins.data.fieldFormats; const field = this.getField(); let format = field && field.format; if (!format) format = defaultFormat; @@ -443,8 +456,8 @@ export class AggConfig { }); } - public setType(type: IAggType) { - this.type = type; + public setType(type: string | IAggType) { + this.type = typeof type === 'string' ? getTypeFromRegistry(type) : type; } public get schema() { diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_configs.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_configs.test.ts deleted file mode 100644 index 29f16b1e4f0bf2..00000000000000 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_configs.test.ts +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { indexBy } from 'lodash'; -import { AggConfig } from './agg_config'; -import { AggConfigs } from './agg_configs'; -import { AggTypesRegistryStart } from './agg_types_registry'; -import { Schemas } from './schemas'; -import { AggGroupNames } from './agg_groups'; -import { mockDataServices, mockAggTypesRegistry } from './test_helpers'; -import { IndexPatternField, IndexPattern } from '../../../../../../plugins/data/public'; -import { - stubIndexPattern, - stubIndexPatternWithFields, - // eslint-disable-next-line @kbn/eslint/no-restricted-paths -} from '../../../../../../plugins/data/public/stubs'; - -describe('AggConfigs', () => { - let indexPattern: IndexPattern; - let typesRegistry: AggTypesRegistryStart; - - beforeEach(() => { - indexPattern = stubIndexPatternWithFields as IndexPattern; - typesRegistry = mockAggTypesRegistry(); - }); - - describe('constructor', () => { - it('handles passing just a type', () => { - const configStates = [ - { - enabled: true, - type: 'histogram', - params: {}, - }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - expect(ac.aggs).toHaveLength(1); - }); - - it('attempts to ensure that all states have an id', () => { - const configStates = [ - { - enabled: true, - type: 'histogram', - params: {}, - }, - { - enabled: true, - type: 'date_histogram', - params: {}, - }, - { - enabled: true, - type: 'terms', - params: {}, - schema: 'split', - }, - ]; - - const spy = jest.spyOn(AggConfig, 'ensureIds'); - new AggConfigs(indexPattern, configStates, { typesRegistry }); - expect(spy).toHaveBeenCalledTimes(1); - expect(spy.mock.calls[0]).toEqual([configStates]); - spy.mockRestore(); - }); - - describe('defaults', () => { - const schemas = new Schemas([ - { - group: AggGroupNames.Metrics, - name: 'metric', - title: 'Simple', - min: 1, - max: 2, - defaults: [ - { schema: 'metric', type: 'count' }, - { schema: 'metric', type: 'avg' }, - { schema: 'metric', type: 'sum' }, - ], - }, - { - group: AggGroupNames.Buckets, - name: 'segment', - title: 'Example', - min: 0, - max: 1, - defaults: [ - { schema: 'segment', type: 'terms' }, - { schema: 'segment', type: 'filters' }, - ], - }, - ]); - - it('should only set the number of defaults defined by the max', () => { - const ac = new AggConfigs(indexPattern, [], { - schemas: schemas.all, - typesRegistry, - }); - expect(ac.bySchemaName('metric')).toHaveLength(2); - }); - - it('should set the defaults defined in the schema when none exist', () => { - const ac = new AggConfigs(indexPattern, [], { - schemas: schemas.all, - typesRegistry, - }); - expect(ac.aggs).toHaveLength(3); - }); - - it('should NOT set the defaults defined in the schema when some exist', () => { - const configStates = [ - { - enabled: true, - type: 'date_histogram', - params: {}, - schema: 'segment', - }, - ]; - const ac = new AggConfigs(indexPattern, configStates, { - schemas: schemas.all, - typesRegistry, - }); - expect(ac.aggs).toHaveLength(3); - expect(ac.bySchemaName('segment')[0].type.name).toEqual('date_histogram'); - }); - }); - }); - - describe('#createAggConfig', () => { - it('accepts a configState which is provided as an AggConfig object', () => { - const configStates = [ - { - enabled: true, - type: 'histogram', - params: {}, - }, - { - enabled: true, - type: 'date_histogram', - params: {}, - }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - expect(ac.aggs).toHaveLength(2); - - ac.createAggConfig( - new AggConfig(ac, { - enabled: true, - type: typesRegistry.get('terms'), - params: {}, - schema: 'split', - }) - ); - expect(ac.aggs).toHaveLength(3); - }); - - it('adds new AggConfig entries to AggConfigs by default', () => { - const configStates = [ - { - enabled: true, - type: 'histogram', - params: {}, - }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - expect(ac.aggs).toHaveLength(1); - - ac.createAggConfig({ - enabled: true, - type: 'terms', - params: {}, - schema: 'split', - }); - expect(ac.aggs).toHaveLength(2); - }); - - it('does not add an agg to AggConfigs if addToAggConfigs: false', () => { - const configStates = [ - { - enabled: true, - type: 'histogram', - params: {}, - }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - expect(ac.aggs).toHaveLength(1); - - ac.createAggConfig( - { - enabled: true, - type: 'terms', - params: {}, - schema: 'split', - }, - { addToAggConfigs: false } - ); - expect(ac.aggs).toHaveLength(1); - }); - }); - - describe('#getRequestAggs', () => { - it('performs a stable sort, but moves metrics to the bottom', () => { - const configStates = [ - { type: 'avg', enabled: true, params: {}, schema: 'metric' }, - { type: 'terms', enabled: true, params: {}, schema: 'split' }, - { type: 'histogram', enabled: true, params: {}, schema: 'split' }, - { type: 'sum', enabled: true, params: {}, schema: 'metric' }, - { type: 'date_histogram', enabled: true, params: {}, schema: 'segment' }, - { type: 'filters', enabled: true, params: {}, schema: 'split' }, - { type: 'percentiles', enabled: true, params: {}, schema: 'metric' }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - const sorted = ac.getRequestAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); - - expect(sorted.shift()).toBe(aggs.terms); - expect(sorted.shift()).toBe(aggs.histogram); - expect(sorted.shift()).toBe(aggs.date_histogram); - expect(sorted.shift()).toBe(aggs.filters); - expect(sorted.shift()).toBe(aggs.avg); - expect(sorted.shift()).toBe(aggs.sum); - expect(sorted.shift()).toBe(aggs.percentiles); - expect(sorted).toHaveLength(0); - }); - }); - - describe('#getResponseAggs', () => { - it('returns all request aggs for basic aggs', () => { - const configStates = [ - { type: 'terms', enabled: true, params: {}, schema: 'split' }, - { type: 'date_histogram', enabled: true, params: {}, schema: 'segment' }, - { type: 'count', enabled: true, params: {}, schema: 'metric' }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - const sorted = ac.getResponseAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); - - expect(sorted.shift()).toBe(aggs.terms); - expect(sorted.shift()).toBe(aggs.date_histogram); - expect(sorted.shift()).toBe(aggs.count); - expect(sorted).toHaveLength(0); - }); - - it('expands aggs that have multiple responses', () => { - const configStates = [ - { type: 'terms', enabled: true, params: {}, schema: 'split' }, - { type: 'date_histogram', enabled: true, params: {}, schema: 'segment' }, - { type: 'percentiles', enabled: true, params: { percents: [1, 2, 3] }, schema: 'metric' }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - const sorted = ac.getResponseAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); - - expect(sorted.shift()).toBe(aggs.terms); - expect(sorted.shift()).toBe(aggs.date_histogram); - expect(sorted.shift()!.id!).toBe(aggs.percentiles.id + '.' + 1); - expect(sorted.shift()!.id!).toBe(aggs.percentiles.id + '.' + 2); - expect(sorted.shift()!.id!).toBe(aggs.percentiles.id + '.' + 3); - expect(sorted).toHaveLength(0); - }); - }); - - describe('#toDsl', () => { - const schemas = new Schemas([ - { - group: AggGroupNames.Buckets, - name: 'segment', - }, - { - group: AggGroupNames.Buckets, - name: 'split', - }, - ]); - - beforeEach(() => { - mockDataServices(); - indexPattern = stubIndexPattern as IndexPattern; - indexPattern.fields.getByName = name => (name as unknown) as IndexPatternField; - }); - - it('uses the sorted aggs', () => { - const configStates = [{ enabled: true, type: 'avg', params: { field: 'bytes' } }]; - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - const spy = jest.spyOn(AggConfigs.prototype, 'getRequestAggs'); - ac.toDsl(); - expect(spy).toHaveBeenCalledTimes(1); - spy.mockRestore(); - }); - - it('calls aggConfig#toDsl() on each aggConfig and compiles the nested output', () => { - const configStates = [ - { enabled: true, type: 'date_histogram', params: {}, schema: 'segment' }, - { enabled: true, type: 'terms', params: {}, schema: 'split' }, - { enabled: true, type: 'count', params: {} }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { - typesRegistry, - schemas: schemas.all, - }); - - const aggInfos = ac.aggs.map(aggConfig => { - const football = {}; - aggConfig.toDsl = jest.fn().mockImplementation(() => football); - - return { - id: aggConfig.id, - football, - }; - }); - - (function recurse(lvl: Record): void { - const info = aggInfos.shift(); - if (!info) return; - - expect(lvl).toHaveProperty(info.id); - expect(lvl[info.id]).toBe(info.football); - - if (lvl[info.id].aggs) { - return recurse(lvl[info.id].aggs); - } - })(ac.toDsl()); - - expect(aggInfos).toHaveLength(1); - }); - - it("skips aggs that don't have a dsl representation", () => { - const configStates = [ - { - enabled: true, - type: 'date_histogram', - params: { field: '@timestamp', interval: '10s' }, - schema: 'segment', - }, - { - enabled: true, - type: 'count', - params: {}, - schema: 'metric', - }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - const dsl = ac.toDsl(); - const histo = ac.byName('date_histogram')[0]; - const count = ac.byName('count')[0]; - - expect(dsl).toHaveProperty(histo.id); - expect(typeof dsl[histo.id]).toBe('object'); - expect(dsl[histo.id]).not.toHaveProperty('aggs'); - expect(dsl).not.toHaveProperty(count.id); - }); - - it('writes multiple metric aggregations at the same level', () => { - const configStates = [ - { - enabled: true, - type: 'date_histogram', - schema: 'segment', - params: { field: '@timestamp', interval: '10s' }, - }, - { enabled: true, type: 'avg', schema: 'metric', params: { field: 'bytes' } }, - { enabled: true, type: 'sum', schema: 'metric', params: { field: 'bytes' } }, - { enabled: true, type: 'min', schema: 'metric', params: { field: 'bytes' } }, - { enabled: true, type: 'max', schema: 'metric', params: { field: 'bytes' } }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { - typesRegistry, - schemas: schemas.all, - }); - const dsl = ac.toDsl(); - const histo = ac.byName('date_histogram')[0]; - const metrics = ac.bySchemaGroup('metrics'); - - expect(dsl).toHaveProperty(histo.id); - expect(typeof dsl[histo.id]).toBe('object'); - expect(dsl[histo.id]).toHaveProperty('aggs'); - - metrics.forEach(metric => { - expect(dsl[histo.id].aggs).toHaveProperty(metric.id); - expect(dsl[histo.id].aggs[metric.id]).not.toHaveProperty('aggs'); - }); - }); - - it('writes multiple metric aggregations at every level if the vis is hierarchical', () => { - const configStates = [ - { enabled: true, type: 'terms', schema: 'segment', params: { field: 'bytes', orderBy: 1 } }, - { enabled: true, type: 'terms', schema: 'segment', params: { field: 'bytes', orderBy: 1 } }, - { enabled: true, id: '1', type: 'avg', schema: 'metric', params: { field: 'bytes' } }, - { enabled: true, type: 'sum', schema: 'metric', params: { field: 'bytes' } }, - { enabled: true, type: 'min', schema: 'metric', params: { field: 'bytes' } }, - { enabled: true, type: 'max', schema: 'metric', params: { field: 'bytes' } }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - const topLevelDsl = ac.toDsl(true); - const buckets = ac.bySchemaGroup('buckets'); - const metrics = ac.bySchemaGroup('metrics'); - - (function checkLevel(dsl) { - const bucket = buckets.shift(); - if (!bucket) return; - - expect(dsl).toHaveProperty(bucket.id); - - expect(typeof dsl[bucket.id]).toBe('object'); - expect(dsl[bucket.id]).toHaveProperty('aggs'); - - metrics.forEach((metric: AggConfig) => { - expect(dsl[bucket.id].aggs).toHaveProperty(metric.id); - expect(dsl[bucket.id].aggs[metric.id]).not.toHaveProperty('aggs'); - }); - - if (buckets.length) { - checkLevel(dsl[bucket.id].aggs); - } - })(topLevelDsl); - }); - - it('adds the parent aggs of nested metrics at every level if the vis is hierarchical', () => { - const configStates = [ - { - enabled: true, - id: '1', - type: 'avg_bucket', - schema: 'metric', - params: { - customBucket: { - id: '1-bucket', - type: 'date_histogram', - schema: 'bucketAgg', - params: { - field: '@timestamp', - interval: '10s', - }, - }, - customMetric: { - id: '1-metric', - type: 'count', - schema: 'metricAgg', - params: {}, - }, - }, - }, - { - enabled: true, - id: '2', - type: 'terms', - schema: 'bucket', - params: { - field: 'clientip', - }, - }, - { - enabled: true, - id: '3', - type: 'terms', - schema: 'bucket', - params: { - field: 'machine.os.raw', - }, - }, - ]; - - const ac = new AggConfigs(indexPattern, configStates, { typesRegistry }); - const topLevelDsl = ac.toDsl(true)['2']; - - expect(Object.keys(topLevelDsl.aggs)).toContain('1'); - expect(Object.keys(topLevelDsl.aggs)).toContain('1-bucket'); - expect(topLevelDsl.aggs['1'].avg_bucket).toHaveProperty('buckets_path', '1-bucket>_count'); - expect(Object.keys(topLevelDsl.aggs['3'].aggs)).toContain('1'); - expect(Object.keys(topLevelDsl.aggs['3'].aggs)).toContain('1-bucket'); - expect(topLevelDsl.aggs['3'].aggs['1'].avg_bucket).toHaveProperty( - 'buckets_path', - '1-bucket>_count' - ); - }); - }); -}); diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_configs.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_configs.ts index ab70e66b1e138c..8e091ed5f21ae0 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_configs.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_configs.ts @@ -17,12 +17,17 @@ * under the License. */ -import _ from 'lodash'; -import { Assign } from '@kbn/utility-types'; +/** + * @name AggConfig + * + * @extends IndexedArray + * + * @description A "data structure"-like class with methods for indexing and + * accessing instances of AggConfig. + */ +import _ from 'lodash'; import { AggConfig, AggConfigOptions, IAggConfig } from './agg_config'; -import { IAggType } from './agg_type'; -import { AggTypesRegistryStart } from './agg_types_registry'; import { Schema } from './schemas'; import { AggGroupNames } from './agg_groups'; import { @@ -50,24 +55,6 @@ function parseParentAggs(dslLvlCursor: any, dsl: any) { } } -export interface AggConfigsOptions { - schemas?: Schemas; - typesRegistry: AggTypesRegistryStart; -} - -export type CreateAggConfigParams = Assign; - -/** - * @name AggConfigs - * - * @description A "data structure"-like class with methods for indexing and - * accessing instances of AggConfig. This should never be instantiated directly - * outside of this plugin. Rather, downstream plugins should do this via - * `createAggConfigs()` - * - * @internal - */ - // TODO need to make a more explicit interface for this export type IAggConfigs = AggConfigs; @@ -75,31 +62,23 @@ export class AggConfigs { public indexPattern: IndexPattern; public schemas: any; public timeRange?: TimeRange; - private readonly typesRegistry: AggTypesRegistryStart; aggs: IAggConfig[]; - constructor( - indexPattern: IndexPattern, - configStates: CreateAggConfigParams[] = [], - opts: AggConfigsOptions - ) { - this.typesRegistry = opts.typesRegistry; - + constructor(indexPattern: IndexPattern, configStates = [] as any, schemas?: any) { configStates = AggConfig.ensureIds(configStates); this.aggs = []; this.indexPattern = indexPattern; - this.schemas = opts.schemas; + this.schemas = schemas; configStates.forEach((params: any) => this.createAggConfig(params)); - if (this.schemas) { - this.initializeDefaultsFromSchemas(this.schemas); + if (schemas) { + this.initializeDefaultsFromSchemas(schemas); } } - // do this wherever the schemas were passed in, & pass in state defaults instead initializeDefaultsFromSchemas(schemas: Schemas) { // Set the defaults for any schema which has them. If the defaults // for some reason has more then the max only set the max number @@ -112,11 +91,10 @@ export class AggConfigs { }) .each((schema: any) => { if (!this.aggs.find((agg: AggConfig) => agg.schema && agg.schema.name === schema.name)) { - // the result here should be passable as a configState const defaults = schema.defaults.slice(0, schema.max); _.each(defaults, defaultState => { const state = _.defaults({ id: AggConfig.nextId(this.aggs) }, defaultState); - this.createAggConfig(state as AggConfigOptions); + this.aggs.push(new AggConfig(this, state as AggConfigOptions)); }); } }) @@ -146,36 +124,28 @@ export class AggConfigs { if (!enabledOnly) return true; return agg.enabled; }; - - const aggConfigs = new AggConfigs(this.indexPattern, this.aggs.filter(filterAggs), { - schemas: this.schemas, - typesRegistry: this.typesRegistry, - }); - + const aggConfigs = new AggConfigs( + this.indexPattern, + this.aggs.filter(filterAggs), + this.schemas + ); return aggConfigs; } createAggConfig = ( - params: CreateAggConfigParams, + params: AggConfig | AggConfigOptions, { addToAggConfigs = true } = {} ) => { - const { type } = params; let aggConfig; - if (params instanceof AggConfig) { aggConfig = params; params.parent = this; } else { - aggConfig = new AggConfig(this, { - ...params, - type: typeof type === 'string' ? this.typesRegistry.get(type) : type, - }); + aggConfig = new AggConfig(this, params); } - if (addToAggConfigs) { this.aggs.push(aggConfig); } - return aggConfig as T; }; @@ -196,10 +166,10 @@ export class AggConfigs { return true; } - toDsl(hierarchical: boolean = false): Record { + toDsl(hierarchical: boolean = false) { const dslTopLvl = {}; let dslLvlCursor: Record; - let nestedMetrics: Array<{ config: AggConfig; dsl: Record }> | []; + let nestedMetrics: Array<{ config: AggConfig; dsl: any }> | []; if (hierarchical) { // collect all metrics, and filter out the ones that we won't be copying diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_params.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_params.test.ts index b08fcf309e9ed6..30ab272537dad1 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_params.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_params.test.ts @@ -23,6 +23,8 @@ import { FieldParamType } from './param_types/field'; import { OptionedParamType } from './param_types/optioned'; import { AggParamType } from '../aggs/param_types/agg'; +jest.mock('ui/new_platform'); + describe('AggParams class', () => { describe('constructor args', () => { it('accepts an array of param defs', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_type.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_type.test.ts index c78e56dd25887d..6d4c2d1317f505 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_type.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_type.test.ts @@ -19,16 +19,11 @@ import { AggType, AggTypeConfig } from './agg_type'; import { IAggConfig } from './agg_config'; -import { mockDataServices } from './test_helpers'; -import { dataPluginMock } from '../../../../../../plugins/data/public/mocks'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { setFieldFormats } from '../../../../../../plugins/data/public/services'; +import { npStart } from 'ui/new_platform'; -describe('AggType Class', () => { - beforeEach(() => { - mockDataServices(); - }); +jest.mock('ui/new_platform'); +describe('AggType Class', () => { describe('constructor', () => { it("requires a valid config object as it's first param", () => { expect(() => { @@ -158,10 +153,7 @@ describe('AggType Class', () => { }); it('returns default formatter', () => { - setFieldFormats({ - ...dataPluginMock.createStartContract().fieldFormats, - getDefaultInstance: jest.fn(() => 'default') as any, - }); + npStart.plugins.data.fieldFormats.getDefaultInstance = jest.fn(() => 'default') as any; const aggType = new AggType({ name: 'name', diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_type.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_type.ts index 3cd9496d3f23d0..5ccf0f65c0e921 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_type.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/agg_type.ts @@ -19,6 +19,7 @@ import { constant, noop, identity } from 'lodash'; import { i18n } from '@kbn/i18n'; +import { npStart } from 'ui/new_platform'; import { initParams } from './agg_params'; import { AggConfig } from './agg_config'; @@ -31,8 +32,6 @@ import { IFieldFormat, ISearchSource, } from '../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getFieldFormats } from '../../../../../../plugins/data/public/services'; export interface AggTypeConfig< TAggConfig extends AggConfig = AggConfig, @@ -66,7 +65,7 @@ export interface AggTypeConfig< const getFormat = (agg: AggConfig) => { const field = agg.getField(); - const fieldFormatsService = getFieldFormats(); + const fieldFormatsService = npStart.plugins.data.fieldFormats; return field ? field.format : fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.STRING); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.test.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.test.ts deleted file mode 100644 index 405f83e237de83..00000000000000 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { - AggTypesRegistry, - AggTypesRegistrySetup, - AggTypesRegistryStart, -} from './agg_types_registry'; -import { BucketAggType } from './buckets/_bucket_agg_type'; -import { MetricAggType } from './metrics/metric_agg_type'; - -const bucketType = { name: 'terms', type: 'bucket' } as BucketAggType; -const metricType = { name: 'count', type: 'metric' } as MetricAggType; - -describe('AggTypesRegistry', () => { - let registry: AggTypesRegistry; - let setup: AggTypesRegistrySetup; - let start: AggTypesRegistryStart; - - beforeEach(() => { - registry = new AggTypesRegistry(); - setup = registry.setup(); - start = registry.start(); - }); - - it('registerBucket adds new buckets', () => { - setup.registerBucket(bucketType); - expect(start.getBuckets()).toEqual([bucketType]); - }); - - it('registerBucket throws error when registering duplicate bucket', () => { - expect(() => { - setup.registerBucket(bucketType); - setup.registerBucket(bucketType); - }).toThrow(/already been registered with name: terms/); - }); - - it('registerMetric adds new metrics', () => { - setup.registerMetric(metricType); - expect(start.getMetrics()).toEqual([metricType]); - }); - - it('registerMetric throws error when registering duplicate metric', () => { - expect(() => { - setup.registerMetric(metricType); - setup.registerMetric(metricType); - }).toThrow(/already been registered with name: count/); - }); - - it('gets either buckets or metrics by id', () => { - setup.registerBucket(bucketType); - setup.registerMetric(metricType); - expect(start.get('terms')).toEqual(bucketType); - expect(start.get('count')).toEqual(metricType); - }); - - it('getBuckets retrieves only buckets', () => { - setup.registerBucket(bucketType); - expect(start.getBuckets()).toEqual([bucketType]); - }); - - it('getMetrics retrieves only metrics', () => { - setup.registerMetric(metricType); - expect(start.getMetrics()).toEqual([metricType]); - }); - - it('getAll returns all buckets and metrics', () => { - setup.registerBucket(bucketType); - setup.registerMetric(metricType); - expect(start.getAll()).toEqual({ - buckets: [bucketType], - metrics: [metricType], - }); - }); -}); diff --git a/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.ts b/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.ts deleted file mode 100644 index 8a8746106ae587..00000000000000 --- a/src/legacy/core_plugins/data/public/search/aggs/agg_types_registry.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { BucketAggType } from './buckets/_bucket_agg_type'; -import { MetricAggType } from './metrics/metric_agg_type'; - -export type AggTypesRegistrySetup = ReturnType; -export type AggTypesRegistryStart = ReturnType; - -export class AggTypesRegistry { - private readonly bucketAggs = new Map(); - private readonly metricAggs = new Map(); - - setup = () => { - return { - registerBucket: >(type: T): void => { - const { name } = type; - if (this.bucketAggs.get(name)) { - throw new Error(`Bucket agg has already been registered with name: ${name}`); - } - this.bucketAggs.set(name, type); - }, - registerMetric: >(type: T): void => { - const { name } = type; - if (this.metricAggs.get(name)) { - throw new Error(`Metric agg has already been registered with name: ${name}`); - } - this.metricAggs.set(name, type); - }, - }; - }; - - start = () => { - return { - get: (name: string) => { - return this.bucketAggs.get(name) || this.metricAggs.get(name); - }, - getBuckets: () => { - return Array.from(this.bucketAggs.values()); - }, - getMetrics: () => { - return Array.from(this.metricAggs.values()); - }, - getAll: () => { - return { - buckets: Array.from(this.bucketAggs.values()), - metrics: Array.from(this.metricAggs.values()), - }; - }, - }; - }; -} diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/_bucket_agg_type.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/_bucket_agg_type.ts index d6ab58d5250a8c..546d054c5af978 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/_bucket_agg_type.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/_bucket_agg_type.ts @@ -17,16 +17,16 @@ * under the License. */ -import { IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; import { AggType, AggTypeConfig } from '../agg_type'; import { AggParamType } from '../param_types/agg'; -export interface IBucketAggConfig extends IAggConfig { +export interface IBucketAggConfig extends AggConfig { type: InstanceType; } -export interface BucketAggParam +export interface BucketAggParam extends AggParamType { scriptable?: boolean; filterFieldTypes?: KBN_FIELD_TYPES | KBN_FIELD_TYPES[] | '*'; @@ -34,12 +34,12 @@ export interface BucketAggParam const bucketType = 'buckets'; -interface BucketAggTypeConfig +interface BucketAggTypeConfig extends AggTypeConfig> { - getKey?: (bucket: any, key: any, agg: IAggConfig) => any; + getKey?: (bucket: any, key: any, agg: AggConfig) => any; } -export class BucketAggType extends AggType< +export class BucketAggType extends AggType< TBucketAggConfig, BucketAggParam > { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/_interval_options.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/_interval_options.ts index 393d3b745250f4..e196687607d198 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/_interval_options.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/_interval_options.ts @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import { i18n } from '@kbn/i18n'; import { IBucketAggConfig } from './_bucket_agg_type'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts index 2b47dc384bca2f..0d3f58c50a42e7 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts @@ -21,22 +21,14 @@ import moment from 'moment'; import { createFilterDateHistogram } from './date_histogram'; import { intervalOptions } from '../_interval_options'; import { AggConfigs } from '../../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; -import { dateHistogramBucketAgg, IBucketDateHistogramAggConfig } from '../date_histogram'; +import { IBucketDateHistogramAggConfig } from '../date_histogram'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { RangeFilter } from '../../../../../../../../plugins/data/public'; -// TODO: remove this once time buckets is migrated jest.mock('ui/new_platform'); describe('AggConfig Filters', () => { describe('date_histogram', () => { - beforeEach(() => { - mockDataServices(); - }); - - const typesRegistry = mockAggTypesRegistry([dateHistogramBucketAgg]); - let agg: IBucketDateHistogramAggConfig; let filter: RangeFilter; let bucketStart: any; @@ -64,7 +56,7 @@ describe('AggConfig Filters', () => { params: { field: field.name, interval, customInterval: '5d' }, }, ], - { typesRegistry } + null ); const bucketKey = 1422579600000; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts index c594c7718e58bb..41e806668337e2 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/date_range.test.ts @@ -18,17 +18,16 @@ */ import moment from 'moment'; -import { dateRangeBucketAgg } from '../date_range'; import { createFilterDateRange } from './date_range'; import { fieldFormats, FieldFormatsGetConfigFn } from '../../../../../../../../plugins/data/public'; import { AggConfigs } from '../../agg_configs'; -import { mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; +jest.mock('ui/new_platform'); + describe('AggConfig Filters', () => { describe('Date range', () => { - const typesRegistry = mockAggTypesRegistry([dateRangeBucketAgg]); const getConfig = (() => {}) as FieldFormatsGetConfigFn; const getAggConfigs = () => { const field = { @@ -56,7 +55,7 @@ describe('AggConfig Filters', () => { }, }, ], - { typesRegistry } + null ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts index 3b9c771e0f15f9..34cf996826865f 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/filters.test.ts @@ -16,21 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import { filtersBucketAgg } from '../filters'; import { createFilterFilters } from './filters'; import { AggConfigs } from '../../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; import { IBucketAggConfig } from '../_bucket_agg_type'; +jest.mock('ui/new_platform'); + describe('AggConfig Filters', () => { describe('filters', () => { - beforeEach(() => { - mockDataServices(); - }); - - const typesRegistry = mockAggTypesRegistry([filtersBucketAgg]); - const getAggConfigs = () => { const field = { name: 'bytes', @@ -59,7 +52,7 @@ describe('AggConfig Filters', () => { }, }, ], - { typesRegistry } + null ); }; it('should return a filters filter', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/histogram.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/histogram.test.ts index b046c802c58c15..9f845847df5d9d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/histogram.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/histogram.test.ts @@ -16,22 +16,16 @@ * specific language governing permissions and limitations * under the License. */ - import { createFilterHistogram } from './histogram'; import { AggConfigs } from '../../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; import { fieldFormats, FieldFormatsGetConfigFn } from '../../../../../../../../plugins/data/public'; +jest.mock('ui/new_platform'); + describe('AggConfig Filters', () => { describe('histogram', () => { - beforeEach(() => { - mockDataServices(); - }); - - const typesRegistry = mockAggTypesRegistry(); - const getConfig = (() => {}) as FieldFormatsGetConfigFn; const getAggConfigs = () => { const field = { @@ -61,7 +55,7 @@ describe('AggConfig Filters', () => { }, }, ], - { typesRegistry } + null ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts index 7572c48390dc25..e92ba5cb2852a1 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/ip_range.test.ts @@ -17,18 +17,17 @@ * under the License. */ -import { ipRangeBucketAgg } from '../ip_range'; import { createFilterIpRange } from './ip_range'; -import { AggConfigs, CreateAggConfigParams } from '../../agg_configs'; -import { mockAggTypesRegistry } from '../../test_helpers'; +import { AggConfigs } from '../../agg_configs'; import { fieldFormats } from '../../../../../../../../plugins/data/public'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; +jest.mock('ui/new_platform'); + describe('AggConfig Filters', () => { describe('IP range', () => { - const typesRegistry = mockAggTypesRegistry([ipRangeBucketAgg]); - const getAggConfigs = (aggs: CreateAggConfigParams[]) => { + const getAggConfigs = (aggs: Array>) => { const field = { name: 'ip', format: fieldFormats.IpFormat, @@ -43,7 +42,7 @@ describe('AggConfig Filters', () => { }, } as any; - return new AggConfigs(indexPattern, aggs, { typesRegistry }); + return new AggConfigs(indexPattern, aggs, null); }; it('should return a range filter for ip_range agg', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/range.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/range.test.ts index 324d4252908324..33344ca0a34845 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/range.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/range.test.ts @@ -17,22 +17,16 @@ * under the License. */ -import { rangeBucketAgg } from '../range'; import { createFilterRange } from './range'; import { fieldFormats, FieldFormatsGetConfigFn } from '../../../../../../../../plugins/data/public'; import { AggConfigs } from '../../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../../test_helpers'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; +jest.mock('ui/new_platform'); + describe('AggConfig Filters', () => { describe('range', () => { - beforeEach(() => { - mockDataServices(); - }); - - const typesRegistry = mockAggTypesRegistry([rangeBucketAgg]); - const getConfig = (() => {}) as FieldFormatsGetConfigFn; const getAggConfigs = () => { const field = { @@ -62,7 +56,7 @@ describe('AggConfig Filters', () => { }, }, ], - { typesRegistry } + null ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts index 6db6eb11a5f527..7c6e769437ca1d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/create_filter/terms.test.ts @@ -17,18 +17,17 @@ * under the License. */ -import { termsBucketAgg } from '../terms'; import { createFilterTerms } from './terms'; -import { AggConfigs, CreateAggConfigParams } from '../../agg_configs'; -import { mockAggTypesRegistry } from '../../test_helpers'; +import { AggConfigs } from '../../agg_configs'; import { BUCKET_TYPES } from '../bucket_agg_types'; import { IBucketAggConfig } from '../_bucket_agg_type'; import { Filter, ExistsFilter } from '../../../../../../../../plugins/data/public'; +jest.mock('ui/new_platform'); + describe('AggConfig Filters', () => { describe('terms', () => { - const typesRegistry = mockAggTypesRegistry([termsBucketAgg]); - const getAggConfigs = (aggs: CreateAggConfigParams[]) => { + const getAggConfigs = (aggs: Array>) => { const indexPattern = { id: '1234', title: 'logstash-*', @@ -43,7 +42,7 @@ describe('AggConfig Filters', () => { indexPattern, }; - return new AggConfigs(indexPattern, aggs, { typesRegistry }); + return new AggConfigs(indexPattern, aggs, null); }; it('should return a match_phrase filter for terms', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/date_histogram.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/date_histogram.ts index a5368135728d49..dc0f9baa6d0cc7 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/date_histogram.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/date_histogram.ts @@ -21,7 +21,8 @@ import _ from 'lodash'; import moment from 'moment-timezone'; import { i18n } from '@kbn/i18n'; -// TODO need to move TimeBuckets +import { npStart } from 'ui/new_platform'; +import { timefilter } from 'ui/timefilter'; import { TimeBuckets } from 'ui/time_buckets'; import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; @@ -32,8 +33,6 @@ import { writeParams } from '../agg_params'; import { isMetricAggType } from '../metrics/metric_agg_type'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getQueryService, getUiSettings } from '../../../../../../../plugins/data/public/services'; const detectedTimezone = moment.tz.guess(); const tzOffset = moment().format('Z'); @@ -41,7 +40,6 @@ const tzOffset = moment().format('Z'); const getInterval = (agg: IBucketAggConfig): string => _.get(agg, ['params', 'interval']); export const setBounds = (agg: IBucketDateHistogramAggConfig, force?: boolean) => { - const { timefilter } = getQueryService().timefilter; if (agg.buckets._alreadySet && !force) return; agg.buckets._alreadySet = true; const bounds = agg.params.timeRange ? timefilter.calculateBounds(agg.params.timeRange) : null; @@ -223,7 +221,7 @@ export const dateHistogramBucketAgg = new BucketAggType { - beforeEach(() => { - mockDataServices(); - }); +import { npStart } from 'ui/new_platform'; - const typesRegistry = mockAggTypesRegistry([dateRangeBucketAgg]); +jest.mock('ui/new_platform'); +describe('date_range params', () => { const getAggConfigs = (params: Record = {}, hasIncludeTypeMeta: boolean = true) => { const field = { name: 'bytes', @@ -67,7 +58,7 @@ describe('date_range params', () => { params, }, ], - { typesRegistry } + null ); }; @@ -104,11 +95,7 @@ describe('date_range params', () => { }); it('should use the Kibana time_zone if no parameter specified', () => { - const core = coreMock.createStart(); - setUiSettings({ - ...core.uiSettings, - get: () => 'kibanaTimeZone' as any, - }); + npStart.core.uiSettings.get = jest.fn(() => 'kibanaTimeZone' as any); const aggConfigs = getAggConfigs( { @@ -119,8 +106,6 @@ describe('date_range params', () => { const dateRange = aggConfigs.aggs[0]; const params = dateRange.toDsl()[BUCKET_TYPES.DATE_RANGE]; - setUiSettings(core.uiSettings); // clean up - expect(params.time_zone).toBe('kibanaTimeZone'); }); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/date_range.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/date_range.ts index 933cdd0577f8da..1dc24ca80035c0 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/date_range.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/date_range.ts @@ -16,20 +16,18 @@ * specific language governing permissions and limitations * under the License. */ - import { get } from 'lodash'; import moment from 'moment-timezone'; import { i18n } from '@kbn/i18n'; +import { npStart } from 'ui/new_platform'; +import { convertDateRangeToString, DateRangeKey } from './lib/date_range'; import { BUCKET_TYPES } from './bucket_agg_types'; import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type'; import { createFilterDateRange } from './create_filter/date_range'; import { KBN_FIELD_TYPES, fieldFormats } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getFieldFormats, getUiSettings } from '../../../../../../../plugins/data/public/services'; -import { convertDateRangeToString, DateRangeKey } from './lib/date_range'; -export { convertDateRangeToString, DateRangeKey }; // for BWC +export { convertDateRangeToString, DateRangeKey }; const dateRangeTitle = i18n.translate('data.search.aggs.buckets.dateRangeTitle', { defaultMessage: 'Date Range', @@ -43,7 +41,7 @@ export const dateRangeBucketAgg = new BucketAggType({ return { from, to }; }, getFormat(agg) { - const fieldFormatsService = getFieldFormats(); + const fieldFormatsService = npStart.plugins.data.fieldFormats; const formatter = agg.fieldOwnFormatter( fieldFormats.TEXT_CONTEXT_TYPE, @@ -94,7 +92,7 @@ export const dateRangeBucketAgg = new BucketAggType({ ]); } if (!tz) { - const config = getUiSettings(); + const config = npStart.core.uiSettings; const detectedTimezone = moment.tz.guess(); const tzOffset = moment().format('Z'); const isDefaultTimezone = config.isDefault('dateFormat:tz'); diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/filter.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/filter.ts index 80efc0cf92071d..b52e2d6cfd4df4 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/filter.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/filter.ts @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import { i18n } from '@kbn/i18n'; import { BucketAggType } from './_bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/filters.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/filters.ts index 2852f3e4bdf464..6eaf788b83c04a 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/filters.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/filters.ts @@ -18,21 +18,19 @@ */ import _ from 'lodash'; +import angular from 'angular'; + import { i18n } from '@kbn/i18n'; import chrome from 'ui/chrome'; - import { createFilterFilters } from './create_filter/filters'; -import { toAngularJSON } from '../utils'; import { BucketAggType } from './_bucket_agg_type'; -import { BUCKET_TYPES } from './bucket_agg_types'; import { Storage } from '../../../../../../../plugins/kibana_utils/public'; - import { getQueryLog, esQuery, Query } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getUiSettings } from '../../../../../../../plugins/data/public/services'; +import { BUCKET_TYPES } from './bucket_agg_types'; const config = chrome.getUiSettingsClient(); +const storage = new Storage(window.localStorage); const filtersTitle = i18n.translate('data.search.aggs.buckets.filtersTitle', { defaultMessage: 'Filters', @@ -54,17 +52,15 @@ export const filtersBucketAgg = new BucketAggType({ params: [ { name: 'filters', - // TODO need to get rid of reference to `config` below default: [{ input: { query: '', language: config.get('search:queryLanguage') }, label: '' }], write(aggConfig, output) { - const uiSettings = getUiSettings(); const inFilters: FilterValue[] = aggConfig.params.filters; if (!_.size(inFilters)) return; inFilters.forEach(filter => { const persistedLog = getQueryLog( - uiSettings, - new Storage(window.localStorage), + config, + storage, 'vis_default_editor', filter.input.language ); @@ -81,13 +77,7 @@ export const filtersBucketAgg = new BucketAggType({ return; } - const esQueryConfigs = esQuery.getEsQueryConfig(uiSettings); - const query = esQuery.buildEsQuery( - aggConfig.getIndexPattern(), - [input], - [], - esQueryConfigs - ); + const query = esQuery.buildEsQuery(aggConfig.getIndexPattern(), [input], [], config); if (!query) { console.log('malformed filter agg params, missing "query" on input'); // eslint-disable-line no-console @@ -100,7 +90,7 @@ export const filtersBucketAgg = new BucketAggType({ matchAllLabel || (typeof filter.input.query === 'string' ? filter.input.query - : toAngularJSON(filter.input.query)); + : angular.toJson(filter.input.query)); filters[label] = { query }; }, {} diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_hash.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_hash.test.ts index 09dd03c759155e..f0ad5954764867 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_hash.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_hash.test.ts @@ -19,13 +19,12 @@ import { geoHashBucketAgg } from './geo_hash'; import { AggConfigs, IAggConfigs } from '../agg_configs'; -import { mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; import { IBucketAggConfig } from './_bucket_agg_type'; +jest.mock('ui/new_platform'); + describe('Geohash Agg', () => { - // const typesRegistry = mockAggTypesRegistry([geoHashBucketAgg]); - const typesRegistry = mockAggTypesRegistry(); const getAggConfigs = (params?: Record) => { const indexPattern = { id: '1234', @@ -63,7 +62,7 @@ describe('Geohash Agg', () => { }, }, ], - { typesRegistry } + null ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_tile.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_tile.ts index 9142a30338163c..57e8f6e8c5ded4 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_tile.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/geo_tile.ts @@ -19,6 +19,7 @@ import { i18n } from '@kbn/i18n'; import { noop } from 'lodash'; +import { AggConfigOptions } from '../agg_config'; import { BucketAggType } from './_bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; @@ -56,7 +57,7 @@ export const geoTileBucketAgg = new BucketAggType({ aggs.push(agg); if (useGeocentroid) { - const aggConfig = { + const aggConfig: AggConfigOptions = { type: METRIC_TYPES.GEO_CENTROID, enabled: true, params: { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.test.ts index 11dc8e42fd6538..4e89d7db1ff647 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.test.ts @@ -17,23 +17,16 @@ * under the License. */ -import { AggConfigs } from '../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; +import { npStart } from 'ui/new_platform'; +import { AggConfigs } from '../index'; import { BUCKET_TYPES } from './bucket_agg_types'; import { IBucketHistogramAggConfig, histogramBucketAgg, AutoBounds } from './histogram'; import { BucketAggType } from './_bucket_agg_type'; -import { coreMock } from '../../../../../../../../src/core/public/mocks'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { setUiSettings } from '../../../../../../../plugins/data/public/services'; -describe('Histogram Agg', () => { - beforeEach(() => { - mockDataServices(); - }); +jest.mock('ui/new_platform'); - const typesRegistry = mockAggTypesRegistry([histogramBucketAgg]); - - const getAggConfigs = (params: Record) => { +describe('Histogram Agg', () => { + const getAggConfigs = (params: Record = {}) => { const indexPattern = { id: '1234', title: 'logstash-*', @@ -52,13 +45,16 @@ describe('Histogram Agg', () => { indexPattern, [ { + field: { + name: 'field', + }, id: 'test', type: BUCKET_TYPES.HISTOGRAM, schema: 'segment', params, }, ], - { typesRegistry } + null ); }; @@ -162,15 +158,10 @@ describe('Histogram Agg', () => { aggConfig.setAutoBounds(autoBounds); } - const core = coreMock.createStart(); - setUiSettings({ - ...core.uiSettings, - get: () => maxBars as any, - }); + // mock histogram:maxBars value; + npStart.core.uiSettings.get = jest.fn(() => maxBars as any); - const interval = aggConfig.write(aggConfigs).params; - setUiSettings(core.uiSettings); // clean up - return interval; + return aggConfig.write(aggConfigs).params; }; it('will respect the histogram:maxBars setting', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.ts index 70df2f230db094..f7e9ef45961e04 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/histogram.ts @@ -19,13 +19,13 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; +import { toastNotifications } from 'ui/notify'; +import { npStart } from 'ui/new_platform'; import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type'; import { createFilterHistogram } from './create_filter/histogram'; -import { BUCKET_TYPES } from './bucket_agg_types'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getNotifications, getUiSettings } from '../../../../../../../plugins/data/public/services'; +import { BUCKET_TYPES } from './bucket_agg_types'; export interface AutoBounds { min: number; @@ -37,6 +37,8 @@ export interface IBucketHistogramAggConfig extends IBucketAggConfig { getAutoBounds: () => AutoBounds; } +const getUIConfig = () => npStart.core.uiSettings; + export const histogramBucketAgg = new BucketAggType({ name: BUCKET_TYPES.HISTOGRAM, title: i18n.translate('data.search.aggs.buckets.histogramTitle', { @@ -114,7 +116,7 @@ export const histogramBucketAgg = new BucketAggType({ }) .catch((e: Error) => { if (e.name === 'AbortError') return; - getNotifications().toasts.addWarning( + toastNotifications.addWarning( i18n.translate('data.search.aggs.histogram.missingMaxMinValuesWarning', { defaultMessage: 'Unable to retrieve max and min values to auto-scale histogram buckets. This may lead to poor visualization performance.', @@ -134,7 +136,7 @@ export const histogramBucketAgg = new BucketAggType({ const range = autoBounds.max - autoBounds.min; const bars = range / interval; - const config = getUiSettings(); + const config = getUIConfig(); if (bars > config.get('histogram:maxBars')) { const minInterval = range / config.get('histogram:maxBars'); diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/ip_range.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/ip_range.ts index 3fb464d8fa7a8b..91bdf53e7f8091 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/ip_range.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/ip_range.ts @@ -19,17 +19,15 @@ import { noop, map, omit, isNull } from 'lodash'; import { i18n } from '@kbn/i18n'; +import { npStart } from 'ui/new_platform'; +import { IpRangeKey, convertIPRangeToString } from './lib/ip_range'; import { BucketAggType } from './_bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; +// @ts-ignore import { createFilterIpRange } from './create_filter/ip_range'; import { KBN_FIELD_TYPES, fieldFormats } from '../../../../../../../plugins/data/public'; - -import { IpRangeKey, convertIPRangeToString } from './lib/ip_range'; -export { IpRangeKey, convertIPRangeToString }; // for BWC - -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; +export { IpRangeKey, convertIPRangeToString }; const ipRangeTitle = i18n.translate('data.search.aggs.buckets.ipRangeTitle', { defaultMessage: 'IPv4 Range', @@ -46,7 +44,7 @@ export const ipRangeBucketAgg = new BucketAggType({ return { type: 'range', from: bucket.from, to: bucket.to }; }, getFormat(agg) { - const fieldFormatsService = getFieldFormats(); + const fieldFormatsService = npStart.plugins.data.fieldFormats; const formatter = agg.fieldOwnFormatter( fieldFormats.TEXT_CONTEXT_TYPE, fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.IP) diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts index d94477b588f8d1..77e84e044de55a 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts @@ -19,10 +19,10 @@ import { isString, isObject } from 'lodash'; import { IBucketAggConfig, BucketAggType, BucketAggParam } from './_bucket_agg_type'; -import { IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; export const isType = (type: string) => { - return (agg: IAggConfig): boolean => { + return (agg: AggConfig): boolean => { const field = agg.params.field; return field && field.type === type; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/range.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/range.test.ts index 096b19fe7de66d..b1b0c4bc30a58e 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/range.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/range.test.ts @@ -17,12 +17,12 @@ * under the License. */ -import { rangeBucketAgg } from './range'; import { AggConfigs } from '../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; import { BUCKET_TYPES } from './bucket_agg_types'; import { FieldFormatsGetConfigFn, fieldFormats } from '../../../../../../../plugins/data/public'; +jest.mock('ui/new_platform'); + const buckets = [ { to: 1024, @@ -44,12 +44,6 @@ const buckets = [ ]; describe('Range Agg', () => { - beforeEach(() => { - mockDataServices(); - }); - - const typesRegistry = mockAggTypesRegistry([rangeBucketAgg]); - const getConfig = (() => {}) as FieldFormatsGetConfigFn; const getAggConfigs = () => { const field = { @@ -86,7 +80,7 @@ describe('Range Agg', () => { }, }, ], - { typesRegistry } + null ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/significant_terms.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/significant_terms.test.ts index cee3ed506c29c4..37b829bfc20fb2 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/significant_terms.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/significant_terms.test.ts @@ -17,16 +17,17 @@ * under the License. */ -import { AggConfigs, IAggConfigs } from '../agg_configs'; -import { mockAggTypesRegistry } from '../test_helpers'; +import { AggConfigs } from '../index'; +import { IAggConfigs } from '../types'; import { BUCKET_TYPES } from './bucket_agg_types'; import { significantTermsBucketAgg } from './significant_terms'; import { IBucketAggConfig } from './_bucket_agg_type'; +jest.mock('ui/new_platform'); + describe('Significant Terms Agg', () => { describe('order agg editor UI', () => { describe('convert include/exclude from old format', () => { - const typesRegistry = mockAggTypesRegistry([significantTermsBucketAgg]); const getAggConfigs = (params: Record = {}) => { const indexPattern = { id: '1234', @@ -52,7 +53,7 @@ describe('Significant Terms Agg', () => { params, }, ], - { typesRegistry } + null ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/buckets/terms.test.ts b/src/legacy/core_plugins/data/public/search/aggs/buckets/terms.test.ts index 9a4f28afd3edf2..24ac332ae4d55c 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/buckets/terms.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/buckets/terms.test.ts @@ -17,13 +17,13 @@ * under the License. */ -import { AggConfigs } from '../agg_configs'; -import { mockAggTypesRegistry } from '../test_helpers'; +import { AggConfigs } from '../index'; import { BUCKET_TYPES } from './bucket_agg_types'; +jest.mock('ui/new_platform'); + describe('Terms Agg', () => { describe('order agg editor UI', () => { - const typesRegistry = mockAggTypesRegistry(); const getAggConfigs = (params: Record = {}) => { const indexPattern = { id: '1234', @@ -48,7 +48,7 @@ describe('Terms Agg', () => { type: BUCKET_TYPES.TERMS, }, ], - { typesRegistry } + null ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.test.ts b/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.test.ts index 0de1c31d02f961..cc1288d339692f 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.test.ts @@ -19,12 +19,13 @@ import { IndexPattern } from '../../../../../../../plugins/data/public'; import { AggTypeFilters } from './agg_type_filters'; -import { IAggConfig, IAggType } from '../types'; +import { AggConfig } from '..'; +import { IAggType } from '../types'; describe('AggTypeFilters', () => { let registry: AggTypeFilters; const indexPattern = ({ id: '1234', fields: [], title: 'foo' } as unknown) as IndexPattern; - const aggConfig = {} as IAggConfig; + const aggConfig = {} as AggConfig; beforeEach(() => { registry = new AggTypeFilters(); diff --git a/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.ts b/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.ts index 13a4cc0856b090..d3b38ce041d7ee 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/filter/agg_type_filters.ts @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import { IndexPattern } from 'src/plugins/data/public'; import { IAggConfig, IAggType } from '../types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/filter/prop_filter.test.ts b/src/legacy/core_plugins/data/public/search/aggs/filter/prop_filter.test.ts index 32cda7b950e93d..431e1161e0dbdf 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/filter/prop_filter.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/filter/prop_filter.test.ts @@ -17,6 +17,7 @@ * under the License. */ +import expect from '@kbn/expect'; import { propFilter } from './prop_filter'; describe('prop filter', () => { @@ -46,48 +47,48 @@ describe('prop filter', () => { it('returns list when no filters are provided', () => { const objects = getObjects('table', 'table', 'pie'); - expect(nameFilter(objects)).toEqual(objects); + expect(nameFilter(objects)).to.eql(objects); }); it('returns list when empty list of filters is provided', () => { const objects = getObjects('table', 'table', 'pie'); - expect(nameFilter(objects, [])).toEqual(objects); + expect(nameFilter(objects, [])).to.eql(objects); }); it('should keep only the tables', () => { const objects = getObjects('table', 'table', 'pie'); - expect(nameFilter(objects, 'table')).toEqual(getObjects('table', 'table')); + expect(nameFilter(objects, 'table')).to.eql(getObjects('table', 'table')); }); it('should support comma-separated values', () => { const objects = getObjects('table', 'line', 'pie'); - expect(nameFilter(objects, 'table,line')).toEqual(getObjects('table', 'line')); + expect(nameFilter(objects, 'table,line')).to.eql(getObjects('table', 'line')); }); it('should support an array of values', () => { const objects = getObjects('table', 'line', 'pie'); - expect(nameFilter(objects, ['table', 'line'])).toEqual(getObjects('table', 'line')); + expect(nameFilter(objects, ['table', 'line'])).to.eql(getObjects('table', 'line')); }); it('should return all objects', () => { const objects = getObjects('table', 'line', 'pie'); - expect(nameFilter(objects, '*')).toEqual(objects); + expect(nameFilter(objects, '*')).to.eql(objects); }); it('should allow negation', () => { const objects = getObjects('table', 'line', 'pie'); - expect(nameFilter(objects, ['!line'])).toEqual(getObjects('table', 'pie')); + expect(nameFilter(objects, ['!line'])).to.eql(getObjects('table', 'pie')); }); it('should support a function for specifying what should be kept', () => { const objects = getObjects('table', 'line', 'pie'); const line = (value: string) => value === 'line'; - expect(nameFilter(objects, line)).toEqual(getObjects('line')); + expect(nameFilter(objects, line)).to.eql(getObjects('line')); }); it('gracefully handles a filter function with zero arity', () => { const objects = getObjects('table', 'line', 'pie'); const rejectEverything = () => false; - expect(nameFilter(objects, rejectEverything)).toEqual([]); + expect(nameFilter(objects, rejectEverything)).to.eql([]); }); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/index.test.ts b/src/legacy/core_plugins/data/public/search/aggs/index.test.ts index 4d0cd55b09d533..a867769a77fc1d 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/index.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/index.test.ts @@ -25,6 +25,8 @@ import { isMetricAggType } from './metrics/metric_agg_type'; const bucketAggs = aggTypes.buckets; const metricAggs = aggTypes.metrics; +jest.mock('ui/new_platform'); + describe('AggTypesComponent', () => { describe('bucket aggs', () => { it('all extend BucketAggType', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/index.ts b/src/legacy/core_plugins/data/public/search/aggs/index.ts index f6914c36f6c05c..0bdb92b8de65e8 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/index.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/index.ts @@ -17,13 +17,8 @@ * under the License. */ -export { - AggTypesRegistry, - AggTypesRegistrySetup, - AggTypesRegistryStart, -} from './agg_types_registry'; -export { AggType } from './agg_type'; export { aggTypes } from './agg_types'; +export { AggType } from './agg_type'; export { AggConfig } from './agg_config'; export { AggConfigs } from './agg_configs'; export { FieldParamType } from './param_types'; @@ -57,4 +52,4 @@ export { METRIC_TYPES } from './metrics/metric_agg_types'; export { ISchemas, Schema, Schemas } from './schemas'; // types -export { CreateAggConfigParams, IAggConfig, IAggConfigs } from './types'; +export { IAggConfig, IAggConfigs } from './types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_avg.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_avg.ts index 11bb5592747297..9fb28f8631bc63 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_avg.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_avg.ts @@ -19,6 +19,7 @@ import { i18n } from '@kbn/i18n'; import { get } from 'lodash'; + import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_max.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_max.ts index 0668a9bcf57a8f..83837f0de51146 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_max.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_max.ts @@ -18,6 +18,7 @@ */ import { i18n } from '@kbn/i18n'; + import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; import { siblingPipelineAggHelper } from './lib/sibling_pipeline_agg_helper'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_min.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_min.ts index 8f728cb5e7e426..d96197693dc2ee 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_min.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/bucket_min.ts @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { makeNestedLabel } from './lib/make_nested_label'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/cardinality.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/cardinality.ts index 4f7b6e555ca33e..147e9255210887 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/cardinality.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/cardinality.ts @@ -18,11 +18,10 @@ */ import { i18n } from '@kbn/i18n'; +import { npStart } from 'ui/new_platform'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; const uniqueCountTitle = i18n.translate('data.search.aggs.metrics.uniqueCountTitle', { defaultMessage: 'Unique Count', @@ -38,7 +37,7 @@ export const cardinalityMetricAgg = new MetricAggType({ }); }, getFormat() { - const fieldFormatsService = getFieldFormats(); + const fieldFormatsService = npStart.plugins.data.fieldFormats; return fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); }, diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/count.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/count.ts index 8b3e0a488c68a1..14a9bd073ff2bc 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/count.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/count.ts @@ -18,11 +18,10 @@ */ import { i18n } from '@kbn/i18n'; +import { npStart } from 'ui/new_platform'; +import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; -import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; export const countMetricAgg = new MetricAggType({ name: METRIC_TYPES.COUNT, @@ -36,7 +35,7 @@ export const countMetricAgg = new MetricAggType({ }); }, getFormat() { - const fieldFormatsService = getFieldFormats(); + const fieldFormatsService = npStart.plugins.data.fieldFormats; return fieldFormatsService.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); }, diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/get_response_agg_config_class.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/get_response_agg_config_class.ts index 00d866e6f2b3ed..054543de3dd067 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/get_response_agg_config_class.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/get_response_agg_config_class.ts @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import { assign } from 'lodash'; import { IMetricAggConfig } from '../metric_agg_type'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts index 88549ee3019ee6..e24aca08271c72 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/parent_pipeline_agg_helper.ts @@ -23,6 +23,7 @@ import { noop, identity } from 'lodash'; import { forwardModifyAggConfigOnSearchRequestStart } from './nested_agg_helpers'; import { IMetricAggConfig, MetricAggParam } from '../metric_agg_type'; import { parentPipelineAggWriter } from './parent_pipeline_agg_writer'; + import { Schemas } from '../../schemas'; import { fieldFormats } from '../../../../../../../../plugins/data/public'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts index 05e009cc9da30e..e7c98e575fdb4f 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/lib/sibling_pipeline_agg_helper.ts @@ -21,6 +21,7 @@ import { identity } from 'lodash'; import { i18n } from '@kbn/i18n'; import { siblingPipelineAggWriter } from './sibling_pipeline_agg_writer'; import { forwardModifyAggConfigOnSearchRequestStart } from './nested_agg_helpers'; + import { IMetricAggConfig, MetricAggParam } from '../metric_agg_type'; import { Schemas } from '../../schemas'; import { fieldFormats } from '../../../../../../../../plugins/data/public'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/median.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/median.test.ts index ad55837ec9a300..4755a873e69779 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/median.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/median.test.ts @@ -17,16 +17,15 @@ * under the License. */ -import { medianMetricAgg } from './median'; import { AggConfigs, IAggConfigs } from '../agg_configs'; -import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; +jest.mock('ui/new_platform'); + describe('AggTypeMetricMedianProvider class', () => { let aggConfigs: IAggConfigs; beforeEach(() => { - const typesRegistry = mockAggTypesRegistry([medianMetricAgg]); const field = { name: 'bytes', }; @@ -51,7 +50,7 @@ describe('AggTypeMetricMedianProvider class', () => { }, }, ], - { typesRegistry } + null ); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/median.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/median.ts index 68fc98261118c2..53a5ffff418f10 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/median.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/median.ts @@ -16,10 +16,12 @@ * specific language governing permissions and limitations * under the License. */ - import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; + +// @ts-ignore +import { percentilesMetricAgg } from './percentiles'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; const medianTitle = i18n.translate('data.search.aggs.metrics.medianTitle', { diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/metric_agg_type.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/metric_agg_type.ts index 952dcc96de8330..3bae7b92618dcd 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/metric_agg_type.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/metric_agg_type.ts @@ -18,14 +18,13 @@ */ import { i18n } from '@kbn/i18n'; +import { npStart } from 'ui/new_platform'; import { AggType, AggTypeConfig } from '../agg_type'; import { AggParamType } from '../param_types/agg'; import { AggConfig } from '../agg_config'; -import { FilterFieldTypes } from '../param_types/field'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; +import { FilterFieldTypes } from '../param_types/field'; export interface IMetricAggConfig extends AggConfig { type: InstanceType; @@ -79,7 +78,7 @@ export class MetricAggType { - const fieldFormatsService = getFieldFormats(); + const fieldFormatsService = npStart.plugins.data.fieldFormats; const field = agg.getField(); return field ? field.format diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/min.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/min.ts index 1806c6d9d77107..48851051634356 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/min.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/min.ts @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import { i18n } from '@kbn/i18n'; import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts index 58b4ee530a8c2d..11fc39c20bdc42 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts @@ -17,12 +17,12 @@ * under the License. */ +import sinon from 'sinon'; import { derivativeMetricAgg } from './derivative'; import { cumulativeSumMetricAgg } from './cumulative_sum'; import { movingAvgMetricAgg } from './moving_avg'; import { serialDiffMetricAgg } from './serial_diff'; import { AggConfigs } from '../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; jest.mock('../schemas', () => { @@ -34,13 +34,9 @@ jest.mock('../schemas', () => { }; }); -describe('parent pipeline aggs', function() { - beforeEach(() => { - mockDataServices(); - }); - - const typesRegistry = mockAggTypesRegistry(); +jest.mock('ui/new_platform'); +describe('parent pipeline aggs', function() { const metrics = [ { name: 'derivative', title: 'Derivative', provider: derivativeMetricAgg }, { name: 'cumulative_sum', title: 'Cumulative Sum', provider: cumulativeSumMetricAgg }, @@ -98,7 +94,7 @@ describe('parent pipeline aggs', function() { schema: 'metric', }, ], - { typesRegistry } + null ); // Grab the aggConfig off the vis (we don't actually use the vis for anything else) @@ -224,16 +220,16 @@ describe('parent pipeline aggs', function() { }); const searchSource: any = {}; - const customMetricSpy = jest.fn(); + const customMetricSpy = sinon.spy(); const customMetric = aggConfig.params.customMetric; // Attach a modifyAggConfigOnSearchRequestStart with a spy to the first parameter customMetric.type.params[0].modifyAggConfigOnSearchRequestStart = customMetricSpy; aggConfig.type.params.forEach(param => { - param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource, {}); + param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource); }); - expect(customMetricSpy.mock.calls[0]).toEqual([customMetric, searchSource, {}]); + expect(customMetricSpy.calledWith(customMetric, searchSource)).toBe(true); }); }); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts index 628f1cd204ee5e..655e918ce07deb 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts @@ -19,16 +19,14 @@ import { IPercentileRanksAggConfig, percentileRanksMetricAgg } from './percentile_ranks'; import { AggConfigs, IAggConfigs } from '../agg_configs'; -import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; +jest.mock('ui/new_platform'); + describe('AggTypesMetricsPercentileRanksProvider class', function() { let aggConfigs: IAggConfigs; beforeEach(() => { - mockDataServices(); - - const typesRegistry = mockAggTypesRegistry([percentileRanksMetricAgg]); const field = { name: 'bytes', }; @@ -60,7 +58,7 @@ describe('AggTypesMetricsPercentileRanksProvider class', function() { }, }, ], - { typesRegistry } + null ); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.ts index 1d640a9c1fa42f..38b47a7e97d2f2 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentile_ranks.ts @@ -18,17 +18,20 @@ */ import { i18n } from '@kbn/i18n'; +import { npStart } from 'ui/new_platform'; import { MetricAggType } from './metric_agg_type'; import { getResponseAggConfigClass, IResponseAggConfig } from './lib/get_response_agg_config_class'; + import { getPercentileValue } from './percentiles_get_value'; import { METRIC_TYPES } from './metric_agg_types'; import { fieldFormats, KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getFieldFormats } from '../../../../../../../plugins/data/public/services'; // required by the values editor + export type IPercentileRanksAggConfig = IResponseAggConfig; +const getFieldFormats = () => npStart.plugins.data.fieldFormats; + const valueProps = { makeLabel(this: IPercentileRanksAggConfig) { const fieldFormatsService = getFieldFormats(); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.test.ts index e077bc0f8c7737..dd1aaca973e473 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.test.ts @@ -19,14 +19,14 @@ import { IPercentileAggConfig, percentilesMetricAgg } from './percentiles'; import { AggConfigs, IAggConfigs } from '../agg_configs'; -import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; +jest.mock('ui/new_platform'); + describe('AggTypesMetricsPercentilesProvider class', () => { let aggConfigs: IAggConfigs; beforeEach(() => { - const typesRegistry = mockAggTypesRegistry([percentilesMetricAgg]); const field = { name: 'bytes', }; @@ -58,7 +58,7 @@ describe('AggTypesMetricsPercentilesProvider class', () => { }, }, ], - { typesRegistry } + null ); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.ts index 49e927d07d8dd0..39dc0d0f181e92 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/percentiles.ts @@ -18,11 +18,15 @@ */ import { i18n } from '@kbn/i18n'; + import { MetricAggType } from './metric_agg_type'; import { METRIC_TYPES } from './metric_agg_types'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; + import { getResponseAggConfigClass, IResponseAggConfig } from './lib/get_response_agg_config_class'; import { getPercentileValue } from './percentiles_get_value'; + +// @ts-ignore import { ordinalSuffix } from './lib/ordinal_suffix'; export type IPercentileAggConfig = IResponseAggConfig; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts index d3456bacceb6ab..d643cf0d2a4781 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts @@ -17,6 +17,7 @@ * under the License. */ +import { spy } from 'sinon'; import { bucketSumMetricAgg } from './bucket_sum'; import { bucketAvgMetricAgg } from './bucket_avg'; import { bucketMinMetricAgg } from './bucket_min'; @@ -24,7 +25,6 @@ import { bucketMaxMetricAgg } from './bucket_max'; import { AggConfigs } from '../agg_configs'; import { IMetricAggConfig, MetricAggType } from './metric_agg_type'; -import { mockDataServices, mockAggTypesRegistry } from '../test_helpers'; jest.mock('../schemas', () => { class MockedSchemas { @@ -35,13 +35,9 @@ jest.mock('../schemas', () => { }; }); -describe('sibling pipeline aggs', () => { - beforeEach(() => { - mockDataServices(); - }); - - const typesRegistry = mockAggTypesRegistry(); +jest.mock('ui/new_platform'); +describe('sibling pipeline aggs', () => { const metrics = [ { name: 'sum_bucket', title: 'Overall Sum', provider: bucketSumMetricAgg }, { name: 'avg_bucket', title: 'Overall Average', provider: bucketAvgMetricAgg }, @@ -100,7 +96,7 @@ describe('sibling pipeline aggs', () => { }, }, ], - { typesRegistry } + null ); // Grab the aggConfig off the vis (we don't actually use the vis for anything else) @@ -166,8 +162,8 @@ describe('sibling pipeline aggs', () => { init(); const searchSource: any = {}; - const customMetricSpy = jest.fn(); - const customBucketSpy = jest.fn(); + const customMetricSpy = spy(); + const customBucketSpy = spy(); const { customMetric, customBucket } = aggConfig.params; // Attach a modifyAggConfigOnSearchRequestStart with a spy to the first parameter @@ -175,11 +171,11 @@ describe('sibling pipeline aggs', () => { customBucket.type.params[0].modifyAggConfigOnSearchRequestStart = customBucketSpy; aggConfig.type.params.forEach(param => { - param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource, {}); + param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource); }); - expect(customMetricSpy.mock.calls[0]).toEqual([customMetric, searchSource, {}]); - expect(customBucketSpy.mock.calls[0]).toEqual([customBucket, searchSource, {}]); + expect(customMetricSpy.calledWith(customMetric, searchSource)).toBe(true); + expect(customBucketSpy.calledWith(customBucket, searchSource)).toBe(true); }); }); }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/std_deviation.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/std_deviation.test.ts index 0679831b1e6ac8..3125026a521854 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/std_deviation.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/std_deviation.test.ts @@ -19,11 +19,11 @@ import { IStdDevAggConfig, stdDeviationMetricAgg } from './std_deviation'; import { AggConfigs } from '../agg_configs'; -import { mockAggTypesRegistry } from '../test_helpers'; import { METRIC_TYPES } from './metric_agg_types'; +jest.mock('ui/new_platform'); + describe('AggTypeMetricStandardDeviationProvider class', () => { - const typesRegistry = mockAggTypesRegistry([stdDeviationMetricAgg]); const getAggConfigs = (customLabel?: string) => { const field = { name: 'memory', @@ -52,7 +52,7 @@ describe('AggTypeMetricStandardDeviationProvider class', () => { }, }, ], - { typesRegistry } + null ); }; diff --git a/src/legacy/core_plugins/data/public/search/aggs/metrics/top_hit.test.ts b/src/legacy/core_plugins/data/public/search/aggs/metrics/top_hit.test.ts index ad1f42f5c563e6..a973de4fe8659e 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/metrics/top_hit.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/metrics/top_hit.test.ts @@ -20,10 +20,11 @@ import { dropRight, last } from 'lodash'; import { topHitMetricAgg } from './top_hit'; import { AggConfigs } from '../agg_configs'; -import { mockAggTypesRegistry } from '../test_helpers'; import { IMetricAggConfig } from './metric_agg_type'; import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; +jest.mock('ui/new_platform'); + describe('Top hit metric', () => { let aggDsl: Record; let aggConfig: IMetricAggConfig; @@ -36,7 +37,6 @@ describe('Top hit metric', () => { fieldType = KBN_FIELD_TYPES.NUMBER, size = 1, }: any) => { - const typesRegistry = mockAggTypesRegistry([topHitMetricAgg]); const field = { name: fieldName, displayName: fieldName, @@ -81,7 +81,7 @@ describe('Top hit metric', () => { params, }, ], - { typesRegistry } + null ); // Grab the aggConfig off the vis (we don't actually use the vis for anything else) diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/agg.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/agg.ts index d31abe64491d0d..2e7c11004b472e 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/agg.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/agg.ts @@ -17,10 +17,10 @@ * under the License. */ -import { AggConfig, IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; import { BaseParamType } from './base'; -export class AggParamType extends BaseParamType< +export class AggParamType extends BaseParamType< TAggConfig > { makeAgg: (agg: TAggConfig, state?: any) => TAggConfig; diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/base.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/base.ts index 95ad71a616ab27..1523cb03eb966c 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/base.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/base.ts @@ -18,10 +18,10 @@ */ import { IAggConfigs } from '../agg_configs'; -import { IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; import { FetchOptions, ISearchSource } from '../../../../../../../plugins/data/public'; -export class BaseParamType { +export class BaseParamType { name: string; type: string; displayName: string; diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/field.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/field.test.ts index 7338c41f920d72..fa88754ac60b94 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/field.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/field.test.ts @@ -25,6 +25,8 @@ import { IAggConfig } from '../agg_config'; import { IMetricAggConfig } from '../metrics/metric_agg_type'; import { Schema } from '../schemas'; +jest.mock('ui/new_platform'); + describe('Field', () => { const indexPattern = { id: '1234', diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/field.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/field.ts index bb5707cbb482ec..40c30f6210a833 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/field.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/field.ts @@ -19,6 +19,7 @@ import { i18n } from '@kbn/i18n'; import { isFunction } from 'lodash'; +import { npStart } from 'ui/new_platform'; import { IAggConfig } from '../agg_config'; import { SavedObjectNotFound } from '../../../../../../../plugins/kibana_utils/public'; import { BaseParamType } from './base'; @@ -29,8 +30,6 @@ import { indexPatterns, KBN_FIELD_TYPES, } from '../../../../../../../plugins/data/public'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { getNotifications } from '../../../../../../../plugins/data/public/services'; const filterByType = propFilter('type'); @@ -94,7 +93,7 @@ export class FieldParamType extends BaseParamType { // @ts-ignore const validField = this.getAvailableFields(aggConfig).find((f: any) => f.name === fieldName); if (!validField) { - getNotifications().toasts.addDanger( + npStart.core.notifications.toasts.addDanger( i18n.translate( 'data.search.aggs.paramTypes.field.invalidSavedFieldParameterErrorMessage', { diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.test.ts index 1a453a225797db..bc36bb46d3d166 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.test.ts @@ -17,26 +17,27 @@ * under the License. */ +import { IndexedArray } from 'ui/indexed_array'; import { AggTypeFieldFilters } from './field_filters'; -import { IAggConfig } from '../../agg_config'; +import { AggConfig } from '../../agg_config'; import { IndexPatternField } from '../../../../../../../../plugins/data/public'; describe('AggTypeFieldFilters', () => { let registry: AggTypeFieldFilters; - const aggConfig = {} as IAggConfig; + const aggConfig = {} as AggConfig; beforeEach(() => { registry = new AggTypeFieldFilters(); }); it('should filter nothing without registered filters', async () => { - const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexPatternField[]; + const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexedArray; const filtered = registry.filter(fields, aggConfig); expect(filtered).toEqual(fields); }); it('should pass all fields to the registered filter', async () => { - const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexPatternField[]; + const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexedArray; const filter = jest.fn(); registry.addFilter(filter); registry.filter(fields, aggConfig); @@ -45,7 +46,7 @@ describe('AggTypeFieldFilters', () => { }); it('should allow registered filters to filter out fields', async () => { - const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexPatternField[]; + const fields = [{ name: 'foo' }, { name: 'bar' }] as IndexedArray; let filtered = registry.filter(fields, aggConfig); expect(filtered).toEqual(fields); diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.ts index 1cbf0c9ae36245..7d1348ab5423be 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/filter/field_filters.ts @@ -17,9 +17,9 @@ * under the License. */ import { IndexPatternField } from 'src/plugins/data/public'; -import { IAggConfig } from '../../agg_config'; +import { AggConfig } from '../../agg_config'; -type AggTypeFieldFilter = (field: IndexPatternField, aggConfig: IAggConfig) => boolean; +type AggTypeFieldFilter = (field: IndexPatternField, aggConfig: AggConfig) => boolean; /** * A registry to store {@link AggTypeFieldFilter} which are used to filter down @@ -41,11 +41,11 @@ class AggTypeFieldFilters { /** * Returns the {@link any|fields} filtered by all registered filters. * - * @param fields An array of fields that will be filtered down by this registry. + * @param fields An IndexedArray of fields that will be filtered down by this registry. * @param aggConfig The aggConfig for which the returning list will be used. * @return A filtered list of the passed fields. */ - public filter(fields: IndexPatternField[], aggConfig: IAggConfig) { + public filter(fields: IndexPatternField[], aggConfig: AggConfig) { const allFilters = Array.from(this.filters); const allowedAggTypeFields = fields.filter(field => { const isAggTypeFieldAllowed = allFilters.every(filter => filter(field, aggConfig)); diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/json.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/json.test.ts index 12fd29b3a14527..827299814c62aa 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/json.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/json.test.ts @@ -19,11 +19,13 @@ import { BaseParamType } from './base'; import { JsonParamType } from './json'; -import { IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; + +jest.mock('ui/new_platform'); describe('JSON', function() { const paramName = 'json_test'; - let aggConfig: IAggConfig; + let aggConfig: AggConfig; let output: Record; const initAggParam = (config: Record = {}) => @@ -34,7 +36,7 @@ describe('JSON', function() { }); beforeEach(function() { - aggConfig = { params: {} } as IAggConfig; + aggConfig = { params: {} } as AggConfig; output = { params: {} }; }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/json.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/json.ts index bf85b3b890c358..771919b0bb56b9 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/json.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/json.ts @@ -19,7 +19,7 @@ import _ from 'lodash'; -import { IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; import { BaseParamType } from './base'; export class JsonParamType extends BaseParamType { @@ -29,7 +29,7 @@ export class JsonParamType extends BaseParamType { this.name = config.name || 'json'; if (!config.write) { - this.write = (aggConfig: IAggConfig, output: Record) => { + this.write = (aggConfig: AggConfig, output: Record) => { let paramJson; const param = aggConfig.params[this.name]; diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.test.ts index c03d6cdfa1c700..6b58d81914097c 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.test.ts @@ -20,6 +20,8 @@ import { BaseParamType } from './base'; import { OptionedParamType } from './optioned'; +jest.mock('ui/new_platform'); + describe('Optioned', () => { describe('constructor', () => { it('it is an instance of BaseParamType', () => { diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.ts index 9eb7ceda607117..5ffda3740af49f 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/optioned.ts @@ -17,14 +17,14 @@ * under the License. */ -import { IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; import { BaseParamType } from './base'; export interface OptionedValueProp { value: string; text: string; disabled?: boolean; - isCompatible: (agg: IAggConfig) => boolean; + isCompatible: (agg: AggConfig) => boolean; } export interface OptionedParamEditorProps { @@ -40,7 +40,7 @@ export class OptionedParamType extends BaseParamType { super(config); if (!config.write) { - this.write = (aggConfig: IAggConfig, output: Record) => { + this.write = (aggConfig: AggConfig, output: Record) => { output.params[this.name] = aggConfig.params[this.name].value; }; } diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/string.test.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/string.test.ts index 29ec9741611a37..fd5ccebde993eb 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/string.test.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/string.test.ts @@ -19,11 +19,13 @@ import { BaseParamType } from './base'; import { StringParamType } from './string'; -import { IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; + +jest.mock('ui/new_platform'); describe('String', function() { let paramName = 'json_test'; - let aggConfig: IAggConfig; + let aggConfig: AggConfig; let output: Record; const initAggParam = (config: Record = {}) => @@ -34,7 +36,7 @@ describe('String', function() { }); beforeEach(() => { - aggConfig = { params: {} } as IAggConfig; + aggConfig = { params: {} } as AggConfig; output = { params: {} }; }); diff --git a/src/legacy/core_plugins/data/public/search/aggs/param_types/string.ts b/src/legacy/core_plugins/data/public/search/aggs/param_types/string.ts index 750606eb8433bf..58ba99f8a6d636 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/param_types/string.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/param_types/string.ts @@ -17,7 +17,7 @@ * under the License. */ -import { IAggConfig } from '../agg_config'; +import { AggConfig } from '../agg_config'; import { BaseParamType } from './base'; export class StringParamType extends BaseParamType { @@ -25,7 +25,7 @@ export class StringParamType extends BaseParamType { super(config); if (!config.write) { - this.write = (aggConfig: IAggConfig, output: Record) => { + this.write = (aggConfig: AggConfig, output: Record) => { if (aggConfig.params[this.name] && aggConfig.params[this.name].length) { output.params[this.name] = aggConfig.params[this.name]; } diff --git a/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts b/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts deleted file mode 100644 index d6bb7938664932..00000000000000 --- a/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { AggTypesRegistry, AggTypesRegistryStart } from '../agg_types_registry'; -import { aggTypes } from '../agg_types'; -import { BucketAggType } from '../buckets/_bucket_agg_type'; -import { MetricAggType } from '../metrics/metric_agg_type'; - -/** - * Testing utility which creates a new instance of AggTypesRegistry, - * registers the provided agg types, and returns AggTypesRegistry.start() - * - * This is useful if your test depends on a certain agg type to be present - * in the registry. - * - * @param [types] - Optional array of AggTypes to register. - * If no value is provided, all default types will be registered. - * - * @internal - */ -export function mockAggTypesRegistry | MetricAggType>( - types?: T[] -): AggTypesRegistryStart { - const registry = new AggTypesRegistry(); - const registrySetup = registry.setup(); - - if (types) { - types.forEach(type => { - if (type instanceof BucketAggType) { - registrySetup.registerBucket(type); - } else if (type instanceof MetricAggType) { - registrySetup.registerMetric(type); - } - }); - } else { - aggTypes.buckets.forEach(type => registrySetup.registerBucket(type)); - aggTypes.metrics.forEach(type => registrySetup.registerMetric(type)); - } - - return registry.start(); -} diff --git a/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_data_services.ts b/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_data_services.ts deleted file mode 100644 index c4e78ab8f64226..00000000000000 --- a/src/legacy/core_plugins/data/public/search/aggs/test_helpers/mock_data_services.ts +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { coreMock } from '../../../../../../../../src/core/public/mocks'; -import { dataPluginMock } from '../../../../../../../plugins/data/public/mocks'; -import { searchStartMock } from '../../mocks'; -import { setSearchServiceShim } from '../../../services'; -import { - setFieldFormats, - setIndexPatterns, - setNotifications, - setOverlays, - setQueryService, - setSearchService, - setUiSettings, - // eslint-disable-next-line @kbn/eslint/no-restricted-paths -} from '../../../../../../../plugins/data/public/services'; - -/** - * Testing helper which calls all of the service setters used in the - * data plugin. Services are added using their provided mocks. - * - * @internal - */ -export function mockDataServices() { - const core = coreMock.createStart(); - const data = dataPluginMock.createStartContract(); - const searchShim = searchStartMock(); - - setSearchServiceShim(searchShim); - setFieldFormats(data.fieldFormats); - setIndexPatterns(data.indexPatterns); - setNotifications(core.notifications); - setOverlays(core.overlays); - setQueryService(data.query); - setSearchService(data.search); - setUiSettings(core.uiSettings); -} diff --git a/src/legacy/core_plugins/data/public/search/aggs/types.ts b/src/legacy/core_plugins/data/public/search/aggs/types.ts index 5d02f426b58967..2c918abf99fcaf 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/types.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/types.ts @@ -18,7 +18,7 @@ */ export { IAggConfig } from './agg_config'; -export { CreateAggConfigParams, IAggConfigs } from './agg_configs'; +export { IAggConfigs } from './agg_configs'; export { IAggType } from './agg_type'; export { AggParam, AggParamOption } from './agg_params'; export { IFieldParamType } from './param_types'; diff --git a/src/legacy/core_plugins/data/public/search/aggs/utils.test.tsx b/src/legacy/core_plugins/data/public/search/aggs/utils.test.tsx index c0662c98755a3d..a3c7f24f3927d8 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/utils.test.tsx +++ b/src/legacy/core_plugins/data/public/search/aggs/utils.test.tsx @@ -19,6 +19,8 @@ import { isValidJson } from './utils'; +jest.mock('ui/new_platform'); + const input = { valid: '{ "test": "json input" }', invalid: 'strings are not json', diff --git a/src/legacy/core_plugins/data/public/search/aggs/utils.ts b/src/legacy/core_plugins/data/public/search/aggs/utils.ts index 67ea373f438fb8..62f07ce44ab46e 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/utils.ts +++ b/src/legacy/core_plugins/data/public/search/aggs/utils.ts @@ -26,7 +26,7 @@ import { isValidEsInterval } from '../../../common'; * @param {string} value a string that should be validated * @returns {boolean} true if value is a valid JSON or if value is an empty string, or a string with whitespaces, otherwise false */ -export function isValidJson(value: string): boolean { +function isValidJson(value: string): boolean { if (!value || value.length === 0) { return true; } @@ -49,7 +49,7 @@ export function isValidJson(value: string): boolean { } } -export function isValidInterval(value: string, baseInterval?: string) { +function isValidInterval(value: string, baseInterval?: string) { if (baseInterval) { return _parseWithBase(value, baseInterval); } else { @@ -69,37 +69,4 @@ function _parseWithBase(value: string, baseInterval: string) { } } -// An inlined version of angular.toJSON() -// source: https://github.com/angular/angular.js/blob/master/src/Angular.js#L1312 -// @internal -export function toAngularJSON(obj: any, pretty?: any): string { - if (obj === undefined) return ''; - if (typeof pretty === 'number') { - pretty = pretty ? 2 : null; - } - return JSON.stringify(obj, toJsonReplacer, pretty); -} - -function isWindow(obj: any) { - return obj && obj.window === obj; -} - -function isScope(obj: any) { - return obj && obj.$evalAsync && obj.$watch; -} - -function toJsonReplacer(key: any, value: any) { - let val = value; - - if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { - val = undefined; - } else if (isWindow(value)) { - val = '$WINDOW'; - } else if (value && window.document === value) { - val = '$DOCUMENT'; - } else if (isScope(value)) { - val = '$SCOPE'; - } - - return val; -} +export { isValidJson, isValidInterval }; diff --git a/src/legacy/core_plugins/data/public/search/expressions/esaggs.ts b/src/legacy/core_plugins/data/public/search/expressions/esaggs.ts index 24dd1c4944bfba..7a5d927d0f219a 100644 --- a/src/legacy/core_plugins/data/public/search/expressions/esaggs.ts +++ b/src/legacy/core_plugins/data/public/search/expressions/esaggs.ts @@ -19,7 +19,7 @@ import { get, has } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { createAggConfigs, IAggConfigs } from 'ui/agg_types'; +import { AggConfigs, IAggConfigs } from 'ui/agg_types'; import { createFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; import { KibanaContext, @@ -258,7 +258,7 @@ export const esaggs = (): ExpressionFunctionDefinition { - const { aggs } = getSearchServiceShim(); - const aggConfigs = aggs.createAggConfigs(indexPattern); + const aggConfigs = new AggConfigs(indexPattern); const aggConfig = aggConfigs.createAggConfig({ enabled: true, type, diff --git a/src/legacy/core_plugins/data/public/search/mocks.ts b/src/legacy/core_plugins/data/public/search/mocks.ts deleted file mode 100644 index 86b6a928dc5b42..00000000000000 --- a/src/legacy/core_plugins/data/public/search/mocks.ts +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { SearchSetup, SearchStart } from './search_service'; -import { AggTypesRegistrySetup, AggTypesRegistryStart } from './aggs/agg_types_registry'; -import { AggConfigs } from './aggs/agg_configs'; -import { mockAggTypesRegistry } from './aggs/test_helpers'; - -const aggTypeBaseParamMock = () => ({ - name: 'some_param', - type: 'some_param_type', - displayName: 'some_agg_type_param', - required: false, - advanced: false, - default: {}, - write: jest.fn(), - serialize: jest.fn().mockImplementation(() => {}), - deserialize: jest.fn().mockImplementation(() => {}), - options: [], -}); - -const aggTypeConfigMock = () => ({ - name: 'some_name', - title: 'some_title', - params: [aggTypeBaseParamMock()], -}); - -export const aggTypesRegistrySetupMock = (): MockedKeys => ({ - registerBucket: jest.fn(), - registerMetric: jest.fn(), -}); - -export const aggTypesRegistryStartMock = (): MockedKeys => ({ - get: jest.fn().mockImplementation(aggTypeConfigMock), - getBuckets: jest.fn().mockImplementation(() => [aggTypeConfigMock()]), - getMetrics: jest.fn().mockImplementation(() => [aggTypeConfigMock()]), - getAll: jest.fn().mockImplementation(() => ({ - buckets: [aggTypeConfigMock()], - metrics: [aggTypeConfigMock()], - })), -}); - -export const searchSetupMock = (): MockedKeys => ({ - aggs: { - types: aggTypesRegistrySetupMock(), - }, -}); - -export const searchStartMock = (): MockedKeys => ({ - aggs: { - createAggConfigs: jest.fn().mockImplementation((indexPattern, configStates = [], schemas) => { - return new AggConfigs(indexPattern, configStates, { - schemas, - typesRegistry: mockAggTypesRegistry(), - }); - }), - types: mockAggTypesRegistry(), - __LEGACY: { - AggConfig: jest.fn() as any, - AggType: jest.fn(), - aggTypeFieldFilters: jest.fn() as any, - FieldParamType: jest.fn(), - MetricAggType: jest.fn(), - parentPipelineAggHelper: jest.fn() as any, - setBounds: jest.fn(), - siblingPipelineAggHelper: jest.fn() as any, - }, - }, -}); diff --git a/src/legacy/core_plugins/data/public/search/search_service.ts b/src/legacy/core_plugins/data/public/search/search_service.ts index 6754c0e3551af5..45f9ff17328adb 100644 --- a/src/legacy/core_plugins/data/public/search/search_service.ts +++ b/src/legacy/core_plugins/data/public/search/search_service.ts @@ -18,16 +18,11 @@ */ import { CoreSetup, CoreStart } from '../../../../../core/public'; -import { IndexPattern } from '../../../../../plugins/data/public'; import { aggTypes, AggType, - AggTypesRegistry, - AggTypesRegistrySetup, - AggTypesRegistryStart, AggConfig, AggConfigs, - CreateAggConfigParams, FieldParamType, MetricAggType, aggTypeFieldFilters, @@ -37,28 +32,20 @@ import { } from './aggs'; interface AggsSetup { - types: AggTypesRegistrySetup; + types: typeof aggTypes; } -interface AggsStartLegacy { +interface AggsStart { + types: typeof aggTypes; AggConfig: typeof AggConfig; + AggConfigs: typeof AggConfigs; AggType: typeof AggType; aggTypeFieldFilters: typeof aggTypeFieldFilters; FieldParamType: typeof FieldParamType; MetricAggType: typeof MetricAggType; parentPipelineAggHelper: typeof parentPipelineAggHelper; - setBounds: typeof setBounds; siblingPipelineAggHelper: typeof siblingPipelineAggHelper; -} - -interface AggsStart { - createAggConfigs: ( - indexPattern: IndexPattern, - configStates?: CreateAggConfigParams[], - schemas?: Record - ) => InstanceType; - types: AggTypesRegistryStart; - __LEGACY: AggsStartLegacy; + setBounds: typeof setBounds; } export interface SearchSetup { @@ -76,41 +63,28 @@ export interface SearchStart { * it will move into the existing search service in src/plugins/data/public/search */ export class SearchService { - private readonly aggTypesRegistry = new AggTypesRegistry(); - public setup(core: CoreSetup): SearchSetup { - const aggTypesSetup = this.aggTypesRegistry.setup(); - aggTypes.buckets.forEach(b => aggTypesSetup.registerBucket(b)); - aggTypes.metrics.forEach(m => aggTypesSetup.registerMetric(m)); - return { aggs: { - types: aggTypesSetup, + types: aggTypes, // TODO convert to registry + // TODO add other items as needed }, }; } public start(core: CoreStart): SearchStart { - const aggTypesStart = this.aggTypesRegistry.start(); return { aggs: { - createAggConfigs: (indexPattern, configStates = [], schemas) => { - return new AggConfigs(indexPattern, configStates, { - schemas, - typesRegistry: aggTypesStart, - }); - }, - types: aggTypesStart, - __LEGACY: { - AggConfig, // TODO make static - AggType, - aggTypeFieldFilters, - FieldParamType, - MetricAggType, - parentPipelineAggHelper, // TODO make static - setBounds, // TODO make static - siblingPipelineAggHelper, // TODO make static - }, + types: aggTypes, // TODO convert to registry + AggConfig, // TODO make static + AggConfigs, + AggType, + aggTypeFieldFilters, + FieldParamType, + MetricAggType, + parentPipelineAggHelper, // TODO make static + siblingPipelineAggHelper, // TODO make static + setBounds, // TODO make static }, }; } diff --git a/src/legacy/core_plugins/data/public/search/tabify/buckets.test.ts b/src/legacy/core_plugins/data/public/search/tabify/buckets.test.ts index 98048cb25db2fe..ef2748102623ab 100644 --- a/src/legacy/core_plugins/data/public/search/tabify/buckets.test.ts +++ b/src/legacy/core_plugins/data/public/search/tabify/buckets.test.ts @@ -20,6 +20,8 @@ import { TabifyBuckets } from './buckets'; import { AggGroupNames } from '../aggs'; +jest.mock('ui/new_platform'); + describe('Buckets wrapper', () => { const check = (aggResp: any, count: number, keys: string[]) => { test('reads the length', () => { diff --git a/src/legacy/core_plugins/data/public/search/tabify/get_columns.test.ts b/src/legacy/core_plugins/data/public/search/tabify/get_columns.test.ts index 6c5dc790ef9767..cfd4cd7de640b2 100644 --- a/src/legacy/core_plugins/data/public/search/tabify/get_columns.test.ts +++ b/src/legacy/core_plugins/data/public/search/tabify/get_columns.test.ts @@ -18,17 +18,12 @@ */ import { tabifyGetColumns } from './get_columns'; -import { TabbedAggColumn } from './types'; import { AggConfigs, AggGroupNames, Schemas } from '../aggs'; -import { mockAggTypesRegistry, mockDataServices } from '../aggs/test_helpers'; - -describe('get columns', () => { - beforeEach(() => { - mockDataServices(); - }); +import { TabbedAggColumn } from './types'; - const typesRegistry = mockAggTypesRegistry(); +jest.mock('ui/new_platform'); +describe('get columns', () => { const createAggConfigs = (aggs: any[] = []) => { const field = { name: '@timestamp', @@ -43,17 +38,18 @@ describe('get columns', () => { }, } as any; - return new AggConfigs(indexPattern, aggs, { - typesRegistry, - schemas: new Schemas([ + return new AggConfigs( + indexPattern, + aggs, + new Schemas([ { group: AggGroupNames.Metrics, name: 'metric', min: 1, defaults: [{ schema: 'metric', type: 'count' }], }, - ]).all, - }); + ]).all + ); }; test('should inject a count metric if no aggs exist', () => { diff --git a/src/legacy/core_plugins/data/public/search/tabify/response_writer.test.ts b/src/legacy/core_plugins/data/public/search/tabify/response_writer.test.ts index 94301eedac74a7..f5df0a683ca00c 100644 --- a/src/legacy/core_plugins/data/public/search/tabify/response_writer.test.ts +++ b/src/legacy/core_plugins/data/public/search/tabify/response_writer.test.ts @@ -19,19 +19,14 @@ import { TabbedAggResponseWriter } from './response_writer'; import { AggConfigs, AggGroupNames, Schemas, BUCKET_TYPES } from '../aggs'; -import { mockDataServices, mockAggTypesRegistry } from '../aggs/test_helpers'; import { TabbedResponseWriterOptions } from './types'; -describe('TabbedAggResponseWriter class', () => { - beforeEach(() => { - mockDataServices(); - }); +jest.mock('ui/new_platform'); +describe('TabbedAggResponseWriter class', () => { let responseWriter: TabbedAggResponseWriter; - const typesRegistry = mockAggTypesRegistry(); - const splitAggConfig = [ { type: BUCKET_TYPES.TERMS, @@ -71,17 +66,18 @@ describe('TabbedAggResponseWriter class', () => { } as any; return new TabbedAggResponseWriter( - new AggConfigs(indexPattern, aggs, { - typesRegistry, - schemas: new Schemas([ + new AggConfigs( + indexPattern, + aggs, + new Schemas([ { group: AggGroupNames.Metrics, name: 'metric', min: 1, defaults: [{ schema: 'metric', type: 'count' }], }, - ]).all, - }), + ]).all + ), { metricsAtAllLevels: false, partialRows: false, diff --git a/src/legacy/core_plugins/data/public/search/tabify/tabify.test.ts b/src/legacy/core_plugins/data/public/search/tabify/tabify.test.ts index db4ad3bdea96bd..13fe7719b0a856 100644 --- a/src/legacy/core_plugins/data/public/search/tabify/tabify.test.ts +++ b/src/legacy/core_plugins/data/public/search/tabify/tabify.test.ts @@ -20,12 +20,11 @@ import { IndexPattern } from '../../../../../../plugins/data/public'; import { tabifyAggResponse } from './tabify'; import { IAggConfig, IAggConfigs, AggGroupNames, Schemas, AggConfigs } from '../aggs'; -import { mockAggTypesRegistry } from '../aggs/test_helpers'; import { metricOnly, threeTermBuckets } from 'fixtures/fake_hierarchical_data'; -describe('tabifyAggResponse Integration', () => { - const typesRegistry = mockAggTypesRegistry(); +jest.mock('ui/new_platform'); +describe('tabifyAggResponse Integration', () => { const createAggConfigs = (aggs: IAggConfig[] = []) => { const field = { name: '@timestamp', @@ -40,17 +39,18 @@ describe('tabifyAggResponse Integration', () => { }, } as unknown) as IndexPattern; - return new AggConfigs(indexPattern, aggs, { - typesRegistry, - schemas: new Schemas([ + return new AggConfigs( + indexPattern, + aggs, + new Schemas([ { group: AggGroupNames.Metrics, name: 'metric', min: 1, defaults: [{ schema: 'metric', type: 'count' }], }, - ]).all, - }); + ]).all + ); }; const mockAggConfig = (agg: any): IAggConfig => (agg as unknown) as IAggConfig; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts index 6ae4e415f8caa8..6591aa5fb53d5f 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts @@ -20,8 +20,7 @@ import { cloneDeep } from 'lodash'; import { Vis, VisState } from 'src/legacy/core_plugins/visualizations/public'; - -import { createAggConfigs, IAggConfig, AggGroupNames } from '../../../legacy_imports'; +import { AggConfigs, IAggConfig, AggGroupNames } from '../../../legacy_imports'; import { EditorStateActionTypes } from './constants'; import { getEnabledMetricAggsCount } from '../../agg_group_helper'; import { EditorAction } from './actions'; @@ -33,8 +32,7 @@ function initEditorState(vis: Vis) { function editorStateReducer(state: VisState, action: EditorAction): VisState { switch (action.type) { case EditorStateActionTypes.ADD_NEW_AGG: { - const payloadAggConfig = action.payload as IAggConfig; - const aggConfig = state.aggs.createAggConfig(payloadAggConfig, { + const aggConfig = state.aggs.createAggConfig(action.payload as IAggConfig, { addToAggConfigs: false, }); aggConfig.brandNew = true; @@ -42,7 +40,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -65,7 +63,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -90,7 +88,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -131,7 +129,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -143,7 +141,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } @@ -165,7 +163,7 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { return { ...state, - aggs: createAggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), + aggs: new AggConfigs(state.aggs.indexPattern, newAggs, state.aggs.schemas), }; } diff --git a/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts b/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts index 8aed263c4e4d1d..832f73752a99b6 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts @@ -22,12 +22,12 @@ export { AggType, IAggType, IAggConfig, + AggConfigs, IAggConfigs, AggParam, AggGroupNames, aggGroupNamesMap, aggTypes, - createAggConfigs, FieldParamType, IFieldParamType, BUCKET_TYPES, diff --git a/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts b/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts index 736152c7014dc2..0e1e48d00a1b27 100644 --- a/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts +++ b/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts @@ -34,7 +34,7 @@ import { stubFields } from '../../../../plugins/data/public/stubs'; import { tableVisResponseHandler } from './table_vis_response_handler'; import { coreMock } from '../../../../core/public/mocks'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { createAggConfigs } from 'ui/agg_types'; +import { AggConfigs } from 'ui/agg_types'; import { tabifyAggResponse, IAggConfig } from './legacy_imports'; jest.mock('ui/new_platform'); @@ -113,7 +113,7 @@ describe('Table Vis - Controller', () => { return ({ type: tableVisTypeDefinition, params: Object.assign({}, tableVisTypeDefinition.visConfig.defaults, params), - aggs: createAggConfigs( + aggs: new AggConfigs( stubIndexPattern, [ { type: 'count', schema: 'metric' }, diff --git a/src/legacy/core_plugins/visualizations/public/legacy_imports.ts b/src/legacy/core_plugins/visualizations/public/legacy_imports.ts index 0a3b1938436c0e..fb7a157b53a9ac 100644 --- a/src/legacy/core_plugins/visualizations/public/legacy_imports.ts +++ b/src/legacy/core_plugins/visualizations/public/legacy_imports.ts @@ -18,10 +18,10 @@ */ export { + AggConfigs, IAggConfig, IAggConfigs, isDateHistogramBucketAggConfig, setBounds, } from '../../data/public'; -export { createAggConfigs } from 'ui/agg_types'; export { createSavedSearchesLoader } from '../../../../plugins/discover/public'; diff --git a/src/legacy/core_plugins/visualizations/public/np_ready/public/vis_impl.js b/src/legacy/core_plugins/visualizations/public/np_ready/public/vis_impl.js index 15a826cc6ddbe5..2f36322c67256a 100644 --- a/src/legacy/core_plugins/visualizations/public/np_ready/public/vis_impl.js +++ b/src/legacy/core_plugins/visualizations/public/np_ready/public/vis_impl.js @@ -30,7 +30,7 @@ import { EventEmitter } from 'events'; import _ from 'lodash'; import { PersistedState } from '../../../../../../../src/plugins/visualizations/public'; -import { createAggConfigs } from '../../legacy_imports'; +import { AggConfigs } from '../../legacy_imports'; import { updateVisualizationConfig } from './legacy/vis_update'; import { getTypes } from './services'; @@ -83,7 +83,7 @@ class VisImpl extends EventEmitter { updateVisualizationConfig(state.params, this.params); if (state.aggs || !this.aggs) { - this.aggs = createAggConfigs( + this.aggs = new AggConfigs( this.indexPattern, state.aggs ? state.aggs.aggs || state.aggs : [], this.type.schemas.all @@ -125,7 +125,7 @@ class VisImpl extends EventEmitter { copyCurrentState(includeDisabled = false) { const state = this.getCurrentState(includeDisabled); - state.aggs = createAggConfigs( + state.aggs = new AggConfigs( this.indexPattern, state.aggs.aggs || state.aggs, this.type.schemas.all diff --git a/src/legacy/ui/public/agg_types/index.ts b/src/legacy/ui/public/agg_types/index.ts index ffc300251c4bb3..ac5d0bed7ef153 100644 --- a/src/legacy/ui/public/agg_types/index.ts +++ b/src/legacy/ui/public/agg_types/index.ts @@ -27,19 +27,18 @@ import { start as dataStart } from '../../../core_plugins/data/public/legacy'; // runtime contracts -const { types } = dataStart.search.aggs; -export const aggTypes = types.getAll(); -export const { createAggConfigs } = dataStart.search.aggs; export const { + types: aggTypes, AggConfig, + AggConfigs, AggType, aggTypeFieldFilters, FieldParamType, MetricAggType, parentPipelineAggHelper, - setBounds, siblingPipelineAggHelper, -} = dataStart.search.aggs.__LEGACY; + setBounds, +} = dataStart.search.aggs; // types export { diff --git a/src/legacy/ui/public/vis/__tests__/_agg_config.js b/src/legacy/ui/public/vis/__tests__/_agg_config.js new file mode 100644 index 00000000000000..9e53044f681baa --- /dev/null +++ b/src/legacy/ui/public/vis/__tests__/_agg_config.js @@ -0,0 +1,485 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import sinon from 'sinon'; +import expect from '@kbn/expect'; +import ngMock from 'ng_mock'; +import { AggType, AggConfig } from '../../agg_types'; +import { start as visualizationsStart } from '../../../../core_plugins/visualizations/public/np_ready/public/legacy'; + +import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; + +describe('AggConfig', function() { + let indexPattern; + + beforeEach(ngMock.module('kibana')); + beforeEach( + ngMock.inject(function(Private) { + indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + }) + ); + + describe('#toDsl', function() { + it('calls #write()', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }); + + const aggConfig = vis.aggs.byName('date_histogram')[0]; + const stub = sinon.stub(aggConfig, 'write').returns({ params: {} }); + + aggConfig.toDsl(); + expect(stub.callCount).to.be(1); + }); + + it('uses the type name as the agg name', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }); + + const aggConfig = vis.aggs.byName('date_histogram')[0]; + sinon.stub(aggConfig, 'write').returns({ params: {} }); + + const dsl = aggConfig.toDsl(); + expect(dsl).to.have.property('date_histogram'); + }); + + it('uses the params from #write() output as the agg params', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }); + + const aggConfig = vis.aggs.byName('date_histogram')[0]; + const football = {}; + + sinon.stub(aggConfig, 'write').returns({ params: football }); + + const dsl = aggConfig.toDsl(); + expect(dsl.date_histogram).to.be(football); + }); + + it('includes subAggs from #write() output', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + type: 'avg', + schema: 'metric', + }, + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }); + + const histoConfig = vis.aggs.byName('date_histogram')[0]; + const avgConfig = vis.aggs.byName('avg')[0]; + const football = {}; + + sinon.stub(histoConfig, 'write').returns({ params: {}, subAggs: [avgConfig] }); + sinon.stub(avgConfig, 'write').returns({ params: football }); + + const dsl = histoConfig.toDsl(); + + // didn't use .eql() because of variable key names, and final check is strict + expect(dsl).to.have.property('aggs'); + expect(dsl.aggs).to.have.property(avgConfig.id); + expect(dsl.aggs[avgConfig.id]).to.have.property('avg'); + expect(dsl.aggs[avgConfig.id].avg).to.be(football); + }); + }); + + describe('::ensureIds', function() { + it('accepts an array of objects and assigns ids to them', function() { + const objs = [{}, {}, {}, {}]; + AggConfig.ensureIds(objs); + expect(objs[0]).to.have.property('id', '1'); + expect(objs[1]).to.have.property('id', '2'); + expect(objs[2]).to.have.property('id', '3'); + expect(objs[3]).to.have.property('id', '4'); + }); + + it('assigns ids relative to the other only item in the list', function() { + const objs = [{ id: '100' }, {}]; + AggConfig.ensureIds(objs); + expect(objs[0]).to.have.property('id', '100'); + expect(objs[1]).to.have.property('id', '101'); + }); + + it('assigns ids relative to the other items in the list', function() { + const objs = [{ id: '100' }, { id: '200' }, { id: '500' }, { id: '350' }, {}]; + AggConfig.ensureIds(objs); + expect(objs[0]).to.have.property('id', '100'); + expect(objs[1]).to.have.property('id', '200'); + expect(objs[2]).to.have.property('id', '500'); + expect(objs[3]).to.have.property('id', '350'); + expect(objs[4]).to.have.property('id', '501'); + }); + + it('uses ::nextId to get the starting value', function() { + sinon.stub(AggConfig, 'nextId').returns(534); + const objs = AggConfig.ensureIds([{}]); + AggConfig.nextId.restore(); + expect(objs[0]).to.have.property('id', '534'); + }); + + it('only calls ::nextId once', function() { + const start = 420; + sinon.stub(AggConfig, 'nextId').returns(start); + const objs = AggConfig.ensureIds([{}, {}, {}, {}, {}, {}, {}]); + + expect(AggConfig.nextId).to.have.property('callCount', 1); + + AggConfig.nextId.restore(); + objs.forEach(function(obj, i) { + expect(obj).to.have.property('id', String(start + i)); + }); + }); + }); + + describe('::nextId', function() { + it('accepts a list of objects and picks the next id', function() { + const next = AggConfig.nextId([{ id: 100 }, { id: 500 }]); + expect(next).to.be(501); + }); + + it('handles an empty list', function() { + const next = AggConfig.nextId([]); + expect(next).to.be(1); + }); + + it('fails when the list is not defined', function() { + expect(function() { + AggConfig.nextId(); + }).to.throwError(); + }); + }); + + describe('#toJsonDataEquals', function() { + const testsIdentical = [ + { + type: 'metric', + aggs: [ + { + type: 'count', + schema: 'metric', + params: { field: '@timestamp' }, + }, + ], + }, + { + type: 'histogram', + aggs: [ + { + type: 'avg', + schema: 'metric', + }, + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }, + ]; + + testsIdentical.forEach((visConfig, index) => { + it(`identical aggregations (${index})`, function() { + const vis1 = new visualizationsStart.Vis(indexPattern, visConfig); + const vis2 = new visualizationsStart.Vis(indexPattern, visConfig); + expect(vis1.aggs.jsonDataEquals(vis2.aggs.aggs)).to.be(true); + }); + }); + + const testsIdenticalDifferentOrder = [ + { + config1: { + type: 'histogram', + aggs: [ + { + type: 'avg', + schema: 'metric', + }, + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }, + config2: { + type: 'histogram', + aggs: [ + { + schema: 'metric', + type: 'avg', + }, + { + schema: 'segment', + type: 'date_histogram', + }, + ], + }, + }, + ]; + + testsIdenticalDifferentOrder.forEach((test, index) => { + it(`identical aggregations (${index}) - init json is in different order`, function() { + const vis1 = new visualizationsStart.Vis(indexPattern, test.config1); + const vis2 = new visualizationsStart.Vis(indexPattern, test.config2); + expect(vis1.aggs.jsonDataEquals(vis2.aggs.aggs)).to.be(true); + }); + }); + + const testsDifferent = [ + { + config1: { + type: 'histogram', + aggs: [ + { + type: 'avg', + schema: 'metric', + }, + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }, + config2: { + type: 'histogram', + aggs: [ + { + type: 'max', + schema: 'metric', + }, + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }, + }, + { + config1: { + type: 'metric', + aggs: [ + { + type: 'count', + schema: 'metric', + params: { field: '@timestamp' }, + }, + ], + }, + config2: { + type: 'metric', + aggs: [ + { + type: 'count', + schema: 'metric', + params: { field: '@timestamp' }, + }, + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }, + }, + ]; + + testsDifferent.forEach((test, index) => { + it(`different aggregations (${index})`, function() { + const vis1 = new visualizationsStart.Vis(indexPattern, test.config1); + const vis2 = new visualizationsStart.Vis(indexPattern, test.config2); + expect(vis1.aggs.jsonDataEquals(vis2.aggs.aggs)).to.be(false); + }); + }); + }); + + describe('#toJSON', function() { + it('includes the aggs id, params, type and schema', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }); + + const aggConfig = vis.aggs.byName('date_histogram')[0]; + expect(aggConfig.id).to.be('1'); + expect(aggConfig.params).to.be.an('object'); + expect(aggConfig.type) + .to.be.an(AggType) + .and.have.property('name', 'date_histogram'); + expect(aggConfig.schema) + .to.be.an('object') + .and.have.property('name', 'segment'); + + const state = aggConfig.toJSON(); + expect(state).to.have.property('id', '1'); + expect(state.params).to.be.an('object'); + expect(state).to.have.property('type', 'date_histogram'); + expect(state).to.have.property('schema', 'segment'); + }); + + it('test serialization order is identical (for visual consistency)', function() { + const vis1 = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + type: 'date_histogram', + schema: 'segment', + }, + ], + }); + const vis2 = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + schema: 'segment', + type: 'date_histogram', + }, + ], + }); + + //this relies on the assumption that js-engines consistently loop over properties in insertion order. + //most likely the case, but strictly speaking not guaranteed by the JS and JSON specifications. + expect(JSON.stringify(vis1.aggs.aggs) === JSON.stringify(vis2.aggs.aggs)).to.be(true); + }); + }); + + describe('#makeLabel', function() { + it('uses the custom label if it is defined', function() { + const vis = new visualizationsStart.Vis(indexPattern, {}); + const aggConfig = vis.aggs.aggs[0]; + aggConfig.params.customLabel = 'Custom label'; + const label = aggConfig.makeLabel(); + expect(label).to.be(aggConfig.params.customLabel); + }); + it('default label should be "Count"', function() { + const vis = new visualizationsStart.Vis(indexPattern, {}); + const aggConfig = vis.aggs.aggs[0]; + const label = aggConfig.makeLabel(); + expect(label).to.be('Count'); + }); + it('default label should be "Percentage of Count" when percentageMode is set to true', function() { + const vis = new visualizationsStart.Vis(indexPattern, {}); + const aggConfig = vis.aggs.aggs[0]; + const label = aggConfig.makeLabel(true); + expect(label).to.be('Percentage of Count'); + }); + it('empty label if the visualizationsStart.Vis type is not defined', function() { + const vis = new visualizationsStart.Vis(indexPattern, {}); + const aggConfig = vis.aggs.aggs[0]; + aggConfig.type = undefined; + const label = aggConfig.makeLabel(); + expect(label).to.be(''); + }); + }); + + describe('#fieldFormatter - custom getFormat handler', function() { + it('returns formatter from getFormat handler', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'metric', + aggs: [ + { + type: 'count', + schema: 'metric', + params: { field: '@timestamp' }, + }, + ], + }); + + const fieldFormatter = vis.aggs.aggs[0].fieldFormatter(); + + expect(fieldFormatter).to.be.defined; + expect(fieldFormatter('text')).to.be('text'); + }); + }); + + describe('#fieldFormatter - no custom getFormat handler', function() { + const visStateAggWithoutCustomGetFormat = { + aggs: [ + { + type: 'histogram', + schema: 'bucket', + params: { field: 'bytes' }, + }, + ], + }; + let vis; + + beforeEach(function() { + vis = new visualizationsStart.Vis(indexPattern, visStateAggWithoutCustomGetFormat); + }); + + it("returns the field's formatter", function() { + expect(vis.aggs.aggs[0].fieldFormatter().toString()).to.be( + vis.aggs.aggs[0] + .getField() + .format.getConverterFor() + .toString() + ); + }); + + it('returns the string format if the field does not have a format', function() { + const agg = vis.aggs.aggs[0]; + agg.params.field = { type: 'number', format: null }; + const fieldFormatter = agg.fieldFormatter(); + expect(fieldFormatter).to.be.defined; + expect(fieldFormatter('text')).to.be('text'); + }); + + it('returns the string format if their is no field', function() { + const agg = vis.aggs.aggs[0]; + delete agg.params.field; + const fieldFormatter = agg.fieldFormatter(); + expect(fieldFormatter).to.be.defined; + expect(fieldFormatter('text')).to.be('text'); + }); + + it('returns the html converter if "html" is passed in', function() { + const field = indexPattern.fields.getByName('bytes'); + expect(vis.aggs.aggs[0].fieldFormatter('html').toString()).to.be( + field.format.getConverterFor('html').toString() + ); + }); + }); +}); diff --git a/src/legacy/ui/public/vis/__tests__/_agg_configs.js b/src/legacy/ui/public/vis/__tests__/_agg_configs.js new file mode 100644 index 00000000000000..172523ec50c8b0 --- /dev/null +++ b/src/legacy/ui/public/vis/__tests__/_agg_configs.js @@ -0,0 +1,420 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import _ from 'lodash'; +import sinon from 'sinon'; +import expect from '@kbn/expect'; +import ngMock from 'ng_mock'; +import { AggConfig, AggConfigs, AggGroupNames, Schemas } from '../../agg_types'; +import { start as visualizationsStart } from '../../../../core_plugins/visualizations/public/np_ready/public/legacy'; +import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; + +describe('AggConfigs', function() { + let indexPattern; + + beforeEach(ngMock.module('kibana')); + beforeEach( + ngMock.inject(function(Private) { + // load main deps + indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); + }) + ); + + describe('constructor', function() { + it('handles passing just a vis', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [], + }); + + const ac = new AggConfigs(vis.indexPattern, [], vis.type.schemas.all); + expect(ac.aggs).to.have.length(1); + }); + + it('converts configStates into AggConfig objects if they are not already', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [], + }); + + const ac = new AggConfigs( + vis.indexPattern, + [ + { + type: 'date_histogram', + schema: 'segment', + }, + new AggConfig(vis.aggs, { + type: 'terms', + schema: 'split', + }), + ], + vis.type.schemas.all + ); + + expect(ac.aggs).to.have.length(3); + }); + + it('attempts to ensure that all states have an id', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [], + }); + + const states = [ + { + type: 'date_histogram', + schema: 'segment', + }, + { + type: 'terms', + schema: 'split', + }, + ]; + + const spy = sinon.spy(AggConfig, 'ensureIds'); + new AggConfigs(vis.indexPattern, states, vis.type.schemas.all); + expect(spy.callCount).to.be(1); + expect(spy.firstCall.args[0]).to.be(states); + AggConfig.ensureIds.restore(); + }); + + describe('defaults', function() { + let vis; + beforeEach(function() { + vis = { + indexPattern: indexPattern, + type: { + schemas: new Schemas([ + { + group: AggGroupNames.Metrics, + name: 'metric', + title: 'Simple', + min: 1, + max: 2, + defaults: [ + { schema: 'metric', type: 'count' }, + { schema: 'metric', type: 'avg' }, + { schema: 'metric', type: 'sum' }, + ], + }, + { + group: AggGroupNames.Buckets, + name: 'segment', + title: 'Example', + min: 0, + max: 1, + defaults: [ + { schema: 'segment', type: 'terms' }, + { schema: 'segment', type: 'filters' }, + ], + }, + ]), + }, + }; + }); + + it('should only set the number of defaults defined by the max', function() { + const ac = new AggConfigs(vis.indexPattern, [], vis.type.schemas.all); + expect(ac.bySchemaName('metric')).to.have.length(2); + }); + + it('should set the defaults defined in the schema when none exist', function() { + const ac = new AggConfigs(vis.indexPattern, [], vis.type.schemas.all); + expect(ac.aggs).to.have.length(3); + }); + + it('should NOT set the defaults defined in the schema when some exist', function() { + const ac = new AggConfigs( + vis.indexPattern, + [{ schema: 'segment', type: 'date_histogram' }], + vis.type.schemas.all + ); + expect(ac.aggs).to.have.length(3); + expect(ac.bySchemaName('segment')[0].type.name).to.equal('date_histogram'); + }); + }); + }); + + describe('#getRequestAggs', function() { + it('performs a stable sort, but moves metrics to the bottom', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { type: 'avg', schema: 'metric' }, + { type: 'terms', schema: 'split' }, + { type: 'histogram', schema: 'split' }, + { type: 'sum', schema: 'metric' }, + { type: 'date_histogram', schema: 'segment' }, + { type: 'filters', schema: 'split' }, + { type: 'percentiles', schema: 'metric' }, + ], + }); + + const sorted = vis.aggs.getRequestAggs(); + const aggs = _.indexBy(vis.aggs.aggs, function(agg) { + return agg.type.name; + }); + + expect(sorted.shift()).to.be(aggs.terms); + expect(sorted.shift()).to.be(aggs.histogram); + expect(sorted.shift()).to.be(aggs.date_histogram); + expect(sorted.shift()).to.be(aggs.filters); + expect(sorted.shift()).to.be(aggs.avg); + expect(sorted.shift()).to.be(aggs.sum); + expect(sorted.shift()).to.be(aggs.percentiles); + expect(sorted).to.have.length(0); + }); + }); + + describe('#getResponseAggs', function() { + it('returns all request aggs for basic aggs', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { type: 'terms', schema: 'split' }, + { type: 'date_histogram', schema: 'segment' }, + { type: 'count', schema: 'metric' }, + ], + }); + + const sorted = vis.aggs.getResponseAggs(); + const aggs = _.indexBy(vis.aggs.aggs, function(agg) { + return agg.type.name; + }); + + expect(sorted.shift()).to.be(aggs.terms); + expect(sorted.shift()).to.be(aggs.date_histogram); + expect(sorted.shift()).to.be(aggs.count); + expect(sorted).to.have.length(0); + }); + + it('expands aggs that have multiple responses', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { type: 'terms', schema: 'split' }, + { type: 'date_histogram', schema: 'segment' }, + { type: 'percentiles', schema: 'metric', params: { percents: [1, 2, 3] } }, + ], + }); + + const sorted = vis.aggs.getResponseAggs(); + const aggs = _.indexBy(vis.aggs.aggs, function(agg) { + return agg.type.name; + }); + + expect(sorted.shift()).to.be(aggs.terms); + expect(sorted.shift()).to.be(aggs.date_histogram); + expect(sorted.shift().id).to.be(aggs.percentiles.id + '.' + 1); + expect(sorted.shift().id).to.be(aggs.percentiles.id + '.' + 2); + expect(sorted.shift().id).to.be(aggs.percentiles.id + '.' + 3); + expect(sorted).to.have.length(0); + }); + }); + + describe('#toDsl', function() { + it('uses the sorted aggs', function() { + const vis = new visualizationsStart.Vis(indexPattern, { type: 'histogram' }); + sinon.spy(vis.aggs, 'getRequestAggs'); + vis.aggs.toDsl(); + expect(vis.aggs.getRequestAggs).to.have.property('callCount', 1); + }); + + it('calls aggConfig#toDsl() on each aggConfig and compiles the nested output', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { type: 'date_histogram', schema: 'segment' }, + { type: 'filters', schema: 'split' }, + ], + }); + + const aggInfos = vis.aggs.aggs.map(function(aggConfig) { + const football = {}; + + sinon.stub(aggConfig, 'toDsl').returns(football); + + return { + id: aggConfig.id, + football: football, + }; + }); + + (function recurse(lvl) { + const info = aggInfos.shift(); + + expect(lvl).to.have.property(info.id); + expect(lvl[info.id]).to.be(info.football); + + if (lvl[info.id].aggs) { + return recurse(lvl[info.id].aggs); + } + })(vis.aggs.toDsl()); + + expect(aggInfos).to.have.length(1); + }); + + it("skips aggs that don't have a dsl representation", function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + type: 'date_histogram', + schema: 'segment', + params: { field: '@timestamp', interval: '10s' }, + }, + { type: 'count', schema: 'metric' }, + ], + }); + + const dsl = vis.aggs.toDsl(); + const histo = vis.aggs.byName('date_histogram')[0]; + const count = vis.aggs.byName('count')[0]; + + expect(dsl).to.have.property(histo.id); + expect(dsl[histo.id]).to.be.an('object'); + expect(dsl[histo.id]).to.not.have.property('aggs'); + expect(dsl).to.not.have.property(count.id); + }); + + it('writes multiple metric aggregations at the same level', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + type: 'date_histogram', + schema: 'segment', + params: { field: '@timestamp', interval: '10s' }, + }, + { type: 'avg', schema: 'metric', params: { field: 'bytes' } }, + { type: 'sum', schema: 'metric', params: { field: 'bytes' } }, + { type: 'min', schema: 'metric', params: { field: 'bytes' } }, + { type: 'max', schema: 'metric', params: { field: 'bytes' } }, + ], + }); + + const dsl = vis.aggs.toDsl(); + + const histo = vis.aggs.byName('date_histogram')[0]; + const metrics = vis.aggs.bySchemaGroup('metrics'); + + expect(dsl).to.have.property(histo.id); + expect(dsl[histo.id]).to.be.an('object'); + expect(dsl[histo.id]).to.have.property('aggs'); + + metrics.forEach(function(metric) { + expect(dsl[histo.id].aggs).to.have.property(metric.id); + expect(dsl[histo.id].aggs[metric.id]).to.not.have.property('aggs'); + }); + }); + + it('writes multiple metric aggregations at every level if the vis is hierarchical', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { type: 'terms', schema: 'segment', params: { field: 'ip', orderBy: 1 } }, + { type: 'terms', schema: 'segment', params: { field: 'extension', orderBy: 1 } }, + { id: 1, type: 'avg', schema: 'metric', params: { field: 'bytes' } }, + { type: 'sum', schema: 'metric', params: { field: 'bytes' } }, + { type: 'min', schema: 'metric', params: { field: 'bytes' } }, + { type: 'max', schema: 'metric', params: { field: 'bytes' } }, + ], + }); + vis.isHierarchical = _.constant(true); + + const topLevelDsl = vis.aggs.toDsl(vis.isHierarchical()); + const buckets = vis.aggs.bySchemaGroup('buckets'); + const metrics = vis.aggs.bySchemaGroup('metrics'); + + (function checkLevel(dsl) { + const bucket = buckets.shift(); + expect(dsl).to.have.property(bucket.id); + + expect(dsl[bucket.id]).to.be.an('object'); + expect(dsl[bucket.id]).to.have.property('aggs'); + + metrics.forEach(function(metric) { + expect(dsl[bucket.id].aggs).to.have.property(metric.id); + expect(dsl[bucket.id].aggs[metric.id]).to.not.have.property('aggs'); + }); + + if (buckets.length) { + checkLevel(dsl[bucket.id].aggs); + } + })(topLevelDsl); + }); + + it('adds the parent aggs of nested metrics at every level if the vis is hierarchical', function() { + const vis = new visualizationsStart.Vis(indexPattern, { + type: 'histogram', + aggs: [ + { + id: '1', + type: 'avg_bucket', + schema: 'metric', + params: { + customBucket: { + id: '1-bucket', + type: 'date_histogram', + schema: 'bucketAgg', + params: { + field: '@timestamp', + interval: '10s', + }, + }, + customMetric: { + id: '1-metric', + type: 'count', + schema: 'metricAgg', + params: {}, + }, + }, + }, + { + id: '2', + type: 'terms', + schema: 'bucket', + params: { + field: 'geo.src', + }, + }, + { + id: '3', + type: 'terms', + schema: 'bucket', + params: { + field: 'machine.os', + }, + }, + ], + }); + vis.isHierarchical = _.constant(true); + + const topLevelDsl = vis.aggs.toDsl(vis.isHierarchical())['2']; + expect(topLevelDsl.aggs).to.have.keys(['1', '1-bucket']); + expect(topLevelDsl.aggs['1'].avg_bucket).to.have.property('buckets_path', '1-bucket>_count'); + expect(topLevelDsl.aggs['3'].aggs).to.have.keys(['1', '1-bucket']); + expect(topLevelDsl.aggs['3'].aggs['1'].avg_bucket).to.have.property( + 'buckets_path', + '1-bucket>_count' + ); + }); + }); +}); diff --git a/src/legacy/core_plugins/data/public/search/aggs/test_helpers/index.ts b/src/legacy/ui/public/vis/__tests__/index.js similarity index 86% rename from src/legacy/core_plugins/data/public/search/aggs/test_helpers/index.ts rename to src/legacy/ui/public/vis/__tests__/index.js index 131f921586144c..46074f2c5197b7 100644 --- a/src/legacy/core_plugins/data/public/search/aggs/test_helpers/index.ts +++ b/src/legacy/ui/public/vis/__tests__/index.js @@ -17,5 +17,5 @@ * under the License. */ -export { mockAggTypesRegistry } from './mock_agg_types_registry'; -export { mockDataServices } from './mock_data_services'; +import './_agg_config'; +import './_agg_configs'; diff --git a/src/plugins/data/common/field_formats/mocks.ts b/src/plugins/data/common/field_formats/mocks.ts deleted file mode 100644 index bc38374e147cf6..00000000000000 --- a/src/plugins/data/common/field_formats/mocks.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { FieldFormat, IFieldFormatsRegistry } from '.'; - -const fieldFormatMock = ({ - convert: jest.fn(), - getConverterFor: jest.fn(), - getParamDefaults: jest.fn(), - param: jest.fn(), - params: jest.fn(), - toJSON: jest.fn(), - type: jest.fn(), - setupContentType: jest.fn(), -} as unknown) as FieldFormat; - -export const fieldFormatsMock: IFieldFormatsRegistry = { - getByFieldType: jest.fn(), - getDefaultConfig: jest.fn(), - getDefaultInstance: jest.fn().mockImplementation(() => fieldFormatMock) as any, - getDefaultInstanceCacheResolver: jest.fn(), - getDefaultInstancePlain: jest.fn(), - getDefaultType: jest.fn(), - getDefaultTypeName: jest.fn(), - getInstance: jest.fn() as any, - getType: jest.fn(), - getTypeNameByEsTypes: jest.fn(), - init: jest.fn(), - register: jest.fn(), - parseDefaultTypeMap: jest.fn(), - deserialize: jest.fn(), - getTypeWithoutMetaParams: jest.fn(), -}; diff --git a/src/plugins/data/public/mocks.ts b/src/plugins/data/public/mocks.ts index 27de3b5a29bfd0..6a0a33096eaac1 100644 --- a/src/plugins/data/public/mocks.ts +++ b/src/plugins/data/public/mocks.ts @@ -16,9 +16,13 @@ * specific language governing permissions and limitations * under the License. */ - -import { Plugin, DataPublicPluginSetup, DataPublicPluginStart, IndexPatternsContract } from '.'; -import { fieldFormatsMock } from '../common/field_formats/mocks'; +import { + Plugin, + DataPublicPluginSetup, + DataPublicPluginStart, + IndexPatternsContract, + IFieldFormatsRegistry, +} from '.'; import { searchSetupMock } from './search/mocks'; import { queryServiceMock } from './query/mocks'; @@ -31,6 +35,24 @@ const autocompleteMock: any = { hasQuerySuggestions: jest.fn(), }; +const fieldFormatsMock: IFieldFormatsRegistry = { + getByFieldType: jest.fn(), + getDefaultConfig: jest.fn(), + getDefaultInstance: jest.fn() as any, + getDefaultInstanceCacheResolver: jest.fn(), + getDefaultInstancePlain: jest.fn(), + getDefaultType: jest.fn(), + getDefaultTypeName: jest.fn(), + getInstance: jest.fn() as any, + getType: jest.fn(), + getTypeNameByEsTypes: jest.fn(), + init: jest.fn(), + register: jest.fn(), + parseDefaultTypeMap: jest.fn(), + deserialize: jest.fn(), + getTypeWithoutMetaParams: jest.fn(), +}; + const createSetupContract = (): Setup => { const querySetupMock = queryServiceMock.createSetupContract(); const setupContract = { diff --git a/src/plugins/data/public/search/search_source/mocks.ts b/src/plugins/data/public/search/search_source/mocks.ts index 700bea741bd6ae..fd72158012de6f 100644 --- a/src/plugins/data/public/search/search_source/mocks.ts +++ b/src/plugins/data/public/search/search_source/mocks.ts @@ -17,6 +17,25 @@ * under the License. */ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"), you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + import { ISearchSource } from './search_source'; export const searchSourceMock: MockedKeys = { diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_service/service.test.tsx b/x-pack/legacy/plugins/lens/public/editor_frame_service/service.test.tsx index 2e1645c816140c..ef4b5f6d7b834f 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_service/service.test.tsx +++ b/x-pack/legacy/plugins/lens/public/editor_frame_service/service.test.tsx @@ -17,6 +17,10 @@ jest.mock('ui/new_platform'); // mock away actual dependencies to prevent all of it being loaded jest.mock('../../../../../../src/legacy/core_plugins/interpreter/public/registries', () => {}); +jest.mock('../../../../../../src/legacy/core_plugins/data/public/legacy', () => ({ + start: {}, + setup: {}, +})); jest.mock('./embeddable/embeddable_factory', () => ({ EmbeddableFactory: class Mock {}, })); diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/zeek/__snapshots__/zeek_details.test.tsx.snap b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/zeek/__snapshots__/zeek_details.test.tsx.snap index da04b970a494b8..c883983f8cf010 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/zeek/__snapshots__/zeek_details.test.tsx.snap +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/zeek/__snapshots__/zeek_details.test.tsx.snap @@ -2803,7 +2803,7 @@ tr:hover .c3:focus::before {
- - -
- - -
- - - - - - + -
- - - - - - - - + } + > + - Cu0n232QMyvNtzb75j - - - - + + - - + > + + + + - - - - - - - - -
-
-
-
-
-
-
- -
-
-
-
-
-
+ + + + + + + +
+ + + + + + + + + + + + + + @@ -3087,7 +3105,7 @@ tr:hover .c3:focus::before {
- - -
- - -
- - - - - - + -
- - - - - - - - + } + > + - files - - - - + + - - + > + + + + - - - - - - - - -
-
-
-
-
-
-
- -
-
-
-
-
-
+ + + + + + + +
+ + + + + + + + + + + + + + @@ -3371,7 +3407,7 @@ tr:hover .c3:focus::before {
- - -
- - -
- - - - - - + -
- - - - - - - - + } + > + - sha1: fa5195a... - - - - + + - - + > + + + + - - - - - - - - -
-
-
-
-
-
-
- -
-
-
-
-
-
+ + + + + + + +
+ + + + + + + + + + + + + + @@ -3655,7 +3709,7 @@ tr:hover .c3:focus::before {
- - -
- - -
- - - - - - + -
- - - - - - - - + } + > + - md5: f7653f1... - - - - + + - - + > + + + + - - - - - - - - -
-
-
-
-
-
-
- -
-
-
-
-
-
+ + + + + + + +
+ + + + + + + + + + + + + + From 8a8af5a57c5fa33e02da8e8d3db652f5b716375e Mon Sep 17 00:00:00 2001 From: spalger Date: Thu, 27 Feb 2020 23:37:39 -0700 Subject: [PATCH 7/9] skip flaky suite (#58662) --- .../bfetch/common/buffer/tests/timed_item_buffer.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/plugins/bfetch/common/buffer/tests/timed_item_buffer.test.ts b/src/plugins/bfetch/common/buffer/tests/timed_item_buffer.test.ts index c1c6a8f187a44c..e1640927c4ead3 100644 --- a/src/plugins/bfetch/common/buffer/tests/timed_item_buffer.test.ts +++ b/src/plugins/bfetch/common/buffer/tests/timed_item_buffer.test.ts @@ -20,7 +20,8 @@ import { TimedItemBuffer } from '../timed_item_buffer'; import { runItemBufferTests } from './run_item_buffer_tests'; -describe('TimedItemBuffer', () => { +// FLAKY: https://github.com/elastic/kibana/issues/58662 +describe.skip('TimedItemBuffer', () => { runItemBufferTests(TimedItemBuffer); test('does not do unnecessary flushes', async () => { From 913afb3bada2bd75f045ac7d8ec7483c774e2c6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Louv-Jansen?= Date: Fri, 28 Feb 2020 08:54:50 +0100 Subject: [PATCH 8/9] Update APM readme --- x-pack/legacy/plugins/apm/readme.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/x-pack/legacy/plugins/apm/readme.md b/x-pack/legacy/plugins/apm/readme.md index a513249c296db3..0edcdc279815cd 100644 --- a/x-pack/legacy/plugins/apm/readme.md +++ b/x-pack/legacy/plugins/apm/readme.md @@ -74,10 +74,14 @@ node scripts/jest.js plugins/apm --updateSnapshot ### Functional tests **Start server** -`node scripts/functional_tests_server --config x-pack/test/functional/config.js` +``` +node scripts/functional_tests_server --config x-pack/test/functional/config.js +``` **Run tests** -`node scripts/functional_test_runner --config x-pack/test/functional/config.js --grep='APM specs'` +``` +node scripts/functional_test_runner --config x-pack/test/functional/config.js --grep='APM specs' +``` APM tests are located in `x-pack/test/functional/apps/apm`. For debugging access Elasticsearch on http://localhost:9220` (elastic/changeme) @@ -85,10 +89,14 @@ For debugging access Elasticsearch on http://localhost:9220` (elastic/changeme) ### API integration tests **Start server** -`node scripts/functional_tests_server --config x-pack/test/api_integration/config.js` +``` +node scripts/functional_tests_server --config x-pack/test/api_integration/config.js +``` **Run tests** -`node scripts/functional_test_runner --config x-pack/test/api_integration/config.js --grep='APM specs'` +``` +node scripts/functional_test_runner --config x-pack/test/api_integration/config.js --grep='APM specs' +``` APM tests are located in `x-pack/test/api_integration/apis/apm`. For debugging access Elasticsearch on http://localhost:9220` (elastic/changeme) From ce45647ea2212f5cc42147e9b5bb82cb962e81ca Mon Sep 17 00:00:00 2001 From: Pierre Gayvallet Date: Fri, 28 Feb 2020 09:20:51 +0100 Subject: [PATCH 9/9] block SO setup API calls after startup (#58718) --- ...-plugin-server.savedobjectsservicesetup.md | 2 ++ src/core/MIGRATION_EXAMPLES.md | 8 ++++- .../saved_objects_service.test.ts | 30 +++++++++++++++++++ .../saved_objects/saved_objects_service.ts | 15 ++++++++++ 4 files changed, 54 insertions(+), 1 deletion(-) diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.md index b6f2e7320c48ad..963c4bbeb55153 100644 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.md +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.md @@ -16,6 +16,8 @@ export interface SavedObjectsServiceSetup When plugins access the Saved Objects client, a new client is created using the factory provided to `setClientFactory` and wrapped by all wrappers registered through `addClientWrapper`. +All the setup APIs will throw if called after the service has started, and therefor cannot be used from legacy plugin code. Legacy plugins should use the legacy savedObject service until migrated. + ## Example 1 diff --git a/src/core/MIGRATION_EXAMPLES.md b/src/core/MIGRATION_EXAMPLES.md index def83ba177fc9f..2953edb535f47a 100644 --- a/src/core/MIGRATION_EXAMPLES.md +++ b/src/core/MIGRATION_EXAMPLES.md @@ -917,4 +917,10 @@ Would be converted to: ```typescript const migration: SavedObjectMigrationFn = (doc, { log }) => {...} -``` \ No newline at end of file +``` + +### Remarks + +The `registerType` API will throw if called after the service has started, and therefor cannot be used from +legacy plugin code. Legacy plugins should use the legacy savedObjects service and the legacy way to register +saved object types until migrated. \ No newline at end of file diff --git a/src/core/server/saved_objects/saved_objects_service.test.ts b/src/core/server/saved_objects/saved_objects_service.test.ts index a1e2c1e8dbf263..554acf8d43dcb9 100644 --- a/src/core/server/saved_objects/saved_objects_service.test.ts +++ b/src/core/server/saved_objects/saved_objects_service.test.ts @@ -232,6 +232,36 @@ describe('SavedObjectsService', () => { expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(1); }); + it('throws when calling setup APIs once started', async () => { + const coreContext = createCoreContext({ skipMigration: false }); + const soService = new SavedObjectsService(coreContext); + const setup = await soService.setup(createSetupDeps()); + await soService.start({}); + + expect(() => { + setup.setClientFactoryProvider(jest.fn()); + }).toThrowErrorMatchingInlineSnapshot( + `"cannot call \`setClientFactoryProvider\` after service startup."` + ); + + expect(() => { + setup.addClientWrapper(0, 'dummy', jest.fn()); + }).toThrowErrorMatchingInlineSnapshot( + `"cannot call \`addClientWrapper\` after service startup."` + ); + + expect(() => { + setup.registerType({ + name: 'someType', + hidden: false, + namespaceAgnostic: false, + mappings: { properties: {} }, + }); + }).toThrowErrorMatchingInlineSnapshot( + `"cannot call \`registerType\` after service startup."` + ); + }); + describe('#getTypeRegistry', () => { it('returns the internal type registry of the service', async () => { const coreContext = createCoreContext({ skipMigration: false }); diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts index da8f7ab96d6891..d5a9f474209711 100644 --- a/src/core/server/saved_objects/saved_objects_service.ts +++ b/src/core/server/saved_objects/saved_objects_service.ts @@ -61,6 +61,9 @@ import { registerRoutes } from './routes'; * the factory provided to `setClientFactory` and wrapped by all wrappers * registered through `addClientWrapper`. * + * All the setup APIs will throw if called after the service has started, and therefor cannot be used + * from legacy plugin code. Legacy plugins should use the legacy savedObject service until migrated. + * * @example * ```ts * import { SavedObjectsClient, CoreSetup } from 'src/core/server'; @@ -275,6 +278,7 @@ export class SavedObjectsService private migrator$ = new Subject(); private typeRegistry = new SavedObjectTypeRegistry(); private validations: PropertyValidators = {}; + private started = false; constructor(private readonly coreContext: CoreContext) { this.logger = coreContext.logger.get('savedobjects-service'); @@ -316,12 +320,18 @@ export class SavedObjectsService return { setClientFactoryProvider: provider => { + if (this.started) { + throw new Error('cannot call `setClientFactoryProvider` after service startup.'); + } if (this.clientFactoryProvider) { throw new Error('custom client factory is already set, and can only be set once'); } this.clientFactoryProvider = provider; }, addClientWrapper: (priority, id, factory) => { + if (this.started) { + throw new Error('cannot call `addClientWrapper` after service startup.'); + } this.clientFactoryWrappers.push({ priority, id, @@ -329,6 +339,9 @@ export class SavedObjectsService }); }, registerType: type => { + if (this.started) { + throw new Error('cannot call `registerType` after service startup.'); + } this.typeRegistry.registerType(type); }, }; @@ -415,6 +428,8 @@ export class SavedObjectsService clientProvider.addClientWrapperFactory(priority, id, factory); }); + this.started = true; + return { migrator, clientProvider,