Skip to content

Commit

Permalink
Adds docs and includes fixes found by adding docs :)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonrhodes committed Sep 27, 2023
1 parent 9766ec7 commit 32d2173
Show file tree
Hide file tree
Showing 11 changed files with 270 additions and 67 deletions.
38 changes: 38 additions & 0 deletions x-pack/plugins/asset_manager/common/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { schema, TypeOf } from '@kbn/config-schema';

export const INDEX_DEFAULTS = {
metrics: 'metricbeat-*,metrics-*',
logs: 'filebeat-*,logs-*',
};

export const configSchema = schema.object({
alphaEnabled: schema.maybe(schema.boolean()),
// Designate where various types of data live.
// NOTE: this should be handled in a centralized way for observability, so
// that when a user configures these differently from the known defaults,
// that value is propagated everywhere. For now, we duplicate the value here.
sourceIndices: schema.object(
{
metrics: schema.string({ defaultValue: INDEX_DEFAULTS.metrics }),
logs: schema.string({ defaultValue: INDEX_DEFAULTS.logs }),
},
{ defaultValue: INDEX_DEFAULTS }
),
// Choose an explicit source for asset queries.
// NOTE: This will eventually need to be able to cleverly switch
// between these values based on the availability of data in the
// indices, and possibly for each asset kind/type value.
// For now, we set this explicitly.
lockedSource: schema.oneOf([schema.literal('assets'), schema.literal('signals')], {
defaultValue: 'signals',
}),
});

export type AssetManagerConfig = TypeOf<typeof configSchema>;
174 changes: 167 additions & 7 deletions x-pack/plugins/asset_manager/docs/api.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Asset Manager API Documentation

## Alpha Configuration
## Plugin configuration

This plugin is NOT fully enabled by default, even though it's always enabled
by Kibana's definition of "enabled". However, without the following configuration,
Expand All @@ -14,14 +14,174 @@ xpack.assetManager:
alphaEnabled: true
```
## APIs
## Depending on an asset client in your packages
This plugin provides the following APIs.
If you're creating a shared UI component or tool that needs to access asset data, you
can create that code in a stateless Kibana package that can itself be imported into
any Kibana plugin without any dependency restrictions. To gain access to the asset data,
this component or tool can require the appropriate asset client to be passed in.
### Server Assets Client
TODO: need to move main client types to a package so that they can be depended on by
other packages that require an injected asset client. Then we can list that package name
here and explain how to use those types in a package.
TBD
## Client APIs
### Public Assets Client
This plugin provides asset clients for Kibana server and public usage. The differences between these
two clients are described below in their sections, while the methods for both APIs are described
in the Client Methods section.
TBD
These clients are set up in the following way. For a given "methodA":
```
publicMethodA(...options: MethodAPublicOptions)
-> browser client calls corresponding REST API method with MethodAPublicOptions
-> REST API handler calls corresponding serverMethodA
-> serverMethodA requires MethodAPublicOptions & AssetClientDependencies, and it also
injects some internal dependencies from the plugin's config on your behalf
```

The public and server clientss are both accessible to plugin dependants, but the REST API is NOT.

### Required dependency setup

To use either client, you must first add "assetManager" to your `"requiredDependencies"` array
in your plugin's kibana.jsonc file.

TECH PREVIEW NOTE: While this plugin is in "tech preview", in both the server and public clients,
the provided plugin dependencies can be undefined for this plugin if the proper configuration
has not been set (see above). For that reason, the types will force you to guard against this
undefined scenario. Once the tech preview gating is removed, this will no longer be the case.

### Server client usage

In your plugin's `setup` method, you can gain access to the client from the injected `plugins` map.
Make sure you import the `AssetManagerServerPluginSetup` type from the plugin's server
directory and add it to your own SetupPlugins type, as seen below.

```ts
import { AssetManagerServerPluginSetup } from '@kbn/assetManager-plugin/server';

interface MyPluginSetupDeps {
assetManager: AssetManagerServerPluginSetup;
}

class MyPlugin {
setup(core: CoreSetup, plugins: MyPluginSetupDeps) {
// assetClient is found on plugins.assetManager.assetClient
setupRoutes(router, plugins);
}
}
```

To use the server client in your server routes, you can use something like this:

```ts
export function setupRoutes(router: IRouter, plugins: MyPluginDeps) {
router.get<unknown, MyRouteOptions, unknown>(
{
path: '/my/path',
validate: {},
},
async (context, req, res) => {
// handle route
// optionally, use asset client
// NOTE: see below for important info on required server client args
const hosts = await plugins.assetManager.assetClient.getHosts();
}
);
}
```

#### Required parameters for server client methods

All methods called via the server client require some core Kibana clients to be passed in,
so that they are pulled from the request context and properly scoped. If the asset manager
plugin provided these clients internally, they would not be scoped to the user that made
the API request, so they are required arguments for every server client method.

_Note: These required arguments are referred to as `AssetClientDependencies`, which can be
seen in the [the server types file](../server/types.ts)._

For example:

```ts
router.get<unknown, MyRouteOptions, unknown>(
{
path: '/my/path',
validate: {},
},
async (context, req, res) => {
// to use server asset client, you must get the following clients
// from the request context and pass them to the client method
// alongside whatever "public" arguments that method defines
const coreContext = await context.core;
const hostsOptions: PublicGetHostsOptions = {}; // these will be different for each method

const hosts = await plugins.assetManager.assetClient.getHosts({
...hostsOptions,
elasticsearchClient: coreContext.elasticsearch.client.asCurrentUser,
savedObjectsClient: coreContext.savedObjects.client,
});
}
);
```

### Public client usage

You should grab the public client in the same way as the server one, via the plugin dependencies
in your `setup` lifecycle.

```ts
import { AssetManagerPublicPluginStart } from '@kbn/assetManager-plugin/public';

interface MyPluginStartDeps {
assetManager: AssetManagerPublicPluginStart;
}

class MyPlugin {
setup(core: CoreSetup) {
core.application.register({
id: 'my-other-plugin',
title: '',
appRoute: '/app/my-other-plugin',
mount: async (params: AppMountParameters) => {
// mount callback should not use setup dependencies, get start dependencies instead
// so the pluginStart map passed to your renderApp method will be the start deps,
// not the setup deps -- the same asset client is provided to both setup and start in public
const [coreStart, , pluginStart] = await core.getStartServices();
// assetClient is found on pluginStart.assetManager.assetClient
return renderApp(coreStart, pluginStart, params);
},
});
}
}
```

All methods in the public client only require their public options (seen below), and don't require
the "AssetClientDependencies" that are required for the server client versions of the same methods.
This is because the public client will use the asset manager's internal REST API under the hood, where
it will be able to pull the properly-scoped client dependencies off of that request context for you.

### Client methods

#### getHosts

Get a group of host assets found within a specified time range.

| Parameter | Type | Required? | Description |
| :-------- | :-------------- | :-------- | :--------------------------------------------------------------------- |
| from | datetime string | yes | ISO date string representing the START of the time range being queried |
| to | datetime string | yes | ISO date string representing the END of the time range being queried |

**Response**

```json
{
"hosts": [
...found host assets
]
}
```

TODO: Link to a centralized asset document example that each response can reference?
11 changes: 6 additions & 5 deletions x-pack/plugins/asset_manager/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@

import { PluginInitializer, PluginInitializerContext } from '@kbn/core/public';
import { Plugin } from './plugin';
import { AssetManagerSetupExports, AssetManagerStartExports } from './types';
import { AssetManagerPublicPluginSetup, AssetManagerPublicPluginStart } from './types';

export const plugin: PluginInitializer<AssetManagerSetupExports, AssetManagerStartExports> = (
context: PluginInitializerContext
) => {
export const plugin: PluginInitializer<
AssetManagerPublicPluginSetup | undefined,
AssetManagerPublicPluginStart | undefined
> = (context: PluginInitializerContext) => {
return new Plugin(context);
};

export type { AssetManagerSetupExports, AssetManagerStartExports };
export type { AssetManagerPublicPluginSetup, AssetManagerPublicPluginStart };
export type AssetManagerAppId = 'assetManager';
29 changes: 26 additions & 3 deletions x-pack/plugins/asset_manager/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,47 @@
* 2.0.
*/

import { CoreSetup, PluginInitializerContext } from '@kbn/core/public';
import { CoreSetup, CoreStart, PluginInitializerContext } from '@kbn/core/public';
import { Logger } from '@kbn/logging';
import { AssetManagerPluginClass } from './types';
import { PublicAssetsClient } from './lib/public_assets_client';
import type { AssetManagerConfig } from '../common/config';

export class Plugin implements AssetManagerPluginClass {
public config: {};
public config: AssetManagerConfig;
public logger: Logger;

constructor(context: PluginInitializerContext<{}>) {
this.config = context.config.get();
this.logger = context.logger.get();
}

setup(core: CoreSetup) {
// Check for config value and bail out if not "alpha-enabled"
if (!this.config.alphaEnabled) {
this.logger.info('Public is NOT enabled');
return;
}

this.logger.info('Public is enabled');

const publicAssetsClient = new PublicAssetsClient(core.http);
return {
publicAssetsClient,
};
}

start(core: CoreStart) {
// Check for config value and bail out if not "alpha-enabled"
if (!this.config.alphaEnabled) {
return;
}

const publicAssetsClient = new PublicAssetsClient(core.http);
return {
publicAssetsClient,
};
}

start() {}
stop() {}
}
10 changes: 6 additions & 4 deletions x-pack/plugins/asset_manager/public/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@
import type { Plugin as PluginClass } from '@kbn/core/public';
import { GetHostsOptionsPublic } from '../common/types_client';
import { GetHostAssetsResponse } from '../common/types_api';
export interface AssetManagerSetupExports {
export interface AssetManagerPublicPluginSetup {
publicAssetsClient: IPublicAssetsClient;
}

export type AssetManagerStartExports = void;
export interface AssetManagerPublicPluginStart {
publicAssetsClient: IPublicAssetsClient;
}

export type AssetManagerPluginClass = PluginClass<
AssetManagerSetupExports,
AssetManagerStartExports
AssetManagerPublicPluginSetup | undefined,
AssetManagerPublicPluginStart | undefined
>;

export interface IPublicAssetsClient {
Expand Down
16 changes: 13 additions & 3 deletions x-pack/plugins/asset_manager/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,21 @@
*/

import { PluginInitializerContext } from '@kbn/core-plugins-server';
import { AssetManagerServerPlugin, config } from './plugin';
import { AssetManagerConfig } from '../common/config';
import {
AssetManagerServerPlugin,
AssetManagerServerPluginSetup,
AssetManagerServerPluginStart,
config,
} from './plugin';
import type { WriteSamplesPostBody } from './routes/sample_assets';
import { AssetManagerConfig } from './types';

export type { AssetManagerConfig, WriteSamplesPostBody };
export type {
AssetManagerConfig,
WriteSamplesPostBody,
AssetManagerServerPluginSetup,
AssetManagerServerPluginStart,
};
export { config };

export const plugin = (context: PluginInitializerContext<AssetManagerConfig>) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
* 2.0.
*/

import { GetHostsOptionsPublic } from '../../../../common/types_client';
import { AssetClientDependencies, OptionsWithInjectedValues } from '..';
import type { AssetClientDependencies } from '../../../types';
import type { GetHostsOptionsPublic } from '../../../../common/types_client';
import type { OptionsWithInjectedValues } from '..';

export type GetHostsOptions = GetHostsOptionsPublic & AssetClientDependencies;
export type GetHostsOptionsInjected = OptionsWithInjectedValues<GetHostsOptions>;
Expand Down
8 changes: 1 addition & 7 deletions x-pack/plugins/asset_manager/server/lib/accessors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,13 @@
* 2.0.
*/

import { ElasticsearchClient } from '@kbn/core-elasticsearch-server';
import { APMDataAccessConfig } from '@kbn/apm-data-access-plugin/server';
import { SavedObjectsClientContract } from '@kbn/core/server';
import { AssetManagerConfig } from '../../types';
import { AssetManagerConfig } from '../../../common/config';

export interface InjectedValues {
sourceIndices: AssetManagerConfig['sourceIndices'];
getApmIndices: (soClient: SavedObjectsClientContract) => Promise<APMDataAccessConfig['indices']>;
}

export type OptionsWithInjectedValues<T extends object> = T & InjectedValues;

export interface AssetClientDependencies {
elasticsearchClient: ElasticsearchClient;
savedObjectsClient: SavedObjectsClientContract;
}
2 changes: 1 addition & 1 deletion x-pack/plugins/asset_manager/server/lib/asset_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

import { APMDataAccessConfig } from '@kbn/apm-data-access-plugin/server';
import { SavedObjectsClientContract } from '@kbn/core/server';
import { AssetManagerConfig } from '../../common/config';
import { Asset } from '../../common/types_api';
import { AssetManagerConfig } from '../types';
import { OptionsWithInjectedValues } from './accessors';
import { GetHostsOptions } from './accessors/hosts';
import { GetServicesOptions } from './accessors/services';
Expand Down
Loading

0 comments on commit 32d2173

Please sign in to comment.