Skip to content

Commit

Permalink
Make core interfaces exposed to legacy platform consistent
Browse files Browse the repository at this point in the history
  • Loading branch information
joshdover committed Oct 1, 2019
1 parent de841f7 commit c1ab169
Show file tree
Hide file tree
Showing 14 changed files with 82 additions and 49 deletions.
1 change: 1 addition & 0 deletions src/core/public/core_system.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const defaultCoreSystemParams = {

beforeEach(() => {
jest.clearAllMocks();
MockPluginsService.getOpaqueIds.mockReturnValue(new Map());
});

function createCoreSystem(params = {}) {
Expand Down
16 changes: 10 additions & 6 deletions src/core/public/core_system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export interface InternalCoreStart extends Omit<CoreStart, 'application'> {
export class CoreSystem {
private readonly fatalErrors: FatalErrorsService;
private readonly injectedMetadata: InjectedMetadataService;
private readonly legacyPlatform: LegacyPlatformService;
private readonly legacy: LegacyPlatformService;
private readonly notifications: NotificationsService;
private readonly http: HttpService;
private readonly savedObjects: SavedObjectsService;
Expand Down Expand Up @@ -134,7 +134,7 @@ export class CoreSystem {
this.context = new ContextService(this.coreContext);
this.plugins = new PluginsService(this.coreContext, injectedMetadata.uiPlugins);

this.legacyPlatform = new LegacyPlatformService({
this.legacy = new LegacyPlatformService({
requireLegacyFiles,
useLegacyTestHarness,
});
Expand All @@ -154,7 +154,11 @@ export class CoreSystem {
const notifications = this.notifications.setup({ uiSettings });

const pluginDependencies = this.plugins.getOpaqueIds();
const context = this.context.setup({ pluginDependencies });
const context = this.context.setup({
// We inject a fake "legacy plugin" with no dependencies so that legacy plugins can register context providers
// that will only be available to other legacy plugins and will not leak into New Platform plugins.
pluginDependencies: new Map([...pluginDependencies, [this.legacy.legacyId, []]]),
});
const application = this.application.setup({ context });

const core: InternalCoreSetup = {
Expand All @@ -170,7 +174,7 @@ export class CoreSystem {
// Services that do not expose contracts at setup
const plugins = await this.plugins.setup(core);

await this.legacyPlatform.setup({
await this.legacy.setup({
core,
plugins: mapToObject(plugins.contracts),
});
Expand Down Expand Up @@ -260,7 +264,7 @@ export class CoreSystem {
targetDomElement: coreUiTargetDomElement,
});

await this.legacyPlatform.start({
await this.legacy.start({
core,
plugins: mapToObject(plugins.contracts),
targetDomElement: rendering.legacyTargetDomElement,
Expand All @@ -277,7 +281,7 @@ export class CoreSystem {
}

public stop() {
this.legacyPlatform.stop();
this.legacy.stop();
this.plugins.stop();
this.notifications.stop();
this.http.stop();
Expand Down
2 changes: 2 additions & 0 deletions src/core/public/legacy/legacy_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ interface BootstrapModule {
* setup either the app or browser tests.
*/
export class LegacyPlatformService {
/** Symbol to represent the legacy platform as a fake "plugin". Used by the ContextService */
public readonly legacyId = Symbol();
private bootstrapModule?: BootstrapModule;
private targetDomElement?: HTMLElement;

Expand Down
23 changes: 5 additions & 18 deletions src/core/server/legacy/legacy_service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { DiscoveredPlugin, DiscoveredPluginInternal } from '../plugins';
import { PluginsServiceSetup, PluginsServiceStart } from '../plugins/plugins_service';
import { SavedObjectsServiceStart } from 'src/core/server/saved_objects/saved_objects_service';
import { KibanaMigrator } from '../saved_objects/migrations';
import { httpServiceMock } from '../http/http_service.mock';

const MockKbnServer: jest.Mock<KbnServer> = KbnServer as any;

Expand Down Expand Up @@ -86,6 +87,7 @@ beforeEach(() => {
context: contextServiceMock.createSetupContract(),
elasticsearch: { legacy: {} } as any,
http: {
...httpServiceMock.createSetupContract(),
auth: {
getAuthHeaders: () => undefined,
},
Expand Down Expand Up @@ -146,12 +148,7 @@ describe('once LegacyService is set up with connection info', () => {
expect(MockKbnServer).toHaveBeenCalledWith(
{ server: { autoListen: true } },
{ server: { autoListen: true } },
{
setupDeps,
startDeps,
handledConfigPaths: ['foo.bar'],
logger,
},
expect.any(Object),
{ disabledPluginSpecs: [], pluginSpecs: [], uiExports: [] }
);

Expand All @@ -176,12 +173,7 @@ describe('once LegacyService is set up with connection info', () => {
expect(MockKbnServer).toHaveBeenCalledWith(
{ server: { autoListen: true } },
{ server: { autoListen: true } },
{
setupDeps,
startDeps,
handledConfigPaths: ['foo.bar'],
logger,
},
expect.any(Object),
{ disabledPluginSpecs: [], pluginSpecs: [], uiExports: [] }
);

Expand Down Expand Up @@ -311,12 +303,7 @@ describe('once LegacyService is set up without connection info', () => {
expect(MockKbnServer).toHaveBeenCalledWith(
{ server: { autoListen: true } },
{ server: { autoListen: true } },
{
setupDeps,
startDeps,
handledConfigPaths: ['foo.bar'],
logger,
},
expect.any(Object),
{ disabledPluginSpecs: [], pluginSpecs: [], uiExports: [] }
);
});
Expand Down
37 changes: 34 additions & 3 deletions src/core/server/legacy/legacy_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import { combineLatest, ConnectableObservable, EMPTY, Observable, Subscription } from 'rxjs';
import { first, map, publishReplay, tap } from 'rxjs/operators';
import { CoreService } from '../../types';
import { InternalCoreSetup, InternalCoreStart } from '../';
import { InternalCoreSetup, InternalCoreStart, CoreSetup, CoreStart } from '../';
import { SavedObjectsLegacyUiExports } from '../types';
import { Config } from '../config';
import { CoreContext } from '../core_context';
Expand Down Expand Up @@ -81,6 +81,8 @@ export interface LegacyServiceSetup {

/** @internal */
export class LegacyService implements CoreService<LegacyServiceSetup> {
/** Symbol to represent the legacy platform as a fake "plugin". Used by the ContextService */
public readonly legacyId = Symbol();
private readonly log: Logger;
private readonly devConfig$: Observable<DevConfig>;
private readonly httpConfig$: Observable<HttpConfig>;
Expand Down Expand Up @@ -226,15 +228,44 @@ export class LegacyService implements CoreService<LegacyServiceSetup> {
uiExports: SavedObjectsLegacyUiExports;
}
) {
const coreSetup: CoreSetup = {
context: setupDeps.core.context,
elasticsearch: {
adminClient$: setupDeps.core.elasticsearch.adminClient$,
dataClient$: setupDeps.core.elasticsearch.dataClient$,
createClient: setupDeps.core.elasticsearch.createClient,
},
http: {
createCookieSessionStorageFactory: setupDeps.core.http.createCookieSessionStorageFactory,
registerRouteHandlerContext: setupDeps.core.http.registerRouteHandlerContext.bind(
null,
this.legacyId
),
createRouter: () => setupDeps.core.http.createRouter('', this.legacyId),
registerOnPreAuth: setupDeps.core.http.registerOnPreAuth,
registerAuth: setupDeps.core.http.registerAuth,
registerOnPostAuth: setupDeps.core.http.registerOnPostAuth,
basePath: setupDeps.core.http.basePath,
isTlsEnabled: setupDeps.core.http.isTlsEnabled,
},
};
const coreStart: CoreStart = {};

// eslint-disable-next-line @typescript-eslint/no-var-requires
const KbnServer = require('../../../legacy/server/kbn_server');
const kbnServer: LegacyKbnServer = new KbnServer(
settings,
config,
{
handledConfigPaths: await this.coreContext.configService.getUsedPaths(),
setupDeps,
startDeps,
setupDeps: {
core: coreSetup,
plugins: setupDeps.plugins,
},
startDeps: {
core: coreStart,
plugins: startDeps.plugins,
},
logger: this.coreContext.logger,
},
legacyPlugins
Expand Down
1 change: 1 addition & 0 deletions src/core/server/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const logger = loggingServiceMock.create();

beforeEach(() => {
mockConfigService.atPath.mockReturnValue(new BehaviorSubject({ autoListen: true }));
mockPluginsService.discover.mockResolvedValue(new Map());
});

afterEach(() => {
Expand Down
6 changes: 5 additions & 1 deletion src/core/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ export class Server {

// Discover any plugins before continuing. This allows other systems to utilize the plugin dependency graph.
const pluginDependencies = await this.plugins.discover();
const contextServiceSetup = this.context.setup({ pluginDependencies });
const contextServiceSetup = this.context.setup({
// We inject a fake "legacy plugin" with no dependencies so that legacy plugins can register context providers
// that will only be available to other legacy plugins and will not leak into New Platform plugins.
pluginDependencies: new Map([...pluginDependencies, [this.legacy.legacyId, []]]),
});

const httpSetup = await this.http.setup({
context: contextServiceSetup,
Expand Down
15 changes: 5 additions & 10 deletions src/legacy/server/index_patterns/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,10 @@

import { first } from 'rxjs/operators';
import { schema } from '@kbn/config-schema';
import {
InternalCoreSetup,
KibanaRequest,
RequestHandlerContext,
APICaller,
} from '../../../core/server';
import { CoreSetup, KibanaRequest, RequestHandlerContext, APICaller } from '../../../core/server';
import { IndexPatternsService } from './service';

export function registerRoutes(core: InternalCoreSetup) {
export function registerRoutes(core: CoreSetup) {
const getIndexPatternsService = async (request: KibanaRequest): Promise<IndexPatternsService> => {
const client = await core.elasticsearch.dataClient$.pipe(first()).toPromise();
const callCluster: APICaller = (endpoint, params, options) =>
Expand All @@ -45,10 +40,10 @@ export function registerRoutes(core: InternalCoreSetup) {
return parsedFields;
};

const router = core.http.createRouter('/api/index_patterns');
const router = core.http.createRouter();
router.get(
{
path: '/_fields_for_wildcard',
path: '/api/index_patterns/_fields_for_wildcard',
validate: {
query: schema.object({
pattern: schema.string(),
Expand Down Expand Up @@ -89,7 +84,7 @@ export function registerRoutes(core: InternalCoreSetup) {

router.get(
{
path: '/_fields_for_time_pattern',
path: '/api/index_patterns/_fields_for_time_pattern',
validate: {
query: schema.object({
pattern: schema.string(),
Expand Down
13 changes: 10 additions & 3 deletions src/legacy/server/kbn_server.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import { ResponseObject, Server } from 'hapi';
import { UnwrapPromise } from '@kbn/utility-types';

import { SavedObjectsClientProviderOptions } from 'src/core/server';
import { SavedObjectsClientProviderOptions, CoreSetup } from 'src/core/server';
import {
ConfigService,
ElasticsearchServiceSetup,
Expand Down Expand Up @@ -78,6 +78,7 @@ declare module 'hapi' {
factoryFn: (request: Request) => Record<string, any>
) => void;
uiSettingsServiceFactory: (options: any) => any;
newPlatform: KbnServer['newPlatform'];
}

interface Request {
Expand All @@ -100,8 +101,14 @@ export default class KbnServer {
coreContext: {
logger: LoggerFactory;
};
setup: LegacyServiceSetupDeps;
start: LegacyServiceStartDeps;
setup: {
core: CoreSetup;
plugins: Record<string, object>;
};
start: {
core: CoreSetup;
plugins: Record<string, object>;
};
stop: null;
params: {
handledConfigPaths: UnwrapPromise<ReturnType<ConfigService['getUsedPaths']>>;
Expand Down
2 changes: 1 addition & 1 deletion test/plugin_functional/plugins/core_plugin_legacy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function(kibana: any) {
require: ['kibana'],
init(server: KbnServer) {
const { http } = server.newPlatform.setup.core;
const router = http.createRouter('');
const router = http.createRouter();

router.get({ path: '/api/np-http-in-legacy', validate: false }, async (context, req, res) => {
const response = await context.core.elasticsearch.adminClient.callAsInternalUser('ping');
Expand Down
3 changes: 1 addition & 2 deletions x-pack/legacy/plugins/lens/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { LegacyPluginInitializer } from 'src/legacy/types';
import KbnServer, { Server } from 'src/legacy/server/kbn_server';
import { CoreSetup } from 'src/core/server';
import mappings from './mappings.json';
import { PLUGIN_ID, getEditPath, BASE_API_URL } from './common';
import { PLUGIN_ID, getEditPath } from './common';
import { lensServerPlugin } from './server';

const NOT_INTERNATIONALIZED_PRODUCT_NAME = 'Lens Visualizations';
Expand Down Expand Up @@ -87,7 +87,6 @@ export const lens: LegacyPluginInitializer = kibana => {
plugin.setup(({
http: {
...kbnServer.newPlatform.setup.core.http,
createRouter: () => kbnServer.newPlatform.setup.core.http.createRouter(BASE_API_URL),
},
} as unknown) as CoreSetup);

Expand Down
4 changes: 2 additions & 2 deletions x-pack/legacy/plugins/lens/server/routes/field_stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ import DateMath from '@elastic/datemath';
import { schema } from '@kbn/config-schema';
import { AggregationSearchResponse } from 'elasticsearch';
import { CoreSetup } from 'src/core/server';
import { FieldStatsResponse } from '../../common';
import { FieldStatsResponse, BASE_API_URL } from '../../common';

const SHARD_SIZE = 5000;

export async function initFieldsRoute(setup: CoreSetup) {
const router = setup.http.createRouter();
router.post(
{
path: '/index_stats/{indexPatternTitle}/field',
path: `${BASE_API_URL}/index_stats/{indexPatternTitle}/field`,
validate: {
params: schema.object({
indexPatternTitle: schema.string(),
Expand Down
3 changes: 2 additions & 1 deletion x-pack/legacy/plugins/lens/server/routes/index_stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
IndexPatternsService,
FieldDescriptor,
} from '../../../../../../src/legacy/server/index_patterns/service';
import { BASE_API_URL } from '../../common';

type Document = Record<string, unknown>;

Expand All @@ -22,7 +23,7 @@ export async function initStatsRoute(setup: CoreSetup) {
const router = setup.http.createRouter();
router.post(
{
path: '/index_stats/{indexPatternTitle}',
path: `${BASE_API_URL}/index_stats/{indexPatternTitle}`,
validate: {
params: schema.object({
indexPatternTitle: schema.string(),
Expand Down
5 changes: 3 additions & 2 deletions x-pack/legacy/plugins/ml/server/new_platform/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Boom from 'boom';
import { i18n } from '@kbn/i18n';
import { ServerRoute } from 'hapi';
import { KibanaConfig, SavedObjectsLegacyService } from 'src/legacy/server/kbn_server';
import { HttpServiceSetup, Logger, PluginInitializerContext } from 'src/core/server';
import { Logger, PluginInitializerContext, CoreSetup } from 'src/core/server';
import { ElasticsearchPlugin } from 'src/legacy/core_plugins/elasticsearch';
import { XPackMainPlugin } from '../../../xpack_main/xpack_main';
import { addLinksToSampleDatasets } from '../lib/sample_data_sets';
Expand Down Expand Up @@ -61,7 +61,8 @@ import { fileDataVisualizerRoutes } from '../routes/file_data_visualizer';
// @ts-ignore: could not find declaration file for module
import { initMlServerLog, LogInitialization } from '../client/log';

export interface MlHttpServiceSetup extends HttpServiceSetup {
type CoreHttpSetup = CoreSetup['http'];
export interface MlHttpServiceSetup extends CoreHttpSetup {
route(route: ServerRoute | ServerRoute[]): void;
}

Expand Down

0 comments on commit c1ab169

Please sign in to comment.