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

Introduce support for the server-side new platform plugins. #25473

Merged
merged 17 commits into from
Dec 4, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
213 changes: 213 additions & 0 deletions src/core/server/plugins/plugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
/*
* 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 { BehaviorSubject } from 'rxjs';
import { CoreContext } from '../../types';
import { Config, ConfigService, Env, ObjectToConfigAdapter } from '../config';
import { getEnvOptions } from '../config/__mocks__/env';
import { logger } from '../logging/__mocks__';
import { Plugin, PluginManifest } from './plugin';
import { createPluginInitializerContext, createPluginStartContext } from './plugin_context';

const mockPluginInitializer = jest.fn();
jest.mock('plugin-with-initializer-path', () => ({ plugin: mockPluginInitializer }), {
virtual: true,
});
jest.mock('plugin-without-initializer-path', () => ({}), {
virtual: true,
});
jest.mock('plugin-with-wrong-initializer-path', () => ({ plugin: {} }), {
virtual: true,
});

function createPluginManifest(manifestProps: Partial<PluginManifest> = {}): PluginManifest {
return {
id: 'some-plugin-id',
version: 'some-version',
configPath: 'path',
kibanaVersion: '7.0.0',
requiredPlugins: ['some-required-dep'],
optionalPlugins: ['some-optional-dep'],
ui: true,
...manifestProps,
};
}

let configService: ConfigService;
let env: Env;
let coreContext: CoreContext;
beforeEach(() => {
env = Env.createDefault(getEnvOptions());

configService = new ConfigService(
new BehaviorSubject<Config>(new ObjectToConfigAdapter({ plugins: { initialize: true } })),
env,
logger
);

coreContext = { env, logger, configService };
});

afterEach(() => {
jest.clearAllMocks();
});

test('`constructor` correctly initializes plugin instance', () => {
const manifest = createPluginManifest();
const plugin = new Plugin(
'some-plugin-path',
manifest,
createPluginInitializerContext(coreContext, manifest)
);

expect(plugin.name).toBe('some-plugin-id');
expect(plugin.configPath).toBe('path');
expect(plugin.path).toBe('some-plugin-path');
expect(plugin.requiredDependencies).toEqual(['some-required-dep']);
expect(plugin.optionalDependencies).toEqual(['some-optional-dep']);
});

test('`start` fails if `plugin` initializer is not exported', async () => {
const manifest = createPluginManifest();
const plugin = new Plugin(
'plugin-without-initializer-path',
manifest,
createPluginInitializerContext(coreContext, manifest)
);

await expect(
plugin.start(createPluginStartContext(coreContext, plugin), {})
).rejects.toMatchInlineSnapshot(
`[Error: Plugin "some-plugin-id" does not export "plugin" definition (plugin-without-initializer-path).]`
);
});

test('`start` fails if plugin initializer is not a function', async () => {
const manifest = createPluginManifest();
const plugin = new Plugin(
'plugin-with-wrong-initializer-path',
manifest,
createPluginInitializerContext(coreContext, manifest)
);

await expect(
plugin.start(createPluginStartContext(coreContext, plugin), {})
).rejects.toMatchInlineSnapshot(
`[Error: Definition of plugin "some-plugin-id" should be a function (plugin-with-wrong-initializer-path).]`
);
});

test('`start` fails if initializer does not return object', async () => {
const manifest = createPluginManifest();
const plugin = new Plugin(
'plugin-with-initializer-path',
manifest,
createPluginInitializerContext(coreContext, manifest)
);

mockPluginInitializer.mockReturnValue(null);

await expect(
plugin.start(createPluginStartContext(coreContext, plugin), {})
).rejects.toMatchInlineSnapshot(
`[Error: Initializer for plugin "some-plugin-id" is expected to return plugin instance, but returned "null".]`
);
});

test('`start` fails if object returned from initializer does not define `start` function', async () => {
const manifest = createPluginManifest();
const plugin = new Plugin(
'plugin-with-initializer-path',
manifest,
createPluginInitializerContext(coreContext, manifest)
);

const mockPluginInstance = { run: jest.fn() };
mockPluginInitializer.mockReturnValue(mockPluginInstance);

await expect(
plugin.start(createPluginStartContext(coreContext, plugin), {})
).rejects.toMatchInlineSnapshot(
`[Error: Instance of plugin "some-plugin-id" does not define "start" function.]`
);
});

test('`start` initializes plugin and calls appropriate lifecycle hook', async () => {
const manifest = createPluginManifest();
const initializerContext = createPluginInitializerContext(coreContext, manifest);
const plugin = new Plugin('plugin-with-initializer-path', manifest, initializerContext);

const mockPluginInstance = { start: jest.fn().mockResolvedValue({ contract: 'yes' }) };
mockPluginInitializer.mockReturnValue(mockPluginInstance);

const startContext = createPluginStartContext(coreContext, plugin);
const startDependencies = { 'some-required-dep': { contract: 'no' } };
await expect(plugin.start(startContext, startDependencies)).resolves.toEqual({ contract: 'yes' });

expect(mockPluginInitializer).toHaveBeenCalledTimes(1);
expect(mockPluginInitializer).toHaveBeenCalledWith(initializerContext);

expect(mockPluginInstance.start).toHaveBeenCalledTimes(1);
expect(mockPluginInstance.start).toHaveBeenCalledWith(startContext, startDependencies);
});

test('`stop` does nothing if plugin is not started', async () => {
epixa marked this conversation as resolved.
Show resolved Hide resolved
const manifest = createPluginManifest();
const plugin = new Plugin(
'plugin-with-initializer-path',
manifest,
createPluginInitializerContext(coreContext, manifest)
);

const mockPluginInstance = { start: jest.fn(), stop: jest.fn() };
mockPluginInitializer.mockReturnValue(mockPluginInstance);

await expect(plugin.stop()).resolves.toBeUndefined();
expect(mockPluginInstance.stop).not.toHaveBeenCalled();
});

test('`stop` does nothing if plugin does not define `stop` function', async () => {
const manifest = createPluginManifest();
const plugin = new Plugin(
'plugin-with-initializer-path',
manifest,
createPluginInitializerContext(coreContext, manifest)
);

mockPluginInitializer.mockReturnValue({ start: jest.fn() });
await plugin.start(createPluginStartContext(coreContext, plugin), {});

await expect(plugin.stop()).resolves.toBeUndefined();
});

test('`stop` calls `stop` defined by the plugin instance', async () => {
const manifest = createPluginManifest();
const plugin = new Plugin(
'plugin-with-initializer-path',
manifest,
createPluginInitializerContext(coreContext, manifest)
);

const mockPluginInstance = { start: jest.fn(), stop: jest.fn() };
mockPluginInitializer.mockReturnValue(mockPluginInstance);
await plugin.start(createPluginStartContext(coreContext, plugin), {});

await expect(plugin.stop()).resolves.toBeUndefined();
expect(mockPluginInstance.stop).toHaveBeenCalledTimes(1);
});
20 changes: 18 additions & 2 deletions src/core/server/plugins/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,11 @@ type PluginInitializer<TExposedContract, TDependencies extends Record<PluginName
stop?: () => void;
};

/** @internal */
/**
* Lightweight wrapper around discovered plugin that is responsible for instantiating
* plugin and dispatching proper context and dependencies into plugin's lifecycle hooks.
* @internal
*/
export class Plugin<
TStartContract = unknown,
TDependencies extends Record<PluginName, unknown> = Record<PluginName, unknown>
Expand All @@ -107,6 +111,13 @@ export class Plugin<
this.optionalDependencies = manifest.optionalPlugins;
}

/**
* Instantiates plugin and calls `start` function exposed by the plugin initializer.
* @param startContext Context that consists of various core services tailored specifically
* for the `start` lifecycle event.
* @param dependencies The dictionary where the key is the dependency name and the value
* is the contract returned by the dependency's `start` function.
*/
public async start(startContext: PluginStartContext, dependencies: TDependencies) {
this.instance = this.createPluginInstance();

Expand All @@ -115,6 +126,9 @@ export class Plugin<
return await this.instance.start(startContext, dependencies);
}

/**
* Calls optional `stop` function exposed by the plugin initializer.
*/
public async stop() {
if (this.instance === undefined) {
return;
Expand All @@ -125,10 +139,12 @@ export class Plugin<
if (typeof this.instance.stop === 'function') {
await this.instance.stop();
}

this.instance = undefined;
}

private createPluginInstance() {
this.log.info('Initializing plugin');
this.log.debug('Initializing plugin');

const pluginDefinition = require(this.path);
if (!('plugin' in pluginDefinition)) {
Expand Down
4 changes: 2 additions & 2 deletions src/core/server/plugins/plugins_system.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ test('`startPlugins` correctly orders plugins and returns exposed values', async
pluginsSystem.addPlugin(plugin);
});

mockCreatePluginStartContext.mockImplementation(plugin => startContextMap.get(plugin.name));
mockCreatePluginStartContext.mockImplementation((_, plugin) => startContextMap.get(plugin.name));

expect([...(await pluginsSystem.startPlugins())]).toMatchInlineSnapshot(`
Array [
Expand Down Expand Up @@ -176,7 +176,7 @@ Array [
`);

for (const [plugin, deps] of plugins) {
expect(mockCreatePluginStartContext).toHaveBeenCalledWith(plugin, coreContext);
expect(mockCreatePluginStartContext).toHaveBeenCalledWith(coreContext, plugin);
expect(plugin.start).toHaveBeenCalledTimes(1);
expect(plugin.start).toHaveBeenCalledWith(startContextMap.get(plugin.name), deps);
}
Expand Down