From a483d997925adfc5f99c8f6f787ca13c3eb0d87a Mon Sep 17 00:00:00 2001
From: Shahzad <shahzad31comp@gmail.com>
Date: Fri, 3 Jul 2020 22:43:49 +0200
Subject: [PATCH] added rum service

---
 .../components/app/RumDashboard/index.tsx     |  8 +--
 .../__snapshots__/queries.test.ts.snap        | 52 +++++++++++++++++++
 .../server/lib/rum_client/get_rum_services.ts | 48 +++++++++++++++++
 .../apm/server/lib/rum_client/queries.test.ts | 10 ++++
 .../apm/server/routes/create_apm_api.ts       |  2 +
 .../plugins/apm/server/routes/rum_client.ts   | 13 +++++
 6 files changed, 127 insertions(+), 6 deletions(-)
 create mode 100644 x-pack/plugins/apm/server/lib/rum_client/get_rum_services.ts

diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/index.tsx
index 3ddaa66b8de5e..3380a81c7bfab 100644
--- a/x-pack/plugins/apm/public/components/app/RumDashboard/index.tsx
+++ b/x-pack/plugins/apm/public/components/app/RumDashboard/index.tsx
@@ -46,7 +46,7 @@ export function RumOverview() {
     (callApmApi) => {
       if (start && end) {
         return callApmApi({
-          pathname: '/api/apm/services',
+          pathname: '/api/apm/rum-client/services',
           params: {
             query: {
               start,
@@ -68,11 +68,7 @@ export function RumOverview() {
           <LocalUIFilters {...localUIFiltersConfig} showCount={true}>
             {!isRumServiceRoute && (
               <>
-                <ServiceNameFilter
-                  serviceNames={
-                    data?.items?.map((service) => service.serviceName) ?? []
-                  }
-                />
+                <ServiceNameFilter serviceNames={data ?? []} />
                 <EuiSpacer size="xl" />
                 <EuiHorizontalRule margin="none" />{' '}
               </>
diff --git a/x-pack/plugins/apm/server/lib/rum_client/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/lib/rum_client/__snapshots__/queries.test.ts.snap
index c006d01637483..2d5235021e21c 100644
--- a/x-pack/plugins/apm/server/lib/rum_client/__snapshots__/queries.test.ts.snap
+++ b/x-pack/plugins/apm/server/lib/rum_client/__snapshots__/queries.test.ts.snap
@@ -179,3 +179,55 @@ Object {
   "index": "myIndex",
 }
 `;
+
+exports[`rum client dashboard queries fetches rum services 1`] = `
+Object {
+  "body": Object {
+    "aggs": Object {
+      "services": Object {
+        "terms": Object {
+          "field": "service.name",
+          "size": 1000,
+        },
+      },
+    },
+    "query": Object {
+      "bool": Object {
+        "filter": Array [
+          Object {
+            "range": Object {
+              "@timestamp": Object {
+                "format": "epoch_millis",
+                "gte": 1528113600000,
+                "lte": 1528977600000,
+              },
+            },
+          },
+          Object {
+            "term": Object {
+              "processor.event": "transaction",
+            },
+          },
+          Object {
+            "term": Object {
+              "transaction.type": "page-load",
+            },
+          },
+          Object {
+            "exists": Object {
+              "field": "transaction.marks.navigationTiming.fetchStart",
+            },
+          },
+          Object {
+            "term": Object {
+              "my.custom.ui.filter": "foo-bar",
+            },
+          },
+        ],
+      },
+    },
+    "size": 0,
+  },
+  "index": "myIndex",
+}
+`;
diff --git a/x-pack/plugins/apm/server/lib/rum_client/get_rum_services.ts b/x-pack/plugins/apm/server/lib/rum_client/get_rum_services.ts
new file mode 100644
index 0000000000000..38cc0e269e244
--- /dev/null
+++ b/x-pack/plugins/apm/server/lib/rum_client/get_rum_services.ts
@@ -0,0 +1,48 @@
+/*
+ * 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 { getRumOverviewProjection } from '../../../common/projections/rum_overview';
+import { mergeProjection } from '../../../common/projections/util/merge_projection';
+import {
+  Setup,
+  SetupTimeRange,
+  SetupUIFilters,
+} from '../helpers/setup_request';
+
+export async function getRumServices({
+  setup,
+}: {
+  setup: Setup & SetupTimeRange & SetupUIFilters;
+}) {
+  const projection = getRumOverviewProjection({
+    setup,
+  });
+
+  const params = mergeProjection(projection, {
+    body: {
+      size: 0,
+      query: {
+        bool: projection.body.query.bool,
+      },
+      aggs: {
+        services: {
+          terms: {
+            field: 'service.name',
+            size: 1000,
+          },
+        },
+      },
+    },
+  });
+
+  const { client } = setup;
+
+  const response = await client.search(params);
+
+  const result = response.aggregations?.services.buckets ?? [];
+
+  return result.map(({ key }) => key);
+}
diff --git a/x-pack/plugins/apm/server/lib/rum_client/queries.test.ts b/x-pack/plugins/apm/server/lib/rum_client/queries.test.ts
index 5f5a48eced746..37432672c5d89 100644
--- a/x-pack/plugins/apm/server/lib/rum_client/queries.test.ts
+++ b/x-pack/plugins/apm/server/lib/rum_client/queries.test.ts
@@ -11,6 +11,7 @@ import {
 import { getClientMetrics } from './get_client_metrics';
 import { getPageViewTrends } from './get_page_view_trends';
 import { getPageLoadDistribution } from './get_page_load_distribution';
+import { getRumServices } from './get_rum_services';
 
 describe('rum client dashboard queries', () => {
   let mock: SearchParamsMock;
@@ -49,4 +50,13 @@ describe('rum client dashboard queries', () => {
     );
     expect(mock.params).toMatchSnapshot();
   });
+
+  it('fetches rum services', async () => {
+    mock = await inspectSearchParams((setup) =>
+      getRumServices({
+        setup,
+      })
+    );
+    expect(mock.params).toMatchSnapshot();
+  });
 });
diff --git a/x-pack/plugins/apm/server/routes/create_apm_api.ts b/x-pack/plugins/apm/server/routes/create_apm_api.ts
index ed1c045616a27..031c6e7f2ad31 100644
--- a/x-pack/plugins/apm/server/routes/create_apm_api.ts
+++ b/x-pack/plugins/apm/server/routes/create_apm_api.ts
@@ -76,6 +76,7 @@ import {
   rumPageViewsTrendRoute,
   rumPageLoadDistributionRoute,
   rumPageLoadDistBreakdownRoute,
+  rumServicesRoute,
 } from './rum_client';
 import {
   observabilityDashboardHasDataRoute,
@@ -167,6 +168,7 @@ const createApmApi = () => {
     .add(rumPageLoadDistributionRoute)
     .add(rumPageLoadDistBreakdownRoute)
     .add(rumClientMetricsRoute)
+    .add(rumServicesRoute)
 
     // Observability dashboard
     .add(observabilityDashboardHasDataRoute)
diff --git a/x-pack/plugins/apm/server/routes/rum_client.ts b/x-pack/plugins/apm/server/routes/rum_client.ts
index 75651f646a50d..01e549632a0bc 100644
--- a/x-pack/plugins/apm/server/routes/rum_client.ts
+++ b/x-pack/plugins/apm/server/routes/rum_client.ts
@@ -12,6 +12,7 @@ import { rangeRt, uiFiltersRt } from './default_api_types';
 import { getPageViewTrends } from '../lib/rum_client/get_page_view_trends';
 import { getPageLoadDistribution } from '../lib/rum_client/get_page_load_distribution';
 import { getPageLoadDistBreakdown } from '../lib/rum_client/get_pl_dist_breakdown';
+import { getRumServices } from '../lib/rum_client/get_rum_services';
 
 export const percentileRangeRt = t.partial({
   minPercentile: t.string,
@@ -91,3 +92,15 @@ export const rumPageViewsTrendRoute = createRoute(() => ({
     return getPageViewTrends({ setup, breakdowns });
   },
 }));
+
+export const rumServicesRoute = createRoute(() => ({
+  path: '/api/apm/rum-client/services',
+  params: {
+    query: t.intersection([uiFiltersRt, rangeRt]),
+  },
+  handler: async ({ context, request }) => {
+    const setup = await setupRequest(context, request);
+
+    return getRumServices({ setup });
+  },
+}));