Skip to content

Commit

Permalink
[Uptime] Prefer Kibana core http services (elastic#53726) (elastic#54076
Browse files Browse the repository at this point in the history
)

* Prefer Kibana core http service to other fetch functions, refactor helper functions to hooks.

* Reintroduce newline deleted in previous commit.

* Clean up obsolete import.

* Clean up effect code in new hook.

* Clean up enum usage in new hook.

* Implement PR feedback on new hook.

* Fix eslint error.

Co-authored-by: Elastic Machine <[email protected]>

Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
justinkambic and elasticmachine authored Jan 9, 2020
1 parent 1697f21 commit dbdd96a
Show file tree
Hide file tree
Showing 15 changed files with 156 additions and 243 deletions.
8 changes: 1 addition & 7 deletions x-pack/legacy/plugins/uptime/public/apps/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,8 @@ export class Plugin {
}

public start(start: StartObject): void {
const {
core,
plugins: {
data: { autocomplete },
},
} = start;
const libs: UMFrontendLibs = {
framework: getKibanaFrameworkAdapter(core, autocomplete),
framework: getKibanaFrameworkAdapter(start.core, start.plugins),
};
// @ts-ignore improper type description
this.chrome.setRootTemplate(template);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { useState, useEffect, useContext } from 'react';
import React, { useState, useEffect } from 'react';
import { uniqueId, startsWith } from 'lodash';
import { EuiCallOut } from '@elastic/eui';
import styled from 'styled-components';
import { FormattedMessage } from '@kbn/i18n/react';
import { Typeahead } from './typeahead';
import { getIndexPattern } from '../../../lib/adapters/index_pattern';
import { UptimeSettingsContext } from '../../../contexts';
import { useUrlParams } from '../../../hooks';
import { toStaticIndexPattern } from '../../../lib/helper';
import {
Expand All @@ -20,6 +18,7 @@ import {
esKuery,
IIndexPattern,
} from '../../../../../../../../src/plugins/data/public';
import { useIndexPattern } from '../../../hooks';

const Container = styled.div`
margin-bottom: 10px;
Expand Down Expand Up @@ -71,16 +70,18 @@ export function KueryBar({ autocomplete }: Props) {
suggestions: [],
isLoadingIndexPattern: true,
});
const { basePath } = useContext(UptimeSettingsContext);
const [indexPattern, setIndexPattern] = useState<any | undefined>(undefined);
const [isLoadingIndexPattern, setIsLoadingIndexPattern] = useState<boolean>(true);
const [isLoadingSuggestions, setIsLoadingSuggestions] = useState<boolean>(false);
let currentRequestCheck: string;

useIndexPattern((result: any) => setIndexPattern(toStaticIndexPattern(result)));

useEffect(() => {
getIndexPattern(basePath, (result: any) => setIndexPattern(toStaticIndexPattern(result)));
setIsLoadingIndexPattern(false);
}, [basePath]);
if (indexPattern !== undefined) {
setIsLoadingIndexPattern(false);
}
}, [indexPattern]);
const [getUrlParams, updateUrlParams] = useUrlParams();
const { search: kuery } = getUrlParams();

Expand Down
2 changes: 2 additions & 0 deletions x-pack/legacy/plugins/uptime/public/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
*/

export { useUrlParams } from './use_url_params';
export { useIndexPattern } from './use_index_pattern';
export * from './use_telemetry';
20 changes: 20 additions & 0 deletions x-pack/legacy/plugins/uptime/public/hooks/use_index_pattern.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* 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 { useEffect, Dispatch } from 'react';
import { useKibana } from '../../../../../../src/plugins/kibana_react/public';

export const useIndexPattern = <T>(setIndexPattern: Dispatch<T>) => {
const core = useKibana();
useEffect(() => {
const fetch = core.services.http?.fetch;
async function getIndexPattern() {
if (!fetch) throw new Error('Http core services are not defined');
setIndexPattern(await fetch('/api/uptime/index_pattern', { method: 'GET' }));
}
getIndexPattern();
}, [core.services.http, setIndexPattern]);
};
41 changes: 41 additions & 0 deletions x-pack/legacy/plugins/uptime/public/hooks/use_telemetry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* 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 { useEffect } from 'react';
import { HttpHandler } from 'kibana/public';
import { useKibana } from '../../../../../../src/plugins/kibana_react/public';

export enum UptimePage {
Overview = '/api/uptime/logOverview',
Monitor = '/api/uptime/logMonitor',
NotFound = '__not-found__',
}

const getApiPath = (page?: UptimePage) => {
if (!page) throw new Error('Telemetry logging for this page not yet implemented');
if (page === '__not-found__')
throw new Error('Telemetry logging for 404 page not yet implemented');
return page.valueOf();
};

const logPageLoad = async (fetch: HttpHandler, page?: UptimePage) => {
try {
await fetch(getApiPath(page), {
method: 'POST',
});
} catch (e) {
throw e;
}
};

export const useUptimeTelemetry = (page?: UptimePage) => {
const kibana = useKibana();
const fetch = kibana.services.http?.fetch;
useEffect(() => {
if (!fetch) throw new Error('Core http services are not defined');
logPageLoad(fetch, page);
}, [fetch, page]);
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { ChromeBreadcrumb, CoreStart } from 'src/core/public';
import { ChromeBreadcrumb, LegacyCoreStart } from 'src/core/public';
import React from 'react';
import ReactDOM from 'react-dom';
import { get } from 'lodash';
import { AutocompleteProviderRegister } from 'src/plugins/data/public';
import { i18n as i18nFormatter } from '@kbn/i18n';
import { PluginsStart } from 'ui/new_platform/new_platform';
import { CreateGraphQLClient } from './framework_adapter_types';
import { UptimeApp, UptimeAppProps } from '../../../uptime_app';
import { getIntegratedAppAvailability } from './capabilities_adapter';
Expand All @@ -19,13 +19,12 @@ import {
DEFAULT_DARK_MODE,
DEFAULT_TIMEPICKER_QUICK_RANGES,
} from '../../../../common/constants';
import { getTelemetryMonitorPageLogger, getTelemetryOverviewPageLogger } from '../telemetry';
import { UMFrameworkAdapter, BootstrapUptimeApp } from '../../lib';
import { createApolloClient } from './apollo_client_adapter';

export const getKibanaFrameworkAdapter = (
core: CoreStart,
autocomplete: Pick<AutocompleteProviderRegister, 'getProvider'>
core: LegacyCoreStart,
plugins: PluginsStart
): UMFrameworkAdapter => {
const {
application: { capabilities },
Expand All @@ -44,19 +43,18 @@ export const getKibanaFrameworkAdapter = (
);
const canSave = get(capabilities, 'uptime.save', false);
const props: UptimeAppProps = {
autocomplete,
basePath: basePath.get(),
canSave,
client: createApolloClient(`${basePath.get()}/api/uptime/graphql`, 'true'),
core,
darkMode: core.uiSettings.get(DEFAULT_DARK_MODE),
commonlyUsedRanges: core.uiSettings.get(DEFAULT_TIMEPICKER_QUICK_RANGES),
i18n,
isApmAvailable: apm,
isInfraAvailable: infrastructure,
isLogsAvailable: logs,
kibanaBreadcrumbs: breadcrumbs,
logMonitorPageLoad: getTelemetryMonitorPageLogger('true', basePath.get()),
logOverviewPageLoad: getTelemetryOverviewPageLogger('true', basePath.get()),
plugins,
renderGlobalHelpControls: () =>
setHelpExtension({
appName: i18nFormatter.translate('xpack.uptime.header.appName', {
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

14 changes: 3 additions & 11 deletions x-pack/legacy/plugins/uptime/public/pages/monitor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@ import { getMonitorPageBreadcrumb } from '../breadcrumbs';
import { MonitorCharts, MonitorPageTitle, PingList } from '../components/functional';
import { UMUpdateBreadcrumbs } from '../lib/lib';
import { UptimeSettingsContext } from '../contexts';
import { useUrlParams } from '../hooks';
import { useUptimeTelemetry, useUrlParams, UptimePage } from '../hooks';
import { stringifyUrlParams } from '../lib/helper/stringify_url_params';
import { BaseLocationOptions } from '../components/functional/ping_list';
import { useTrackPageview } from '../../../infra/public';
import { MonitorStatusDetails } from '../components/functional/monitor_status_details';

interface MonitorPageProps {
logMonitorPageLoad: () => void;
match: { params: { monitorId: string } };
// this is the query function provided by Apollo's Client API
query: <T, TVariables = OperationVariables>(
Expand All @@ -28,12 +27,7 @@ interface MonitorPageProps {
setBreadcrumbs: UMUpdateBreadcrumbs;
}

export const MonitorPage = ({
logMonitorPageLoad,
query,
setBreadcrumbs,
match,
}: MonitorPageProps) => {
export const MonitorPage = ({ query, setBreadcrumbs, match }: MonitorPageProps) => {
// decode 64 base string, it was decoded to make it a valid url, since monitor id can be a url
const monitorId = atob(match.params.monitorId);
const [pingListPageCount, setPingListPageCount] = useState<number>(10);
Expand Down Expand Up @@ -77,9 +71,7 @@ export const MonitorPage = ({
monitorId,
};

useEffect(() => {
logMonitorPageLoad();
}, [logMonitorPageLoad]);
useUptimeTelemetry(UptimePage.Monitor);

useTrackPageview({ app: 'uptime', path: 'monitor' });
useTrackPageview({ app: 'uptime', path: 'monitor', delay: 15000 });
Expand Down
Loading

0 comments on commit dbdd96a

Please sign in to comment.