Skip to content

Commit

Permalink
[Lens] Enable new context constants in formula (#158452)
Browse files Browse the repository at this point in the history
## Summary

Fixes #151827,  Fixes #117548

This PR contains constant function features in Lens formula:
* direct exposure of the `time_range()` - as suggested in #117548)

<img width="297" alt="Screenshot 2023-05-29 at 12 05 43"
src="https://github.com/elastic/kibana/assets/924948/8dbd63a6-c5ec-4177-a4a2-cc0770a495bc">

* `interval()` (as intended in #151827) 

<img width="359" alt="Screenshot 2023-05-29 at 12 04 18"
src="https://github.com/elastic/kibana/assets/924948/8c3a4637-bd23-4b4d-8a5f-36853ccbfee3">

* and `now()` (as suggested in
[here](#112851 (comment)))
functions in the formula input

<img width="364" alt="Screenshot 2023-05-25 at 14 30 14"
src="https://github.com/elastic/kibana/assets/924948/2137717b-44a0-4531-bcc2-1fbda40368ba">

A visual explanation of what each constant represent:
<img width="677" alt="Screenshot 2023-05-29 at 11 56 16"
src="https://github.com/elastic/kibana/assets/924948/b7b7e92c-b061-4cce-a77e-e7baeab323a8">


Documentation:

<img width="546" alt="Screenshot 2023-05-31 at 12 59 40"
src="https://github.com/elastic/kibana/assets/924948/1fea7e88-6e4f-4958-949f-6b71a770cd44">



Some example usage
<img width="683" alt="Screenshot 2023-05-25 at 13 33 26"
src="https://github.com/elastic/kibana/assets/924948/e03442ab-0062-4999-8a38-c00a66b3b13b">

TSVB => Lens with `params._interval` support:

![tsvb_to_lens_with_interval](https://github.com/elastic/kibana/assets/924948/6ea86bd1-8e71-4928-b2e2-7ad27537b33d)

**Notes**: 

* context values work like static values, with the same limits,
therefore it is not possible to build a date histogram with a context
value alone (i.e. a formula with only `interval()` or `now()`). It works
ok without the `Date Histogram` dimension.
* The `interval()` function will report an error if used without a
configured `Date Histogram` dimension:

<img width="671" alt="Screenshot 2023-05-29 at 12 14 13"
src="https://github.com/elastic/kibana/assets/924948/ca67f102-35bb-4e4d-ab16-15d1be4cadcc">

* The `interval()` function does not take into account different bucket
interval size (i.e. DST changes, leap years, etc...), rather return the
same value to all the buckets. This is the same behaviour as in TSVB,
but in Lens it can be a problem due to the usage of `calendar_interval`.

* I had to duplicate a couple of function from the helpers to avoid
issues with tests. I've tried a different organization of the helpers
(between pure vs impure fns) but that took longer than expected, so I
would defer this task later in another PR.

<details>
  <summary>General approach with `constant(...)` removed</summary>
* a more general approach using `constants(value="...")`
<img width="301" alt="Screenshot 2023-05-29 at 12 07 23"
src="https://github.com/elastic/kibana/assets/924948/0a800aa4-8db5-4055-996d-344d37adfc01">
</details>


A cloud deployment has been created to test both approaches here. Let me
know which one do you prefer cc @elastic/kibana-visualizations

### 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
- [ ] 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&mdash;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&mdash;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)

---------

Co-authored-by: kibanamachine <[email protected]>
Co-authored-by: Stratoula Kalafateli <[email protected]>
  • Loading branch information
3 people authored Jun 6, 2023
1 parent e2a060d commit 3600f97
Show file tree
Hide file tree
Showing 33 changed files with 933 additions and 192 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,34 @@ describe('convertMathToFormulaColumn', () => {
expect(convertMathToFormulaColumn(...input)).toEqual(expect.objectContaining(expected));
}
});

it.each`
expression | expected
${'params._interval'} | ${'interval()'}
${'params._interval + params._interval'} | ${'interval() + interval()'}
${'params._all'} | ${null}
${'params._all + params.interval'} | ${null}
${'params._timestamp'} | ${null}
${'params._timestamp + params.interval'} | ${null}
${'params._index'} | ${null}
${'params._index + params.interval'} | ${null}
`(`handle special params cases: $expression`, ({ expression, expected }) => {
expect(
convertMathToFormulaColumn({
series,
metrics: [{ ...mathMetric, script: expression }],
dataView,
})
).toEqual(
expected
? expect.objectContaining({
meta: { metricId: 'some-id-1' },
operationType: 'formula',
params: { formula: expected },
})
: expected
);
});
});

describe('convertOtherAggsToFormulaColumn', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ export const convertMathToFormulaColumn = (
return null;
}

// now replace the _interval with the new interval() formula
if (script.includes('params._interval')) {
script = script.replaceAll('params._interval', 'interval()');
}

const scripthasNoStaticNumber = isNaN(Number(script));
if (script.includes('params') || !scripthasNoStaticNumber) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ jest.mock('./dimension_panel/reference_editor', () => ({
ReferenceEditor: () => null,
}));

const nowInstant = new Date();

const fieldsOne = [
{
name: 'timestamp',
Expand Down Expand Up @@ -365,7 +367,14 @@ describe('IndexPattern Data Source', () => {
it('should generate an empty expression when no columns are selected', async () => {
const state = FormBasedDatasource.initialize();
expect(
FormBasedDatasource.toExpression(state, 'first', indexPatterns, dateRange, 'testing-seed')
FormBasedDatasource.toExpression(
state,
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
)
).toEqual(null);
});

Expand Down Expand Up @@ -395,6 +404,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
)
).toEqual({
Expand Down Expand Up @@ -450,6 +460,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
)
).toMatchInlineSnapshot(`
Expand Down Expand Up @@ -637,6 +648,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
expect(ast.chain[1].arguments.timeFields).toEqual(['timestamp', 'another_datefield']);
Expand Down Expand Up @@ -678,6 +690,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
expect((ast.chain[1].arguments.aggs[1] as Ast).chain[0].arguments.timeShift).toEqual(['1d']);
Expand Down Expand Up @@ -891,6 +904,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
const count = (ast.chain[1].arguments.aggs[1] as Ast).chain[0];
Expand Down Expand Up @@ -961,6 +975,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
expect(ast.chain[1].arguments.aggs[0]).toMatchInlineSnapshot(`
Expand Down Expand Up @@ -1091,6 +1106,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
const timeScaleCalls = ast.chain.filter((fn) => fn.function === 'lens_time_scale');
Expand Down Expand Up @@ -1162,6 +1178,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
const filteredMetricAgg = (ast.chain[1].arguments.aggs[0] as Ast).chain[0].arguments;
Expand Down Expand Up @@ -1219,6 +1236,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
const formatIndex = ast.chain.findIndex((fn) => fn.function === 'lens_format_column');
Expand Down Expand Up @@ -1273,6 +1291,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
expect(ast.chain[1].arguments.metricsAtAllLevels).toEqual([false]);
Expand Down Expand Up @@ -1318,6 +1337,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
expect(ast.chain[1].arguments.timeFields).toEqual(['timestamp']);
Expand Down Expand Up @@ -1381,6 +1401,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
);

Expand Down Expand Up @@ -1455,6 +1476,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;

Expand Down Expand Up @@ -1525,6 +1547,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;

Expand Down Expand Up @@ -1636,6 +1659,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
// @ts-expect-error we can't isolate just the reference type
Expand Down Expand Up @@ -1675,6 +1699,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;

Expand Down Expand Up @@ -1768,6 +1793,7 @@ describe('IndexPattern Data Source', () => {
'first',
indexPatterns,
dateRange,
nowInstant,
'testing-seed'
) as Ast;
const chainLength = ast.chain.length;
Expand Down
19 changes: 14 additions & 5 deletions x-pack/plugins/lens/public/datasources/form_based/form_based.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { flatten, isEqual } from 'lodash';
import type { DataViewsPublicPluginStart, DataView } from '@kbn/data-views-plugin/public';
import type { IndexPatternFieldEditorStart } from '@kbn/data-view-field-editor-plugin/public';
import { KibanaContextProvider, KibanaThemeProvider } from '@kbn/kibana-react-plugin/public';
import { DataPublicPluginStart, ES_FIELD_TYPES } from '@kbn/data-plugin/public';
import { DataPublicPluginStart, ES_FIELD_TYPES, UI_SETTINGS } from '@kbn/data-plugin/public';
import { VisualizeFieldContext } from '@kbn/ui-actions-plugin/public';
import { ChartsPluginSetup } from '@kbn/charts-plugin/public';
import { UiActionsStart } from '@kbn/ui-actions-plugin/public';
Expand Down Expand Up @@ -186,7 +186,7 @@ export function getFormBasedDatasource({
return loadInitialState({
persistedState,
references,
defaultIndexPatternId: core.uiSettings.get('defaultIndex'),
defaultIndexPatternId: uiSettings.get('defaultIndex'),
storage,
initialContext,
indexPatternRefs,
Expand Down Expand Up @@ -425,8 +425,16 @@ export function getFormBasedDatasource({
return fields;
},

toExpression: (state, layerId, indexPatterns, dateRange, searchSessionId) =>
toExpression(state, layerId, indexPatterns, uiSettings, dateRange, searchSessionId),
toExpression: (state, layerId, indexPatterns, dateRange, nowInstant, searchSessionId) =>
toExpression(
state,
layerId,
indexPatterns,
uiSettings,
dateRange,
nowInstant,
searchSessionId
),

renderLayerSettings(domElement, props) {
render(
Expand Down Expand Up @@ -853,7 +861,8 @@ export function getFormBasedDatasource({
layer,
columnId,
frameDatasourceAPI.dataViews.indexPatterns[layer.indexPatternId],
frameDatasourceAPI.dateRange
frameDatasourceAPI.dateRange,
uiSettings.get(UI_SETTINGS.HISTOGRAM_BAR_TARGET)
);
}
);
Expand Down
Loading

0 comments on commit 3600f97

Please sign in to comment.