Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Lens] Show underlying data embeddable #15

Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
141 commits
Select commit Hold shift + click to select a range
7dbedb9
starting to gather necessary data in embeddable
drewdaemon Mar 3, 2022
10b88d5
Computing view underlying data args
drewdaemon Mar 3, 2022
52997f6
working now
drewdaemon Mar 4, 2022
5792deb
Add compatibility check for action
drewdaemon Mar 4, 2022
9661db2
Move action creator to own module
drewdaemon Mar 4, 2022
7c6d314
[Fleet] Retry Saved Object import on conflict error (#126900)
hop-dev Mar 7, 2022
3c90147
[Console] Support auto-complete for data streams (#126235)
mibragimov Mar 7, 2022
c9e66b8
[Cloud Posture] add filterting for benchmark (#126980)
CohenIdo Mar 7, 2022
bc0d9e7
[Presentation] Fix some bugs with services dependency injection (#126…
Mar 7, 2022
f12891e
:bug: Handle case of undefined fitting for line/area (#126891)
dej611 Mar 7, 2022
0807b53
fix data view load err msg (#126974)
mattkime Mar 7, 2022
0adb328
[data views] Reenable data view validation functional test (#125892)
mattkime Mar 7, 2022
8b82657
[data views] functional tests to typescript (#126977)
mattkime Mar 7, 2022
d0b64d9
[ML] Add API tests for analytics jobs_exist and new_job_caps endpoint…
peteharverson Mar 7, 2022
3fe1270
[Lens][Embeddable] Make Embeddable resilient when toggling actions (#…
dej611 Mar 7, 2022
04f956d
[Cloud Posture] Update cloud security posture code owners (#127004)
ari-aviran Mar 7, 2022
d5a1cdc
[App Search] Add an audit modal to show last changes on a modal. (#12…
efegurkan Mar 7, 2022
90f0d8d
[Reporting] Use the logger from Core instead of a wrapper (#126740)
tsullivan Mar 7, 2022
a79562a
[SecuritySolution] Alerts table Fields Browser revamp (#126105)
semd Mar 7, 2022
eca203c
[AggConfigs] Add TopMetrics agg (#125936)
Dosant Mar 7, 2022
73f7ac4
Fix Pagination is not working correctly for host by risk under hosts …
machadoum Mar 7, 2022
004f0d4
[type-summarizer/integration] fix flaky tests (#127038)
Mar 7, 2022
a4febd7
Allow access to ElasticsearchClient's child function from core's TS i…
mikecote Mar 7, 2022
23ac12b
[Workplace Search] Connect button no longer gets stuck on connection …
sphilipse Mar 7, 2022
f47f89b
[Workplace Search] Make SharePoint Online users start with the Oauth …
sphilipse Mar 7, 2022
ccf16e9
[Security Solution] Add metadta doc and capabilities to telemetry (#1…
kevinlog Mar 7, 2022
8a8bfd5
[Maps] Fixed double click issue when deleting a shape (#124661)
maksimkovalev Mar 7, 2022
f85f809
Add retries (#126480)
qn895 Mar 7, 2022
fd55bbd
Marking more methods on the alerting task runner as private (#124546)
kobelb Mar 7, 2022
ff90bd4
Use execution context for Fullstory (#126780)
Mar 7, 2022
935fcc2
skip flaky suite (#126658)
mistic Mar 7, 2022
b2e419d
[Reporting] Improve error logging for rescheduled jobs (#126737)
tsullivan Mar 7, 2022
629e0f3
skip flaky suite (#126027)
mistic Mar 7, 2022
0640782
[ML] Adding data recognizer module config cache (#126338)
jgowdyelastic Mar 7, 2022
de3ae9b
Remove License Requirement for Enterprise Search App Search Meta Engi…
markjhoy Mar 7, 2022
a24b1fc
Don't submit empty seed_urls or sitemap_urls when making a partial cr…
Mar 7, 2022
cb70888
[Telemetry] Check permissions when requesting telemetry (#126238)
afharo Mar 7, 2022
c0a653d
[Alerting] Adding functional tests for alerting and actions telemetry…
ymao1 Mar 7, 2022
2c7fe22
Revert "[CI] Expand spot instance trial a bit (#126928)"
brianseeders Mar 7, 2022
9b79234
Revert "[ci] Configure hourly pipeline for a small spot instance tria…
brianseeders Mar 7, 2022
be7ff2c
[type-summarizer] always use normalized paths, fix windows compat (#1…
Mar 7, 2022
0821c31
[ftr] implement support for accessing ES through CCS (#126547)
Mar 7, 2022
2f83c65
Fix session cleanup test (#126966)
jportner Mar 7, 2022
18a5344
[Security Solution][Rules] - Remove rule selection for read only user…
yctercero Mar 8, 2022
50ba761
[Security Solution][Lists] - Updates exception flyout edit error mess…
yctercero Mar 8, 2022
e86d7ae
[Security Solution][Lists] - Add missing privileges callout to except…
yctercero Mar 8, 2022
962347f
[Lens] Fixed flakiness on runtime fields' appearance on the list (#12…
stratoula Mar 8, 2022
fc3aedc
Hide Enterprise search panel when no nodes are present (#127100)
matschaffer Mar 8, 2022
5ad355e
Remove all cases related code from timelines (#127003)
academo Mar 8, 2022
720fbed
[Gauge] Vis editors gauge legacy percent mode. (#126318)
Kuznietsov Mar 8, 2022
813ba85
Fix copy and pasted renderer user_name test (#126663)
machadoum Mar 8, 2022
dd4652b
APM Synthtrace: Introduce new DSL using generators (#123454)
Mpdreamz Mar 8, 2022
bf12417
[Security Solution] Add User Risk tab to Users page (#126434)
machadoum Mar 8, 2022
d7c26c1
create rules config based on rules status and update package policy (…
CohenIdo Mar 8, 2022
a5f410e
[Stack Monitoring] add back api integration tests and update esArchiv…
neptunian Mar 8, 2022
7936381
[Cloud Posture] Add blank page graphic (#126750)
ari-aviran Mar 8, 2022
0a06242
removes flakiness from prebuilt rules (#127137)
MadameSheema Mar 8, 2022
1f514d7
[eslint] automatically determine dev packages (#127089)
Mar 8, 2022
015be5f
Update babel (main) (#126871)
renovate[bot] Mar 8, 2022
be0bd54
[APM] set default value for Infrastructure View flag to false (#127127)
MiriamAparicio Mar 8, 2022
8e383bd
[Reporting] Copy updates for warning notifications (#126562)
jloleysens Mar 8, 2022
3dd05d6
unksips cypress creation (#127024)
MadameSheema Mar 8, 2022
5cab9e8
[Cases] Add docs for new hooks (#127133)
academo Mar 8, 2022
a76fef1
Stop showing the warning toast during security solution cypress tests…
kqualters-elastic Mar 8, 2022
ed4c19c
Use debounce instead of async url update to remove app state from URL…
ThomThomson Mar 8, 2022
192309f
Typescript upgrade to 4.6.2 (#126935)
Mar 8, 2022
6c4e208
make getViewUnderlyingDataArgs synchronous
drewdaemon Mar 8, 2022
3864f63
[SO migrations] exit early if cluster routing allocation is disabled …
TinaHeiligers Mar 8, 2022
c4f8fc5
[shared-ux] CODEOWNERS update (#127169)
clintandrewhall Mar 8, 2022
574a38f
[Security Solution] Fixes and unskips export rule test (#127060)
MadameSheema Mar 8, 2022
b5e1945
[CTI] Enable IM Rule Preview (#126651)
ecezalp Mar 8, 2022
2fa485a
123580 o11 rules page (#124132)
mgiota Mar 8, 2022
2bb237f
Add Playwright Service and New User Journeys for Performance tests (#…
suchcodemuchwow Mar 8, 2022
7a00d24
[CORE] Allow find saved object to query on _id (#126933)
XavierM Mar 8, 2022
79905ba
[DOCS] Add Stack Management cases (#126960)
lcawl Mar 8, 2022
849542e
[Lens] data layer & reference layer as separate types (#126885)
mbondyra Mar 8, 2022
0af4578
[ResponseOps] Add new plugin to collect additional kibana monitoring …
Mar 8, 2022
e3e5df6
[Security Solution][Lists] - Disable upload value lists if user is ki…
yctercero Mar 8, 2022
daace92
[kbn/pm] add timings for more parts of bootstrap (#127157)
Mar 8, 2022
0410d1f
Update dependency chromedriver to v99 (#127079)
renovate[bot] Mar 8, 2022
6f5cd00
[App Search] Move to tabbed single tabbed JSON flyout with upload and…
scottybollinger Mar 8, 2022
68ed188
[Security Solution] Adds CCS privileges warning enable switch in adva…
dplumlee Mar 8, 2022
bb1834d
[DOCS] Adds note for data source performance impact (#127184)
KOTungseth Mar 8, 2022
1cb82f5
skip failing test suite (#126949)
kibanamachine Mar 8, 2022
8c075c5
Increase timeout for Jest integration tests (#127220)
Mar 8, 2022
81eec7c
Made fix to broken test. Deleted all existing pipelines before test s…
cuff-links Mar 8, 2022
7923667
[build] Up compression quality (#127064)
jbudz Mar 8, 2022
ad0eb60
[kbn/generate] add basic package generator (#127095)
Mar 9, 2022
f89d531
skip flaky suite (#123372)
mistic Mar 9, 2022
b9b4dc0
Remove deprecated & unused `SavedObjectsImportFailure.title` (#127043)
afharo Mar 9, 2022
22369fd
Remove deprecated & unused `public-AsyncPlugin` (#127048)
afharo Mar 9, 2022
b76370d
Bump dependencies (#127238)
jportner Mar 9, 2022
133e57f
[Lens] Show underlying data editor navigation (#125983)
dej611 Mar 9, 2022
565454c
Remove deprecated & unused `HttpServiceSetup.auth` (#127056)
afharo Mar 9, 2022
d1f0d23
remove opacity for fitting line series (#127176)
flash1293 Mar 9, 2022
eb4cd4a
Remove deprecated & unused `ElasticsearchServiceStart.legacy` (#127050)
afharo Mar 9, 2022
06e453e
add updatedAt to SimpleSavedObject (#126359)
orouz Mar 9, 2022
030816d
[Reporting] Capture Kibana stopped error (#127017)
jloleysens Mar 9, 2022
f74c894
Extend yarn es: plugin support + adding secure files to es keystore (…
Mpdreamz Mar 9, 2022
f5556f1
[Lens] Fix multi terms fields validation (#126618)
dej611 Mar 9, 2022
2836018
[Gauge] Custom color support (#126882)
Kuznietsov Mar 9, 2022
9f880f2
[Lens] Switch to unified metric renderer (#126019)
VladLasitsa Mar 9, 2022
6bcce44
[Flaky tests] Metric's server collector's integration tests (#127139)
afharo Mar 9, 2022
299b21b
[Unified observability] Migrate deprecated IndexPattern types (#124962)
Mar 9, 2022
b32f1da
[Cloud Posture] Update resource type field query #127256
JordanSh Mar 9, 2022
b20a364
[Cases] Remove temporal public methods from the cases plugin (#127248)
academo Mar 9, 2022
8dcf1ad
[TSVB2Lens] Supports static values (#126903)
stratoula Mar 9, 2022
c149966
Add instructions for connecting to local ES cluster started with `yar…
sorenlouv Mar 9, 2022
671960f
[Cloud Posture] Add rules page (#126990)
orouz Mar 9, 2022
1568eed
[Fleet] Fix empty assets on package install (#127070)
nchaulet Mar 9, 2022
12f9e3c
[APM] Load list of services from ML/terms enum (#126581)
dgieselaar Mar 9, 2022
e930db1
[Cases] Fix persistent title error in EditableTitle (#127254)
academo Mar 9, 2022
2e6d6c8
add new cluster id (#127265)
suchcodemuchwow Mar 9, 2022
b2d649f
Updates advanced settings `kibana.json` team ownership (#127186)
TinaHeiligers Mar 9, 2022
b1d6f87
[APM] Invalidate keys created by other when user has privileges (#12…
MiriamAparicio Mar 9, 2022
46a739e
[Lens] Fix type check failure (#127277)
stratoula Mar 9, 2022
e932d83
[Archive Migration] dashboard/current/kibana (#126293)
Mar 9, 2022
b7f3271
[Lens] Improve Datatable content height with custom row height (#127134)
dej611 Mar 9, 2022
5217b9a
skip failing test (#127076)
Mar 9, 2022
d2c9a62
Enable local mtls (#127116)
lucasfcosta Mar 9, 2022
488d939
[ci] Remove package testing jenkins source (#127300)
jbudz Mar 9, 2022
abc734f
[APM] Fix tooltip focus on service map (#127138)
MiriamAparicio Mar 9, 2022
ee369db
ci: discard configuration step and parallelism for performance test p…
suchcodemuchwow Mar 9, 2022
6280ca1
[Security Solution][Endpoint] Create endpoint action and responses fr…
ashokaditya Mar 9, 2022
f169fe7
[Fleet] Use docker registry in fleet cloud preconfiguration test (#12…
nchaulet Mar 9, 2022
5e8d66e
Remove logs.tar.gz (#127299)
jbudz Mar 9, 2022
e009115
[Fleet] Fix ES error during filtering on agent status (#127234)
jen-huang Mar 9, 2022
aa82d75
[Fleet] Remove dependency on `fieldFormatters` to fix Last activity a…
jen-huang Mar 9, 2022
ab109db
[package testing] Update networking profile to account for virtualbox…
jbudz Mar 9, 2022
0ba204b
[Workplace Search] Connect button now displays correct copy (#127291)
sphilipse Mar 9, 2022
0bc7a2e
[DOCS] Adds missing `monitoring.cluster_alerts.email_notifications.em…
KOTungseth Mar 9, 2022
e086d64
[ML] Space aware trained models (#123487)
jgowdyelastic Mar 9, 2022
67e52e7
[ResponseOps] Exclude RBAC from SIEM for alerts search strategy (#126…
Mar 9, 2022
ca447c6
[Security Solution] Adds posix eventing model fields to generator scr…
kqualters-elastic Mar 9, 2022
b2cd94d
[Controls] Improve controls empty state (#125728)
Heenawter Mar 9, 2022
2da341c
Unskip CTI tests (#127313)
nkhristinin Mar 9, 2022
8782ced
[SharedUX] Migrate PageTemplate > NoDataPage > NoDataCard (#127025)
Mar 9, 2022
6456d18
Cancel search queries on timeout regardless of rule type (#124374)
mikecote Mar 9, 2022
2bc710e
Merge branch 'main' of github.com:elastic/kibana into show-underlying…
drewdaemon Mar 9, 2022
f3a5b41
lazy-load view-underlying-data args
drewdaemon Mar 10, 2022
868f0e8
only initialize datasource state the first time
drewdaemon Mar 10, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ export function getLayerMetaInfo(
currentDatasource: Datasource | undefined,
datasourceState: unknown,
activeData: TableInspectorAdapter | undefined,
capabilities: RecursiveReadonly<Capabilities>
capabilities: RecursiveReadonly<{
navLinks: Capabilities['navLinks'];
discover?: Capabilities['discover'];
}>
): { meta: LayerMetaInfo | undefined; isVisible: boolean; error: string | undefined } {
const isVisible = Boolean(capabilities.navLinks?.discover && capabilities.discover?.show);
// If Multiple tables, return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export class EditorFrameService {
private readonly datasources: Array<Datasource | (() => Promise<Datasource>)> = [];
private readonly visualizations: Array<Visualization | (() => Promise<Visualization>)> = [];

private loadDatasources = () => collectAsyncDefinitions(this.datasources);
public loadDatasources = () => collectAsyncDefinitions(this.datasources);
public loadVisualizations = () => collectAsyncDefinitions(this.visualizations);

/**
Expand Down
201 changes: 174 additions & 27 deletions x-pack/plugins/lens/public/embeddable/embeddable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
import type { PaletteOutput } from 'src/plugins/charts/public';
import type { Start as InspectorStart } from 'src/plugins/inspector/public';

import { Subscription } from 'rxjs';
import { Subject, Subscription } from 'rxjs';
import { toExpression, Ast } from '@kbn/interpreter';
import { RenderMode } from 'src/plugins/expressions';
import { map, distinctUntilChanged, skip } from 'rxjs/operators';
Expand Down Expand Up @@ -56,21 +56,25 @@ import {
LensTableRowContextMenuEvent,
VisualizationMap,
Visualization,
DatasourceMap,
Datasource,
} from '../types';

import { IndexPatternsContract } from '../../../../../src/plugins/data/public';
import { getEditPath, DOC_TYPE, PLUGIN_ID } from '../../common';
import type {
Capabilities,
IBasePath,
KibanaExecutionContext,
ThemeServiceStart,
} from '../../../../../src/core/public';
import { LensAttributeService } from '../lens_attribute_service';
import type { ErrorMessage } from '../editor_frame_service/types';
import type { ErrorMessage, TableInspectorAdapter } from '../editor_frame_service/types';
import { getLensInspectorService, LensInspector } from '../lens_inspector_service';
import { SharingSavedObjectProps } from '../types';
import type { SpacesPluginStart } from '../../../spaces/public';
import { inferTimeField } from '../utils';
import { getActiveDatasourceIdFromDoc, getIndexPatternsObjects, inferTimeField } from '../utils';
import { getLayerMetaInfo, combineQueryAndFilters } from '../app_plugin/show_underlying_data';

export type LensSavedObjectAttributes = Omit<Document, 'savedObjectId' | 'type'>;

Expand Down Expand Up @@ -115,19 +119,33 @@ export interface LensEmbeddableDeps {
) => Promise<{ ast: Ast | null; errors: ErrorMessage[] | undefined }>;
injectFilterReferences: FilterManager['inject'];
visualizationMap: VisualizationMap;
datasourceMap: DatasourceMap;
indexPatternService: IndexPatternsContract;
expressionRenderer: ReactExpressionRendererType;
timefilter: TimefilterContract;
basePath: IBasePath;
inspector: InspectorStart;
getTrigger?: UiActionsStart['getTrigger'] | undefined;
getTriggerCompatibleActions?: UiActionsStart['getTriggerCompatibleActions'];
capabilities: { canSaveVisualizations: boolean; canSaveDashboards: boolean };
capabilities: {
canSaveVisualizations: boolean;
canSaveDashboards: boolean;
navLinks: Capabilities['navLinks'];
discover?: Capabilities['discover'];
};
usageCollection?: UsageCollectionSetup;
spaces?: SpacesPluginStart;
theme: ThemeServiceStart;
}

export interface ViewUnderlyingDataArgs {
indexPatternId: string;
timeRange: TimeRange;
filters: Filter[];
query: Query | undefined;
columns: string[];
}

const getExpressionFromDocument = async (
document: Document,
documentToExpression: LensEmbeddableDeps['documentToExpression']
Expand All @@ -139,6 +157,52 @@ const getExpressionFromDocument = async (
};
};

function getViewUnderlyingDataArgs({
activeDatasource,
activeDatasourceState,
activeData,
indexPatterns,
capabilities,
query,
filters,
timeRange,
}: {
activeDatasource: Datasource;
activeDatasourceState: unknown;
activeData: TableInspectorAdapter | undefined;
indexPatterns: IndexPattern[];
capabilities: LensEmbeddableDeps['capabilities'];
query: Query;
filters: Filter[];
timeRange: TimeRange;
}) {
const { error, meta } = getLayerMetaInfo(
activeDatasource,
activeDatasourceState,
activeData,
capabilities
);

if (error || !meta) {
return;
}

const { filters: newFilters, query: newQuery } = combineQueryAndFilters(
query,
filters,
meta,
indexPatterns
);

return {
indexPatternId: meta.id,
timeRange,
filters: newFilters,
query: newQuery,
columns: meta.columns,
};
}

export class Embeddable
extends AbstractEmbeddable<LensEmbeddableInput, LensEmbeddableOutput>
implements ReferenceOrValueEmbeddable<LensByValueInput, LensByReferenceInput>
Expand Down Expand Up @@ -167,13 +231,26 @@ export class Embeddable
);
}

private externalSearchContext: {
private externalSearchContext?: {
timeRange?: TimeRange;
query?: Query;
filters?: Filter[];
searchSessionId?: string;
};

private activeDataInfo: {
activeData?: TableInspectorAdapter;
activeDatasource?: Datasource;
activeDatasourceState?: unknown;
} = {};

private indexPatterns: IndexPattern[] = [];

private viewUnderlyingDataArgs?: ViewUnderlyingDataArgs;

private waitVUDArgsLoaded: Promise<boolean>;
private markVUDArgsLoaded: (loaded: boolean) => void;

constructor(
private deps: LensEmbeddableDeps,
initialInput: LensEmbeddableInput,
Expand All @@ -186,9 +263,29 @@ export class Embeddable
},
parent
);

const _vudSubscription = new Subject<boolean>();

this.markVUDArgsLoaded = (loaded: boolean) => {
_vudSubscription.next(loaded);
_vudSubscription.complete();
};

this.waitVUDArgsLoaded = new Promise<boolean>((resolve) => {
const subscription = _vudSubscription.subscribe((loaded) => {
resolve(loaded);
subscription.unsubscribe();
});
});

this.lensInspector = getLensInspectorService(deps.inspector);
this.expressionRenderer = deps.expressionRenderer;
this.initializeSavedVis(initialInput).then(() => this.onContainerStateChanged(initialInput));
this.initializeSavedVis(initialInput)
.then(() => this.initializeOutput())
.then(() => {
this.isInitialized = true;
this.onContainerStateChanged(initialInput);
});
this.subscription = this.getUpdated$().subscribe(() =>
this.onContainerStateChanged(this.input)
);
Expand Down Expand Up @@ -355,9 +452,6 @@ export class Embeddable
);
this.expression = expression;
this.errors = this.maybeAddConflictError(errors, metaInfo?.sharingSavedObjectProps);

await this.initializeOutput();
this.isInitialized = true;
}

onContainerStateChanged(containerState: LensEmbeddableInput) {
Expand All @@ -370,10 +464,10 @@ export class Embeddable
? containerState.filters.filter((filter) => !filter.meta.disabled)
: undefined;
if (
!isEqual(containerState.timeRange, this.externalSearchContext.timeRange) ||
!isEqual(containerState.query, this.externalSearchContext.query) ||
!isEqual(cleanedFilters, this.externalSearchContext.filters) ||
this.externalSearchContext.searchSessionId !== containerState.searchSessionId ||
!isEqual(containerState.timeRange, this.externalSearchContext?.timeRange) ||
!isEqual(containerState.query, this.externalSearchContext?.query) ||
!isEqual(cleanedFilters, this.externalSearchContext?.filters) ||
this.externalSearchContext?.searchSessionId !== containerState.searchSessionId ||
this.embeddableTitle !== this.getTitle()
) {
this.externalSearchContext = {
Expand All @@ -383,12 +477,15 @@ export class Embeddable
searchSessionId: containerState.searchSessionId,
};
this.embeddableTitle = this.getTitle();
this.updateViewUnderlyingDataArgs();
isDirty = true;
}
return isDirty;
}

private updateActiveData: ExpressionWrapperProps['onData$'] = () => {
private updateActiveData: ExpressionWrapperProps['onData$'] = (_, adapters) => {
this.activeDataInfo.activeData = adapters?.tables?.tables;
this.updateViewUnderlyingDataArgs();
if (this.input.onLoad) {
// once onData$ is get's called from expression renderer, loading becomes false
this.input.onLoad(false);
Expand Down Expand Up @@ -598,29 +695,79 @@ export class Embeddable
}
}

private async updateViewUnderlyingDataArgs() {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you move all this logic outside of the embeddable? I think this has to be evaluated only on context menu update, rather than every change in the embeddable.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I quite understand. Do you mean move it to a standalone function?

I think it initially needs to be evaluated when both activeData and externalSearchContext change because they don't necessarily resolve serially.

The function only works when both are present, but we don't know which one will resolve first, so it is called in both places and the second time it's called we know that both activeData and externalSearchContext will be available.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMHO it makes sense to keep it inside of the embeddable, but only call it if requested from the action (see other comment)

if (!this.activeDataInfo.activeData || !this.externalSearchContext) {
// This function is called both when activeData and externalSearchContext are loaded
// because we're not sure which one will load first. But, both must be loaded before
// we actually run this.
return;
}

const activeDatasourceId = getActiveDatasourceIdFromDoc(this.savedVis);
if (activeDatasourceId) {
this.activeDataInfo.activeDatasource = this.deps.datasourceMap[activeDatasourceId];
const docDatasourceState = this.savedVis?.state.datasourceStates[activeDatasourceId];

this.activeDataInfo.activeDatasourceState =
await this.activeDataInfo.activeDatasource.initialize(
docDatasourceState,
this.savedVis?.references
);
}

const viewUnderlyingDataArgs = getViewUnderlyingDataArgs({
activeDatasource: this.activeDataInfo.activeDatasource!,
activeDatasourceState: this.activeDataInfo.activeDatasourceState,
activeData: this.activeDataInfo.activeData,
indexPatterns: this.indexPatterns!,
capabilities: this.deps.capabilities,
query: this.externalSearchContext.query!,
filters: this.externalSearchContext.filters!,
timeRange: this.externalSearchContext.timeRange!,
});

const loaded = typeof viewUnderlyingDataArgs !== 'undefined';

if (loaded) {
this.viewUnderlyingDataArgs = viewUnderlyingDataArgs;
}

this.markVUDArgsLoaded(loaded);
}

/**
* Returns the necessary arguments to view the underlying data in discover.
*/
public async getViewUnderlyingDataArgs() {
const loaded = await this.waitVUDArgsLoaded;
if (loaded) {
return this.viewUnderlyingDataArgs;
}
}

public getCanViewUnderlyingData() {
// if loading the underlying data args fails
return this.waitVUDArgsLoaded;
}

async initializeOutput() {
if (!this.savedVis) {
return;
}
const responses = await Promise.allSettled(
uniqBy(
this.savedVis.references.filter(({ type }) => type === 'index-pattern'),
'id'
).map(({ id }) => this.deps.indexPatternService.get(id))

const { indexPatterns } = await getIndexPatternsObjects(
this.savedVis?.references.map(({ id }) => id) || [],
this.deps.indexPatternService
);
const indexPatterns = responses
.filter(
(response): response is PromiseFulfilledResult<IndexPattern> =>
response.status === 'fulfilled'
)
.map(({ value }) => value);

this.indexPatterns = indexPatterns;

// passing edit url and index patterns to the output of this embeddable for
// the container to pick them up and use them to configure filter bar and
// config dropdown correctly.
const input = this.getInput();

this.errors = this.maybeAddTimeRangeError(this.errors, input, indexPatterns);
this.errors = this.maybeAddTimeRangeError(this.errors, input, this.indexPatterns);

if (this.errors) {
this.logError('validation');
Expand All @@ -635,7 +782,7 @@ export class Embeddable
title,
editPath: getEditPath(savedObjectId),
editUrl: this.deps.basePath.prepend(`/app/lens${getEditPath(savedObjectId)}`),
indexPatterns,
indexPatterns: this.indexPatterns,
});

// deferred loading of this embeddable is complete
Expand Down
7 changes: 6 additions & 1 deletion x-pack/plugins/lens/public/embeddable/embeddable_factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { DOC_TYPE } from '../../common/constants';
import { ErrorMessage } from '../editor_frame_service/types';
import { extract, inject } from '../../common/embeddable_factory';
import type { SpacesPluginStart } from '../../../spaces/public';
import { VisualizationMap } from '../types';
import { DatasourceMap, VisualizationMap } from '../types';

export interface LensEmbeddableStartServices {
timefilter: TimefilterContract;
Expand All @@ -46,6 +46,7 @@ export interface LensEmbeddableStartServices {
) => Promise<{ ast: Ast | null; errors: ErrorMessage[] | undefined }>;
injectFilterReferences: FilterManager['inject'];
visualizationMap: VisualizationMap;
datasourceMap: DatasourceMap;
spaces?: SpacesPluginStart;
theme: ThemeServiceStart;
}
Expand Down Expand Up @@ -95,6 +96,7 @@ export class EmbeddableFactory implements EmbeddableFactoryDefinition {
documentToExpression,
injectFilterReferences,
visualizationMap,
datasourceMap,
uiActions,
coreHttp,
attributeService,
Expand All @@ -121,9 +123,12 @@ export class EmbeddableFactory implements EmbeddableFactoryDefinition {
documentToExpression,
injectFilterReferences,
visualizationMap,
datasourceMap,
capabilities: {
canSaveDashboards: Boolean(capabilities.dashboard?.showWriteControls),
canSaveVisualizations: Boolean(capabilities.visualize.save),
navLinks: capabilities.navLinks,
discover: capabilities.discover,
},
usageCollection,
theme,
Expand Down
Loading