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

Add ContextService #40554

Closed
wants to merge 2 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-public](./kibana-plugin-public.md) &gt; [ContextContainer](./kibana-plugin-public.contextcontainer.md) &gt; [createContext](./kibana-plugin-public.contextcontainer.createcontext.md)

## ContextContainer.createContext() method

Create a new context.

<b>Signature:</b>

```typescript
createContext(plugin: string, baseContext: Partial<TContext>, ...contextArgs: TProviderParameters): Promise<TContext>;
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| plugin | <code>string</code> | The plugin the context will be exposed to. |
| baseContext | <code>Partial&lt;TContext&gt;</code> | The initial context for the given handler. |
| contextArgs | <code>TProviderParameters</code> | Additional parameters to call providers with. |

<b>Returns:</b>

`Promise<TContext>`

A Promise for the new context object.

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-public](./kibana-plugin-public.md) &gt; [ContextContainer](./kibana-plugin-public.contextcontainer.md)

## ContextContainer interface

An object that handles registration of context providers and building of new context objects.

<b>Signature:</b>

```typescript
export interface ContextContainer<TContext extends {}, TProviderParameters extends any[] = []>
```

## Methods

| Method | Description |
| --- | --- |
| [createContext(plugin, baseContext, contextArgs)](./kibana-plugin-public.contextcontainer.createcontext.md) | Create a new context. |
| [register(contextName, provider, plugin)](./kibana-plugin-public.contextcontainer.register.md) | Register a new context provider. Throws an exception if more than one provider is registered for the same context key. |

## Remarks

A `ContextContainer` can be used by any Core service or plugin (known as the "service owner") which wishes to expose APIs in a handler function. The container object will manage registering context providers and building a context object for a handler with all of the contexts that should be exposed to the handler's plugin. This is dependent on the dependencies that the handler's plugin declares.

Contexts providers are executed in the order they were registered. Each provider gets access to context values provided by any plugins that it depends on.

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-public](./kibana-plugin-public.md) &gt; [ContextContainer](./kibana-plugin-public.contextcontainer.md) &gt; [register](./kibana-plugin-public.contextcontainer.register.md)

## ContextContainer.register() method

Register a new context provider. Throws an exception if more than one provider is registered for the same context key.

<b>Signature:</b>

```typescript
register<TContextName extends keyof TContext>(contextName: TContextName, provider: ContextProvider<TContext, TContextName, TProviderParameters>, plugin?: string): this;
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| contextName | <code>TContextName</code> | The key of the <code>TContext</code> object this provider supplies the value for. |
| provider | <code>ContextProvider&lt;TContext, TContextName, TProviderParameters&gt;</code> | A [ContextProvider](./kibana-plugin-public.contextprovider.md) to be called each time a new context is created. |
| plugin | <code>string</code> | The plugin this provider is associated with. If <code>undefined</code>, provider gets access to all provided context keys. Only the service owner should be able to call with <code>undefined</code>. |

<b>Returns:</b>

`this`

The `ContextContainer` for method chaining.

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-public](./kibana-plugin-public.md) &gt; [ContextProvider](./kibana-plugin-public.contextprovider.md)

## ContextProvider type

A function that returns a context value for a specific key of given context type.

<b>Signature:</b>

```typescript
export declare type ContextProvider<TContext extends {}, TContextName extends keyof TContext, TProviderParameters extends any[] = []> = (context: Partial<TContext>, ...rest: TProviderParameters) => Promise<TContext[TContextName]> | TContext[TContextName];
```

## Remarks

This function will be called each time a new context is built for a handler invocation.

2 changes: 2 additions & 0 deletions docs/development/core/public/kibana-plugin-public.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [ChromeRecentlyAccessed](./kibana-plugin-public.chromerecentlyaccessed.md) | [APIs](./kibana-plugin-public.chromerecentlyaccessed.md) for recently accessed history. |
| [ChromeRecentlyAccessedHistoryItem](./kibana-plugin-public.chromerecentlyaccessedhistoryitem.md) | |
| [ChromeStart](./kibana-plugin-public.chromestart.md) | ChromeStart allows plugins to customize the global chrome header UI and enrich the UX with additional information about the current location of the browser. |
| [ContextContainer](./kibana-plugin-public.contextcontainer.md) | An object that handles registration of context providers and building of new context objects. |
| [CoreSetup](./kibana-plugin-public.coresetup.md) | Core services exposed to the <code>Plugin</code> setup lifecycle |
| [CoreStart](./kibana-plugin-public.corestart.md) | Core services exposed to the <code>Plugin</code> start lifecycle |
| [DocLinksStart](./kibana-plugin-public.doclinksstart.md) | |
Expand All @@ -58,6 +59,7 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| --- | --- |
| [ChromeHelpExtension](./kibana-plugin-public.chromehelpextension.md) | |
| [ChromeNavLinkUpdateableFields](./kibana-plugin-public.chromenavlinkupdateablefields.md) | |
| [ContextProvider](./kibana-plugin-public.contextprovider.md) | A function that returns a context value for a specific key of given context type. |
| [HttpSetup](./kibana-plugin-public.httpsetup.md) | |
| [HttpStart](./kibana-plugin-public.httpstart.md) | |
| [PluginInitializer](./kibana-plugin-public.plugininitializer.md) | The <code>plugin</code> export at the root of a plugin's <code>public</code> directory should conform to this interface. |
Expand Down
187 changes: 187 additions & 0 deletions src/core/public/context/context.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/*
* 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 { PluginName } from '../../server';
import { ContextContainerImplementation } from './context';

const plugins: ReadonlyMap<PluginName, PluginName[]> = new Map([
['pluginA', []],
['pluginB', ['pluginA']],
['pluginC', ['pluginA', 'pluginB']],
['pluginD', []],
]);

interface MyContext {
core1: string;
core2: number;
ctxFromA: string;
ctxFromB: number;
ctxFromC: boolean;
ctxFromD: object;
baseCtx: number;
}

describe('ContextContainer', () => {
it('does not allow the same context to be registered twice', () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we add a test to check an exception, raised during register phase, bubbles to the caller?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what you mean? Do you mean that we move / duplicate this test to ContextService?

const contextContainer = new ContextContainerImplementation<MyContext>(plugins);
contextContainer.register('ctxFromA', () => 'aString', 'pluginA');

expect(() =>
contextContainer.register('ctxFromA', () => 'aString', 'pluginA')
).toThrowErrorMatchingInlineSnapshot(
`"Context provider for ctxFromA has already been registered."`
);
});

it('resolves dependencies', async () => {
// expect.assertions(3);
const contextContainer = new ContextContainerImplementation<MyContext>(plugins);

contextContainer
.register('core1', context => {
expect(context).toEqual({});
return 'core';
})
.register(
'ctxFromA',
context => {
expect(context).toEqual({ core1: 'core' });
return 'aString';
},
'pluginA'
)
.register(
'ctxFromB',
context => {
expect(context).toEqual({ core1: 'core', ctxFromA: 'aString' });
return 299;
},
'pluginB'
)
.register(
'ctxFromC',
context => {
expect(context).toEqual({ core1: 'core', ctxFromA: 'aString', ctxFromB: 299 });
return false;
},
'pluginC'
)
.register(
'ctxFromD',
context => {
expect(context).toEqual({ core1: 'core' });
return {};
},
'pluginD'
);

// Should have context from pluginC, its deps, and core
expect(await contextContainer.createContext('pluginC')).toEqual({
core1: 'core',
ctxFromA: 'aString',
ctxFromB: 299,
ctxFromC: false,
});

// Should have context from pluginD, and core
expect(await contextContainer.createContext('pluginD')).toEqual({
core1: 'core',
ctxFromD: {},
});
});

it('exposes all previously registered context to Core providers', async () => {
expect.assertions(3);
const contextContainer = new ContextContainerImplementation<MyContext>(plugins);

contextContainer
.register('core1', context => {
expect(context).toEqual({});
return 'core';
})
.register('core2', context => {
expect(context).toEqual({ core1: 'core' });
return 101;
});

// If no context is registered for pluginA, only core contexts should be exposed
expect(await contextContainer.createContext('pluginA')).toEqual({
core1: 'core',
core2: 101,
});
});

it('passes additional arguments to providers', async () => {
expect.assertions(5);
const contextContainer = new ContextContainerImplementation<MyContext, [string, number]>(
plugins
);

contextContainer
.register('core1', (context, str, num) => {
expect(str).toEqual('passed string');
expect(num).toEqual(77);
return `core ${str}`;
})
.register('ctxFromD', (context, str, num) => {
expect(str).toEqual('passed string');
expect(num).toEqual(77);
return {
num: 77,
};
});

expect(await contextContainer.createContext('pluginD', {}, 'passed string', 77)).toEqual({
core1: 'core passed string',
ctxFromD: {
num: 77,
},
});
});

it('passes baseContext to context providers', async () => {
expect.assertions(3);
const contextContainer = new ContextContainerImplementation<MyContext>(plugins);

contextContainer
.register('core1', context => {
expect(context.baseCtx).toEqual(1234);
return 'core';
})
.register('ctxFromD', context => {
expect(context.baseCtx).toEqual(1234);
return {};
});

expect(await contextContainer.createContext('pluginD', { baseCtx: 1234 })).toEqual({
core1: 'core',
baseCtx: 1234,
ctxFromD: {},
});
});

it('throws error for unknown plugin', async () => {
const contextContainer = new ContextContainerImplementation<MyContext>(plugins);
await expect(
contextContainer.createContext('otherPlugin')
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Cannot create context for unknown plugin: otherPlugin"`
);
});
});
Loading