Skip to content

Commit

Permalink
replace /elasticsearch/_msearch usages with custom endpoint (elastic#…
Browse files Browse the repository at this point in the history
  • Loading branch information
pgayvallet committed Aug 31, 2020
1 parent bfa87d2 commit 25a78ad
Show file tree
Hide file tree
Showing 5 changed files with 123 additions and 24 deletions.
28 changes: 10 additions & 18 deletions src/plugins/home/public/application/components/tutorial/tutorial.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,26 +201,18 @@ class TutorialUi extends React.Component {
* @return {Promise<string>}
*/
fetchEsHitsStatus = async (esHitsCheckConfig) => {
const searchHeader = JSON.stringify({ index: esHitsCheckConfig.index });
const searchBody = JSON.stringify({ query: esHitsCheckConfig.query, size: 1 });
const response = await fetch(this.props.addBasePath('/elasticsearch/_msearch'), {
method: 'post',
body: `${searchHeader}\n${searchBody}\n`,
headers: {
accept: 'application/json',
'content-type': 'application/x-ndjson',
'kbn-xsrf': 'kibana',
},
credentials: 'same-origin',
});

if (response.status > 300) {
const { http } = getServices();
try {
const response = await http.post('/api/home/hits_status', {
body: JSON.stringify({
index: esHitsCheckConfig.index,
query: esHitsCheckConfig.query,
}),
});
return response.count > 0 ? StatusCheckStates.HAS_DATA : StatusCheckStates.NO_DATA;
} catch (e) {
return StatusCheckStates.ERROR;
}

const results = await response.json();
const numHits = _.get(results, 'responses.[0].hits.hits.length', 0);
return numHits === 0 ? StatusCheckStates.NO_DATA : StatusCheckStates.HAS_DATA;
};

renderInstructionSetsToggle = () => {
Expand Down
29 changes: 23 additions & 6 deletions src/plugins/home/server/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@

import { registryForTutorialsMock, registryForSampleDataMock } from './plugin.test.mocks';
import { HomeServerPlugin } from './plugin';
import { coreMock } from '../../../core/server/mocks';
import { CoreSetup } from '../../../core/server';

type MockedKeys<T> = { [P in keyof T]: jest.Mocked<T[P]> };
import { coreMock, httpServiceMock } from '../../../core/server/mocks';

describe('HomeServerPlugin', () => {
beforeEach(() => {
Expand All @@ -33,8 +30,16 @@ describe('HomeServerPlugin', () => {
});

describe('setup', () => {
const mockCoreSetup: MockedKeys<CoreSetup> = coreMock.createSetup();
const initContext = coreMock.createPluginInitializerContext();
let mockCoreSetup: ReturnType<typeof coreMock.createSetup>;
let initContext: ReturnType<typeof coreMock.createPluginInitializerContext>;
let routerMock: ReturnType<typeof httpServiceMock.createRouter>;

beforeEach(() => {
mockCoreSetup = coreMock.createSetup();
routerMock = httpServiceMock.createRouter();
mockCoreSetup.http.createRouter.mockReturnValue(routerMock);
initContext = coreMock.createPluginInitializerContext();
});

test('wires up tutorials provider service and returns registerTutorial and addScopedTutorialContextFactory', () => {
const setup = new HomeServerPlugin(initContext).setup(mockCoreSetup, {});
Expand All @@ -52,6 +57,18 @@ describe('HomeServerPlugin', () => {
expect(setup.sampleData).toHaveProperty('addAppLinksToSampleDataset');
expect(setup.sampleData).toHaveProperty('replacePanelInSampleDatasetDashboard');
});

test('registers the `/api/home/hits_status` route', () => {
new HomeServerPlugin(initContext).setup(mockCoreSetup, {});

expect(routerMock.post).toHaveBeenCalledTimes(1);
expect(routerMock.post).toHaveBeenCalledWith(
expect.objectContaining({
path: '/api/home/hits_status',
}),
expect.any(Function)
);
});
});

describe('start', () => {
Expand Down
5 changes: 5 additions & 0 deletions src/plugins/home/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
import { UsageCollectionSetup } from '../../usage_collection/server';
import { capabilitiesProvider } from './capabilities_provider';
import { sampleDataTelemetry } from './saved_objects';
import { registerRoutes } from './routes';

interface HomeServerPluginSetupDependencies {
usageCollection?: UsageCollectionSetup;
Expand All @@ -41,6 +42,10 @@ export class HomeServerPlugin implements Plugin<HomeServerPluginSetup, HomeServe
public setup(core: CoreSetup, plugins: HomeServerPluginSetupDependencies): HomeServerPluginSetup {
core.capabilities.registerProvider(capabilitiesProvider);
core.savedObjects.registerType(sampleDataTelemetry);

const router = core.http.createRouter();
registerRoutes(router);

return {
tutorials: { ...this.tutorialsRegistry.setup(core) },
sampleData: { ...this.sampleDataRegistry.setup(core, plugins.usageCollection) },
Expand Down
60 changes: 60 additions & 0 deletions src/plugins/home/server/routes/fetch_es_hits_status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* 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 { schema } from '@kbn/config-schema';
import { IRouter } from 'src/core/server';

export const registerHitsStatusRoute = (router: IRouter) => {
router.post(
{
path: '/api/home/hits_status',
validate: {
body: schema.object({
index: schema.string(),
query: schema.recordOf(schema.string(), schema.any()),
}),
},
},
router.handleLegacyErrors(async (context, req, res) => {
const { index, query } = req.body;
const client = context.core.elasticsearch.client;

try {
const { body } = await client.asCurrentUser.search({
index,
size: 1,
body: {
query,
},
});
const count = body.hits.hits.length;

return res.ok({
body: {
count,
},
});
} catch (e) {
return res.badRequest({
body: e,
});
}
})
);
};
25 changes: 25 additions & 0 deletions src/plugins/home/server/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* 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 { IRouter } from 'src/core/server';
import { registerHitsStatusRoute } from './fetch_es_hits_status';

export const registerRoutes = (router: IRouter) => {
registerHitsStatusRoute(router);
};

0 comments on commit 25a78ad

Please sign in to comment.