[Canvas] Migrate expression runner from bfetch to an HTTP route (#191031)

## Summary

Resolves https://github.com/elastic/kibana/issues/190267.

Moves the Canvas expression runner off of `bfetch` and onto the core
`http` router.

### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
This commit is contained in:
Lukas Olson 2024-08-29 01:28:01 +02:00 committed by GitHub
parent f29bf1c311
commit f1742dbe8c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 43 additions and 35 deletions

View file

@ -12,7 +12,6 @@
"canvas"
],
"requiredPlugins": [
"bfetch",
"charts",
"data",
"dataViews",

View file

@ -27,7 +27,6 @@ import { UiActionsSetup, UiActionsStart } from '@kbn/ui-actions-plugin/public';
import { EmbeddableStart } from '@kbn/embeddable-plugin/public';
import { UsageCollectionSetup } from '@kbn/usage-collection-plugin/public';
import { Start as InspectorStart } from '@kbn/inspector-plugin/public';
import { BfetchPublicSetup } from '@kbn/bfetch-plugin/public';
import { PresentationUtilPluginStart } from '@kbn/presentation-util-plugin/public';
import { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public';
import { ContentManagementPublicStart } from '@kbn/content-management-plugin/public';
@ -53,7 +52,6 @@ export interface CanvasSetupDeps {
expressions: ExpressionsSetup;
home?: HomePublicPluginSetup;
usageCollection?: UsageCollectionSetup;
bfetch: BfetchPublicSetup;
charts: ChartsPluginSetup;
uiActions: UiActionsSetup;
}

View file

@ -21,7 +21,7 @@ export const setupExpressions = async ({
coreSetup: CoreSetup;
setupPlugins: CanvasSetupDeps;
}) => {
const { expressions, bfetch } = setupPlugins;
const { expressions } = setupPlugins;
const loadServerFunctionWrappers = async () => {
if (!cached) {
@ -29,7 +29,6 @@ export const setupExpressions = async ({
const serverFunctionList = await coreSetup.http.get<any>(API_ROUTE_FUNCTIONS, {
version: '1',
});
const batchedFunction = bfetch.batchedFunction({ url: API_ROUTE_FUNCTIONS });
const { serialize } = serializeProvider(expressions.getTypes());
// For every sever-side function, register a client-side
@ -43,7 +42,10 @@ export const setupExpressions = async ({
const fn = () => ({
...serverFunctionList[functionName],
fn: (input: any, args: any) => {
return batchedFunction({ functionName, args, context: serialize(input) });
return coreSetup.http.post(API_ROUTE_FUNCTIONS, {
body: JSON.stringify({ functionName, args, context: serialize(input) }),
version: '1',
});
},
});

View file

@ -11,7 +11,6 @@ import {
PluginStart as DataPluginStart,
} from '@kbn/data-plugin/server';
import { ExpressionsServerSetup } from '@kbn/expressions-plugin/server';
import { BfetchServerSetup } from '@kbn/bfetch-plugin/server';
import { UsageCollectionSetup } from '@kbn/usage-collection-plugin/server';
import { HomeServerPluginSetup } from '@kbn/home-plugin/server';
import { EmbeddableSetup } from '@kbn/embeddable-plugin/server';
@ -33,7 +32,6 @@ interface PluginsSetup {
embeddable: EmbeddableSetup;
features: FeaturesPluginSetup;
home: HomeServerPluginSetup;
bfetch: BfetchServerSetup;
data: DataPluginSetup;
reporting?: ReportingServerPluginSetup;
usageCollection?: UsageCollectionSetup;
@ -81,7 +79,6 @@ export class CanvasPlugin implements Plugin {
initRoutes({
router: canvasRouter,
expressions: expressionsSetup,
bfetch: plugins.bfetch,
logger: this.logger,
});

View file

@ -6,6 +6,7 @@
*/
import { serializeProvider } from '@kbn/expressions-plugin/common';
import { schema } from '@kbn/config-schema';
import { RouteInitializerDeps } from '..';
import { API_ROUTE_FUNCTIONS } from '../../../common/lib/constants';
@ -32,7 +33,43 @@ export function initializeGetFunctionsRoute(deps: RouteInitializerDeps) {
}
export function initializeBatchFunctionsRoute(deps: RouteInitializerDeps) {
const { bfetch, expressions } = deps;
const { router, expressions } = deps;
router.versioned
.post({
path: API_ROUTE_FUNCTIONS,
access: 'internal',
})
.addVersion(
{
version: '1',
validate: {
request: {
body: schema.object({
functionName: schema.string(),
args: schema.object({}, { unknowns: 'allow' }),
context: schema.object({}, { unknowns: 'allow' }),
}),
},
},
},
async (context, request, response) => {
const handlers = {
environment: 'server',
};
const fnCall: FunctionCall = {
functionName: request.body.functionName,
args: request.body.args,
context: request.body.context,
};
const result = await runFunction(handlers, fnCall);
if (typeof result === 'undefined') {
throw new Error(`Function ${fnCall.functionName} did not return anything.`);
}
return response.ok({
body: result,
});
}
);
async function runFunction(handlers: { environment: string }, fnCall: FunctionCall) {
const { functionName, args, context } = fnCall;
@ -46,23 +83,4 @@ export function initializeBatchFunctionsRoute(deps: RouteInitializerDeps) {
return result;
}
/**
* Register an endpoint that executes a batch of functions, and streams the
* results back using ND-JSON.
*/
bfetch.addBatchProcessingRoute(API_ROUTE_FUNCTIONS, (request) => {
return {
onBatchItem: async (fnCall: FunctionCall) => {
const handlers = {
environment: 'server',
};
const result = await runFunction(handlers, fnCall);
if (typeof result === 'undefined') {
throw new Error(`Function ${fnCall.functionName} did not return anything.`);
}
return result;
},
};
});
}

View file

@ -7,7 +7,6 @@
import { IRouter, Logger } from '@kbn/core/server';
import { ExpressionsServerSetup } from '@kbn/expressions-plugin/server';
import { BfetchServerSetup } from '@kbn/bfetch-plugin/server';
import { initCustomElementsRoutes } from './custom_elements';
import { initShareablesRoutes } from './shareables';
import { initWorkpadRoutes } from './workpad';
@ -19,7 +18,6 @@ export interface RouteInitializerDeps {
router: IRouter<CanvasRouteHandlerContext>;
logger: Logger;
expressions: ExpressionsServerSetup;
bfetch: BfetchServerSetup;
}
export function initRoutes(deps: RouteInitializerDeps) {

View file

@ -10,13 +10,11 @@ import {
loggingSystemMock,
elasticsearchServiceMock,
} from '@kbn/core/server/mocks';
import { bfetchPluginMock } from '@kbn/bfetch-plugin/server/mocks';
import { expressionsPluginMock } from '@kbn/expressions-plugin/server/mocks';
export function getMockedRouterDeps() {
const httpService = httpServiceMock.createSetupContract();
const elasticsearch = elasticsearchServiceMock.createSetup();
const bfetch = bfetchPluginMock.createSetupContract();
const expressions = expressionsPluginMock.createSetupContract();
const router = httpService.createRouter();
@ -24,7 +22,6 @@ export function getMockedRouterDeps() {
router,
expressions,
elasticsearch,
bfetch,
logger: loggingSystemMock.create().get(),
};
}

View file

@ -27,7 +27,6 @@
"kbn_references": [
{ "path": "../../../src/setup_node_env/tsconfig.json" },
"@kbn/core",
"@kbn/bfetch-plugin",
"@kbn/charts-plugin",
"@kbn/data-plugin",
"@kbn/share-plugin",