Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Uptime] Create state store at plugin setup time #66054

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 39 additions & 5 deletions x-pack/plugins/uptime/public/apps/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,26 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { Store } from 'redux';
import { CoreSetup, CoreStart, Plugin, PluginInitializerContext } from 'kibana/public';
import { AppMountParameters, DEFAULT_APP_CATEGORIES } from '../../../../../src/core/public';
import { UMFrontendLibs } from '../lib/lib';
import { PLUGIN } from '../../common/constants';
import { FeatureCatalogueCategory } from '../../../../../src/plugins/home/public';
import { HomePublicPluginSetup } from '../../../../../src/plugins/home/public';
import { EmbeddableStart } from '../../../../../src/plugins/embeddable/public';
import { TriggersAndActionsUIPublicPluginSetup } from '../../../triggers_actions_ui/public';
import { DataPublicPluginSetup } from '../../../../../src/plugins/data/public';
import {
TriggersAndActionsUIPublicPluginSetup,
TriggersAndActionsUIPublicPluginStart,
} from '../../../triggers_actions_ui/public';
import {
DataPublicPluginSetup,
DataPublicPluginStart,
} from '../../../../../src/plugins/data/public';
import { alertTypeInitializers } from '../lib/alert_types';
import { initializeStore } from '../state';
import { kibanaService } from '../state/kibana_service';

export interface ClientPluginsSetup {
data: DataPublicPluginSetup;
Expand All @@ -21,10 +32,16 @@ export interface ClientPluginsSetup {

export interface ClientPluginsStart {
embeddable: EmbeddableStart;
data: DataPublicPluginStart;
triggers_actions_ui: TriggersAndActionsUIPublicPluginStart;
}

export class UptimePlugin implements Plugin<void, void, ClientPluginsSetup, ClientPluginsStart> {
constructor(_context: PluginInitializerContext) {}
private _store: Store<any, any>;

constructor(_context: PluginInitializerContext) {
this._store = initializeStore();
}

public async setup(
core: CoreSetup<ClientPluginsStart, unknown>,
Expand All @@ -42,6 +59,7 @@ export class UptimePlugin implements Plugin<void, void, ClientPluginsSetup, Clie
});
}

const self = this;
core.application.register({
appRoute: '/app/uptime#/',
id: PLUGIN.ID,
Expand All @@ -56,16 +74,32 @@ export class UptimePlugin implements Plugin<void, void, ClientPluginsSetup, Clie
);

const { element } = params;

const libs: UMFrontendLibs = {
framework: getKibanaFrameworkAdapter(coreStart, plugins, corePlugins),
framework: getKibanaFrameworkAdapter(coreStart, plugins, corePlugins, self._store),
};
libs.framework.render(element);
return () => {};
},
});
}

public start(_start: CoreStart, _plugins: {}): void {}
public start(start: CoreStart, plugins: ClientPluginsStart): void {
kibanaService.core = start;
alertTypeInitializers.forEach(init => {
const alertInitializer = init({
store: this._store,
core: start,
plugins,
});
if (
plugins.triggers_actions_ui &&
!plugins.triggers_actions_ui.alertTypeRegistry.has(alertInitializer.id)
) {
plugins.triggers_actions_ui.alertTypeRegistry.register(alertInitializer);
}
});
}

public stop(): void {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { EuiLink } from '@elastic/eui';
import { EuiExpression, EuiPopover } from '@elastic/eui';
import { Link } from 'react-router-dom';
import React, { useState } from 'react';
import { FormattedMessage } from '@kbn/i18n/react';
import { SETTINGS_ROUTE } from '../../../../common/constants';
import { useKibana } from '../../../../../../../src/plugins/kibana_react/public';

interface SettingsMessageExpressionPopoverProps {
'aria-label': string;
Expand All @@ -25,6 +25,8 @@ export const SettingsMessageExpressionPopover: React.FC<SettingsMessageExpressio
value,
id,
}) => {
const kibana = useKibana();
const path = kibana.services?.application?.getUrlForApp('uptime', { path: 'settings' });
const [isOpen, setIsOpen] = useState(false);
return (
<EuiPopover
Expand All @@ -50,7 +52,7 @@ export const SettingsMessageExpressionPopover: React.FC<SettingsMessageExpressio
settingsPageLink: (
// this link is wrapped around a span so we can also change the UI state
// and hide the alert flyout before triggering the navigation to the settings page
<Link to={SETTINGS_ROUTE} data-test-subj="xpack.uptime.alerts.tlsFlyout.linkToSettings">
<EuiLink href={path} data-test-subj="xpack.uptime.alerts.tlsFlyout.linkToSettings">
<span
onClick={() => {
setAlertFlyoutVisible(false);
Expand All @@ -63,7 +65,7 @@ export const SettingsMessageExpressionPopover: React.FC<SettingsMessageExpressio
>
settings page
</span>
</Link>
</EuiLink>
),
}}
/>
Expand Down
25 changes: 15 additions & 10 deletions x-pack/plugins/uptime/public/contexts/uptime_refresh_context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@
*/

import React, { createContext, useMemo, useState } from 'react';
import { store } from '../state';
import { Store } from 'redux';
import { triggerAppRefresh } from '../state/actions';

interface UptimeRefreshContext {
lastRefresh: number;
refreshApp: () => void;
}

interface RefreshContextProps {
store: Store<any>;
}

const defaultContext: UptimeRefreshContext = {
lastRefresh: 0,
refreshApp: () => {
Expand All @@ -22,19 +26,20 @@ const defaultContext: UptimeRefreshContext = {

export const UptimeRefreshContext = createContext(defaultContext);

export const UptimeRefreshContextProvider: React.FC = ({ children }) => {
export const UptimeRefreshContextProvider: React.FC<RefreshContextProps> = ({
children,
store,
}) => {
const [lastRefresh, setLastRefresh] = useState<number>(Date.now());

const refreshApp = () => {
const refreshTime = Date.now();
setLastRefresh(refreshTime);
// @ts-ignore
store.dispatch(triggerAppRefresh(refreshTime));
};

const value = useMemo(() => {
const refreshApp = () => {
const refreshTime = Date.now();
setLastRefresh(refreshTime);
store.dispatch(triggerAppRefresh(refreshTime));
};
return { lastRefresh, refreshApp };
}, [lastRefresh]);
}, [lastRefresh, store]);

return <UptimeRefreshContext.Provider value={value} children={children} />;
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import React from 'react';
import ReactDOM from 'react-dom';
import { get } from 'lodash';
import { i18n as i18nFormatter } from '@kbn/i18n';
import { alertTypeInitializers } from '../../alert_types';
import { Store } from 'redux';
import { UptimeApp, UptimeAppProps } from '../../../uptime_app';
import { getIntegratedAppAvailability } from './capabilities_adapter';
import {
Expand All @@ -20,11 +20,13 @@ import {
} from '../../../../common/constants';
import { UMFrameworkAdapter } from '../../lib';
import { ClientPluginsStart, ClientPluginsSetup } from '../../../apps/plugin';
import { AppState } from '../../../state';

export const getKibanaFrameworkAdapter = (
core: CoreStart,
plugins: ClientPluginsSetup,
startPlugins: ClientPluginsStart
startPlugins: ClientPluginsStart,
store: Store<AppState>
): UMFrameworkAdapter => {
const {
application: { capabilities },
Expand All @@ -34,18 +36,6 @@ export const getKibanaFrameworkAdapter = (
i18n,
} = core;

const {
data: { autocomplete },
triggers_actions_ui,
} = plugins;

alertTypeInitializers.forEach(init => {
const alertInitializer = init({ autocomplete });
if (!triggers_actions_ui.alertTypeRegistry.has(alertInitializer.id)) {
triggers_actions_ui.alertTypeRegistry.register(init({ autocomplete }));
}
});

let breadcrumbs: ChromeBreadcrumb[] = [];
core.chrome.getBreadcrumbs$().subscribe((nextBreadcrumbs?: ChromeBreadcrumb[]) => {
breadcrumbs = nextBreadcrumbs || [];
Expand Down Expand Up @@ -90,6 +80,7 @@ export const getKibanaFrameworkAdapter = (
routerBasename: basePath.prepend(PLUGIN.ROUTER_BASE_NAME),
setBadge,
setBreadcrumbs: core.chrome.setBreadcrumbs,
store,
};

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,15 +166,38 @@ describe('monitor status alert type', () => {
});

describe('initMonitorStatusAlertType', () => {
expect(initMonitorStatusAlertType({ autocomplete: {} })).toMatchInlineSnapshot(`
expect(
initMonitorStatusAlertType({
autocomplete: {},
store: {
dispatch: jest.fn(),
getState: jest.fn(),
replaceReducer: jest.fn(),
subscribe: jest.fn(),
[Symbol.observable]: jest.fn(),
},
})
).toMatchInlineSnapshot(`
Object {
"alertParamsExpression": [Function],
"defaultActionMessage": "{{context.message}}
Last triggered at: {{state.lastTriggeredAt}}
{{context.downMonitorsWithGeo}}",
"iconClass": "uptimeApp",
"id": "xpack.uptime.alerts.monitorStatus",
"name": <MonitorStatusTitle />,
"name": <Provider
store={
Object {
"dispatch": [MockFunction],
"getState": [MockFunction],
"replaceReducer": [MockFunction],
"subscribe": [MockFunction],
Symbol(observable): [MockFunction],
}
}
>
<MonitorStatusTitle />
</Provider>,
"requiresAppContext": true,
"validate": [Function],
}
Expand Down
9 changes: 8 additions & 1 deletion x-pack/plugins/uptime/public/lib/alert_types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,18 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { Store } from 'redux';
import { CoreStart } from 'kibana/public';
import { AlertTypeModel } from '../../../../triggers_actions_ui/public';
import { initMonitorStatusAlertType } from './monitor_status';
import { initTlsAlertType } from './tls';
import { ClientPluginsStart } from '../../apps/plugin';

export type AlertTypeInitializer = (dependenies: { autocomplete: any }) => AlertTypeModel;
export type AlertTypeInitializer = (dependenies: {
store: Store<any>;
core: CoreStart;
plugins: ClientPluginsStart;
}) => AlertTypeModel;

export const alertTypeInitializers: AlertTypeInitializer[] = [
initMonitorStatusAlertType,
Expand Down
26 changes: 20 additions & 6 deletions x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import { PathReporter } from 'io-ts/lib/PathReporter';
import { Provider as ReduxProvider } from 'react-redux';
import React from 'react';
import DateMath from '@elastic/datemath';
import { isRight } from 'fp-ts/lib/Either';
Expand All @@ -15,6 +16,7 @@ import { AlertMonitorStatus } from '../../components/overview/alerts/alerts_cont
import { MonitorStatusTitle } from './monitor_status_title';
import { CLIENT_ALERT_TYPES } from '../../../common/constants';
import { MonitorStatusTranslations } from './translations';
import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public';

export const validate = (alertParams: any) => {
const errors: Record<string, any> = {};
Expand Down Expand Up @@ -58,15 +60,27 @@ export const validate = (alertParams: any) => {
const { defaultActionMessage } = MonitorStatusTranslations;

export const initMonitorStatusAlertType: AlertTypeInitializer = ({
autocomplete,
store,
core,
plugins,
}): AlertTypeModel => ({
id: CLIENT_ALERT_TYPES.MONITOR_STATUS,
name: <MonitorStatusTitle />,
iconClass: 'uptimeApp',
alertParamsExpression: (params: any) => (
<AlertMonitorStatus {...params} autocomplete={autocomplete} />
name: (
<ReduxProvider store={store}>
<MonitorStatusTitle />
</ReduxProvider>
),
iconClass: 'uptimeApp',
alertParamsExpression: (params: any) => {
return (
<ReduxProvider store={store}>
<KibanaContextProvider services={{ ...core, ...plugins }}>
<AlertMonitorStatus {...params} autocomplete={plugins.data.autocomplete} />
</KibanaContextProvider>
</ReduxProvider>
);
},
validate,
defaultActionMessage,
requiresAppContext: true,
requiresAppContext: false,
});
18 changes: 15 additions & 3 deletions x-pack/plugins/uptime/public/lib/alert_types/tls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,32 @@
*/

import React from 'react';
import { Provider as ReduxProvider } from 'react-redux';
import { AlertTypeModel } from '../../../../triggers_actions_ui/public';
import { CLIENT_ALERT_TYPES } from '../../../common/constants';
import { TlsTranslations } from './translations';
import { AlertTypeInitializer } from '.';
import { AlertTls } from '../../components/overview/alerts/alerts_containers/alert_tls';
import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public';

const { name, defaultActionMessage } = TlsTranslations;

export const initTlsAlertType: AlertTypeInitializer = (): AlertTypeModel => ({
export const initTlsAlertType: AlertTypeInitializer = ({
store,
core,
plugins,
}): AlertTypeModel => ({
id: CLIENT_ALERT_TYPES.TLS,
iconClass: 'uptimeApp',
alertParamsExpression: () => <AlertTls />,
alertParamsExpression: () => (
<ReduxProvider store={store}>
<KibanaContextProvider services={{ ...core, ...plugins }}>
<AlertTls />
</KibanaContextProvider>
</ReduxProvider>
),
name,
validate: () => ({ errors: {} }),
defaultActionMessage,
requiresAppContext: true,
requiresAppContext: false,
});
Loading