actions.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. // Libraries
  2. import _ from 'lodash';
  3. import { ThunkAction } from 'redux-thunk';
  4. // Services & Utils
  5. import store from 'app/core/store';
  6. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  7. import { Emitter } from 'app/core/core';
  8. import {
  9. LAST_USED_DATASOURCE_KEY,
  10. clearQueryKeys,
  11. ensureQueries,
  12. generateEmptyQuery,
  13. hasNonEmptyQuery,
  14. makeTimeSeriesList,
  15. updateHistory,
  16. buildQueryTransaction,
  17. serializeStateToUrlParam,
  18. } from 'app/core/utils/explore';
  19. // Actions
  20. import { updateLocation } from 'app/core/actions';
  21. // Types
  22. import { StoreState } from 'app/types';
  23. import {
  24. RawTimeRange,
  25. TimeRange,
  26. DataSourceApi,
  27. DataQuery,
  28. DataSourceSelectItem,
  29. QueryHint,
  30. QueryFixAction,
  31. } from '@grafana/ui/src/types';
  32. import { ExploreId, ExploreUrlState, RangeScanner, ResultType, QueryOptions, ExploreUIState } from 'app/types/explore';
  33. import {
  34. Action,
  35. updateDatasourceInstanceAction,
  36. changeQueryAction,
  37. changeSizeAction,
  38. ChangeSizePayload,
  39. changeTimeAction,
  40. scanStopAction,
  41. clearQueriesAction,
  42. initializeExploreAction,
  43. loadDatasourceMissingAction,
  44. loadDatasourceFailureAction,
  45. loadDatasourcePendingAction,
  46. queriesImportedAction,
  47. LoadDatasourceSuccessPayload,
  48. loadDatasourceSuccessAction,
  49. modifyQueriesAction,
  50. queryTransactionFailureAction,
  51. queryTransactionStartAction,
  52. queryTransactionSuccessAction,
  53. scanRangeAction,
  54. runQueriesEmptyAction,
  55. scanStartAction,
  56. setQueriesAction,
  57. splitCloseAction,
  58. splitOpenAction,
  59. addQueryRowAction,
  60. AddQueryRowPayload,
  61. toggleGraphAction,
  62. toggleLogsAction,
  63. toggleTableAction,
  64. ToggleGraphPayload,
  65. ToggleLogsPayload,
  66. ToggleTablePayload,
  67. updateUIStateAction,
  68. } from './actionTypes';
  69. import { ActionOf, ActionCreator } from 'app/core/redux/actionCreatorFactory';
  70. import { LogsDedupStrategy } from 'app/core/logs_model';
  71. type ThunkResult<R> = ThunkAction<R, StoreState, undefined, Action>;
  72. /**
  73. * Updates UI state and save it to the URL
  74. */
  75. const updateExploreUIState = (exploreId, uiStateFragment: Partial<ExploreUIState>) => {
  76. return dispatch => {
  77. dispatch(updateUIStateAction({ exploreId, ...uiStateFragment }));
  78. dispatch(stateSave());
  79. };
  80. };
  81. /**
  82. * Adds a query row after the row with the given index.
  83. */
  84. export function addQueryRow(exploreId: ExploreId, index: number): ActionOf<AddQueryRowPayload> {
  85. const query = generateEmptyQuery(index + 1);
  86. return addQueryRowAction({ exploreId, index, query });
  87. }
  88. /**
  89. * Loads a new datasource identified by the given name.
  90. */
  91. export function changeDatasource(exploreId: ExploreId, datasource: string): ThunkResult<void> {
  92. return async (dispatch, getState) => {
  93. const newDataSourceInstance = await getDatasourceSrv().get(datasource);
  94. const currentDataSourceInstance = getState().explore[exploreId].datasourceInstance;
  95. const queries = getState().explore[exploreId].queries;
  96. await dispatch(importQueries(exploreId, queries, currentDataSourceInstance, newDataSourceInstance));
  97. dispatch(updateDatasourceInstanceAction({ exploreId, datasourceInstance: newDataSourceInstance }));
  98. try {
  99. await dispatch(loadDatasource(exploreId, newDataSourceInstance));
  100. } catch (error) {
  101. console.error(error);
  102. return;
  103. }
  104. dispatch(runQueries(exploreId));
  105. };
  106. }
  107. /**
  108. * Query change handler for the query row with the given index.
  109. * If `override` is reset the query modifications and run the queries. Use this to set queries via a link.
  110. */
  111. export function changeQuery(
  112. exploreId: ExploreId,
  113. query: DataQuery,
  114. index: number,
  115. override: boolean
  116. ): ThunkResult<void> {
  117. return dispatch => {
  118. // Null query means reset
  119. if (query === null) {
  120. query = { ...generateEmptyQuery(index) };
  121. }
  122. dispatch(changeQueryAction({ exploreId, query, index, override }));
  123. if (override) {
  124. dispatch(runQueries(exploreId));
  125. }
  126. };
  127. }
  128. /**
  129. * Keep track of the Explore container size, in particular the width.
  130. * The width will be used to calculate graph intervals (number of datapoints).
  131. */
  132. export function changeSize(
  133. exploreId: ExploreId,
  134. { height, width }: { height: number; width: number }
  135. ): ActionOf<ChangeSizePayload> {
  136. return changeSizeAction({ exploreId, height, width });
  137. }
  138. /**
  139. * Change the time range of Explore. Usually called from the Timepicker or a graph interaction.
  140. */
  141. export function changeTime(exploreId: ExploreId, range: TimeRange): ThunkResult<void> {
  142. return dispatch => {
  143. dispatch(changeTimeAction({ exploreId, range }));
  144. dispatch(runQueries(exploreId));
  145. };
  146. }
  147. /**
  148. * Clear all queries and results.
  149. */
  150. export function clearQueries(exploreId: ExploreId): ThunkResult<void> {
  151. return dispatch => {
  152. dispatch(scanStopAction({ exploreId }));
  153. dispatch(clearQueriesAction({ exploreId }));
  154. dispatch(stateSave());
  155. };
  156. }
  157. /**
  158. * Initialize Explore state with state from the URL and the React component.
  159. * Call this only on components for with the Explore state has not been initialized.
  160. */
  161. export function initializeExplore(
  162. exploreId: ExploreId,
  163. datasourceName: string,
  164. queries: DataQuery[],
  165. range: RawTimeRange,
  166. containerWidth: number,
  167. eventBridge: Emitter,
  168. ui: ExploreUIState
  169. ): ThunkResult<void> {
  170. return async dispatch => {
  171. const exploreDatasources: DataSourceSelectItem[] = getDatasourceSrv()
  172. .getExternal()
  173. .map(ds => ({
  174. value: ds.name,
  175. name: ds.name,
  176. meta: ds.meta,
  177. }));
  178. dispatch(
  179. initializeExploreAction({
  180. exploreId,
  181. containerWidth,
  182. eventBridge,
  183. exploreDatasources,
  184. queries,
  185. range,
  186. ui,
  187. })
  188. );
  189. if (exploreDatasources.length >= 1) {
  190. let instance;
  191. if (datasourceName) {
  192. try {
  193. instance = await getDatasourceSrv().get(datasourceName);
  194. } catch (error) {
  195. console.error(error);
  196. }
  197. }
  198. // Checking on instance here because requested datasource could be deleted already
  199. if (!instance) {
  200. instance = await getDatasourceSrv().get();
  201. }
  202. dispatch(updateDatasourceInstanceAction({ exploreId, datasourceInstance: instance }));
  203. try {
  204. await dispatch(loadDatasource(exploreId, instance));
  205. } catch (error) {
  206. console.error(error);
  207. return;
  208. }
  209. dispatch(runQueries(exploreId, true));
  210. } else {
  211. dispatch(loadDatasourceMissingAction({ exploreId }));
  212. }
  213. };
  214. }
  215. /**
  216. * Datasource loading was successfully completed. The instance is stored in the state as well in case we need to
  217. * run datasource-specific code. Existing queries are imported to the new datasource if an importer exists,
  218. * e.g., Prometheus -> Loki queries.
  219. */
  220. export const loadDatasourceSuccess = (exploreId: ExploreId, instance: any): ActionOf<LoadDatasourceSuccessPayload> => {
  221. // Capabilities
  222. const supportsGraph = instance.meta.metrics;
  223. const supportsLogs = instance.meta.logs;
  224. const supportsTable = instance.meta.tables;
  225. // Custom components
  226. const StartPage = instance.pluginExports.ExploreStartPage;
  227. const historyKey = `grafana.explore.history.${instance.meta.id}`;
  228. const history = store.getObject(historyKey, []);
  229. // Save last-used datasource
  230. store.set(LAST_USED_DATASOURCE_KEY, instance.name);
  231. return loadDatasourceSuccessAction({
  232. exploreId,
  233. StartPage,
  234. datasourceInstance: instance,
  235. history,
  236. showingStartPage: Boolean(StartPage),
  237. supportsGraph,
  238. supportsLogs,
  239. supportsTable,
  240. });
  241. };
  242. export function importQueries(
  243. exploreId: ExploreId,
  244. queries: DataQuery[],
  245. sourceDataSource: DataSourceApi,
  246. targetDataSource: DataSourceApi
  247. ) {
  248. return async dispatch => {
  249. let importedQueries = queries;
  250. // Check if queries can be imported from previously selected datasource
  251. if (sourceDataSource.meta.id === targetDataSource.meta.id) {
  252. // Keep same queries if same type of datasource
  253. importedQueries = [...queries];
  254. } else if (targetDataSource.importQueries) {
  255. // Datasource-specific importers
  256. importedQueries = await targetDataSource.importQueries(queries, sourceDataSource.meta);
  257. } else {
  258. // Default is blank queries
  259. importedQueries = ensureQueries();
  260. }
  261. const nextQueries = importedQueries.map((q, i) => ({
  262. ...q,
  263. ...generateEmptyQuery(i),
  264. }));
  265. dispatch(queriesImportedAction({ exploreId, queries: nextQueries }));
  266. };
  267. }
  268. /**
  269. * Main action to asynchronously load a datasource. Dispatches lots of smaller actions for feedback.
  270. */
  271. export function loadDatasource(exploreId: ExploreId, instance: DataSourceApi): ThunkResult<void> {
  272. return async (dispatch, getState) => {
  273. const datasourceName = instance.name;
  274. // Keep ID to track selection
  275. dispatch(loadDatasourcePendingAction({ exploreId, requestedDatasourceName: datasourceName }));
  276. let datasourceError = null;
  277. try {
  278. const testResult = await instance.testDatasource();
  279. datasourceError = testResult.status === 'success' ? null : testResult.message;
  280. } catch (error) {
  281. datasourceError = (error && error.statusText) || 'Network error';
  282. }
  283. if (datasourceError) {
  284. dispatch(loadDatasourceFailureAction({ exploreId, error: datasourceError }));
  285. return Promise.reject(`${datasourceName} loading failed`);
  286. }
  287. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  288. // User already changed datasource again, discard results
  289. return;
  290. }
  291. if (instance.init) {
  292. instance.init();
  293. }
  294. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  295. // User already changed datasource again, discard results
  296. return;
  297. }
  298. dispatch(loadDatasourceSuccess(exploreId, instance));
  299. return Promise.resolve();
  300. };
  301. }
  302. /**
  303. * Action to modify a query given a datasource-specific modifier action.
  304. * @param exploreId Explore area
  305. * @param modification Action object with a type, e.g., ADD_FILTER
  306. * @param index Optional query row index. If omitted, the modification is applied to all query rows.
  307. * @param modifier Function that executes the modification, typically `datasourceInstance.modifyQueries`.
  308. */
  309. export function modifyQueries(
  310. exploreId: ExploreId,
  311. modification: QueryFixAction,
  312. index: number,
  313. modifier: any
  314. ): ThunkResult<void> {
  315. return dispatch => {
  316. dispatch(modifyQueriesAction({ exploreId, modification, index, modifier }));
  317. if (!modification.preventSubmit) {
  318. dispatch(runQueries(exploreId));
  319. }
  320. };
  321. }
  322. /**
  323. * Mark a query transaction as failed with an error extracted from the query response.
  324. * The transaction will be marked as `done`.
  325. */
  326. export function queryTransactionFailure(
  327. exploreId: ExploreId,
  328. transactionId: string,
  329. response: any,
  330. datasourceId: string
  331. ): ThunkResult<void> {
  332. return (dispatch, getState) => {
  333. const { datasourceInstance, queryTransactions } = getState().explore[exploreId];
  334. if (datasourceInstance.meta.id !== datasourceId || response.cancelled) {
  335. // Navigated away, queries did not matter
  336. return;
  337. }
  338. // Transaction might have been discarded
  339. if (!queryTransactions.find(qt => qt.id === transactionId)) {
  340. return;
  341. }
  342. console.error(response);
  343. let error: string;
  344. let errorDetails: string;
  345. if (response.data) {
  346. if (typeof response.data === 'string') {
  347. error = response.data;
  348. } else if (response.data.error) {
  349. error = response.data.error;
  350. if (response.data.response) {
  351. errorDetails = response.data.response;
  352. }
  353. } else {
  354. throw new Error('Could not handle error response');
  355. }
  356. } else if (response.message) {
  357. error = response.message;
  358. } else if (typeof response === 'string') {
  359. error = response;
  360. } else {
  361. error = 'Unknown error during query transaction. Please check JS console logs.';
  362. }
  363. // Mark transactions as complete
  364. const nextQueryTransactions = queryTransactions.map(qt => {
  365. if (qt.id === transactionId) {
  366. return {
  367. ...qt,
  368. error,
  369. errorDetails,
  370. done: true,
  371. };
  372. }
  373. return qt;
  374. });
  375. dispatch(queryTransactionFailureAction({ exploreId, queryTransactions: nextQueryTransactions }));
  376. };
  377. }
  378. /**
  379. * Complete a query transaction, mark the transaction as `done` and store query state in URL.
  380. * If the transaction was started by a scanner, it keeps on scanning for more results.
  381. * Side-effect: the query is stored in localStorage.
  382. * @param exploreId Explore area
  383. * @param transactionId ID
  384. * @param result Response from `datasourceInstance.query()`
  385. * @param latency Duration between request and response
  386. * @param queries Queries from all query rows
  387. * @param datasourceId Origin datasource instance, used to discard results if current datasource is different
  388. */
  389. export function queryTransactionSuccess(
  390. exploreId: ExploreId,
  391. transactionId: string,
  392. result: any,
  393. latency: number,
  394. queries: DataQuery[],
  395. datasourceId: string
  396. ): ThunkResult<void> {
  397. return (dispatch, getState) => {
  398. const { datasourceInstance, history, queryTransactions, scanner, scanning } = getState().explore[exploreId];
  399. // If datasource already changed, results do not matter
  400. if (datasourceInstance.meta.id !== datasourceId) {
  401. return;
  402. }
  403. // Transaction might have been discarded
  404. const transaction = queryTransactions.find(qt => qt.id === transactionId);
  405. if (!transaction) {
  406. return;
  407. }
  408. // Get query hints
  409. let hints: QueryHint[];
  410. if (datasourceInstance.getQueryHints) {
  411. hints = datasourceInstance.getQueryHints(transaction.query, result);
  412. }
  413. // Mark transactions as complete and attach result
  414. const nextQueryTransactions = queryTransactions.map(qt => {
  415. if (qt.id === transactionId) {
  416. return {
  417. ...qt,
  418. hints,
  419. latency,
  420. result,
  421. done: true,
  422. };
  423. }
  424. return qt;
  425. });
  426. // Side-effect: Saving history in localstorage
  427. const nextHistory = updateHistory(history, datasourceId, queries);
  428. dispatch(
  429. queryTransactionSuccessAction({
  430. exploreId,
  431. history: nextHistory,
  432. queryTransactions: nextQueryTransactions,
  433. })
  434. );
  435. // Keep scanning for results if this was the last scanning transaction
  436. if (scanning) {
  437. if (_.size(result) === 0) {
  438. const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done);
  439. if (!other) {
  440. const range = scanner();
  441. dispatch(scanRangeAction({ exploreId, range }));
  442. }
  443. } else {
  444. // We can stop scanning if we have a result
  445. dispatch(scanStopAction({ exploreId }));
  446. }
  447. }
  448. };
  449. }
  450. /**
  451. * Main action to run queries and dispatches sub-actions based on which result viewers are active
  452. */
  453. export function runQueries(exploreId: ExploreId, ignoreUIState = false) {
  454. return (dispatch, getState) => {
  455. const {
  456. datasourceInstance,
  457. queries,
  458. showingLogs,
  459. showingGraph,
  460. showingTable,
  461. supportsGraph,
  462. supportsLogs,
  463. supportsTable,
  464. } = getState().explore[exploreId];
  465. if (!hasNonEmptyQuery(queries)) {
  466. dispatch(runQueriesEmptyAction({ exploreId }));
  467. dispatch(stateSave()); // Remember to saves to state and update location
  468. return;
  469. }
  470. // Some datasource's query builders allow per-query interval limits,
  471. // but we're using the datasource interval limit for now
  472. const interval = datasourceInstance.interval;
  473. // Keep table queries first since they need to return quickly
  474. if ((ignoreUIState || showingTable) && supportsTable) {
  475. dispatch(
  476. runQueriesForType(
  477. exploreId,
  478. 'Table',
  479. {
  480. interval,
  481. format: 'table',
  482. instant: true,
  483. valueWithRefId: true,
  484. },
  485. data => data[0]
  486. )
  487. );
  488. }
  489. if ((ignoreUIState || showingGraph) && supportsGraph) {
  490. dispatch(
  491. runQueriesForType(
  492. exploreId,
  493. 'Graph',
  494. {
  495. interval,
  496. format: 'time_series',
  497. instant: false,
  498. },
  499. makeTimeSeriesList
  500. )
  501. );
  502. }
  503. if ((ignoreUIState || showingLogs) && supportsLogs) {
  504. dispatch(runQueriesForType(exploreId, 'Logs', { interval, format: 'logs' }));
  505. }
  506. dispatch(stateSave());
  507. };
  508. }
  509. /**
  510. * Helper action to build a query transaction object and handing the query to the datasource.
  511. * @param exploreId Explore area
  512. * @param resultType Result viewer that will be associated with this query result
  513. * @param queryOptions Query options as required by the datasource's `query()` function.
  514. * @param resultGetter Optional result extractor, e.g., if the result is a list and you only need the first element.
  515. */
  516. function runQueriesForType(
  517. exploreId: ExploreId,
  518. resultType: ResultType,
  519. queryOptions: QueryOptions,
  520. resultGetter?: any
  521. ) {
  522. return async (dispatch, getState) => {
  523. const { datasourceInstance, eventBridge, queries, queryIntervals, range, scanning } = getState().explore[exploreId];
  524. const datasourceId = datasourceInstance.meta.id;
  525. // Run all queries concurrently
  526. queries.forEach(async (query, rowIndex) => {
  527. const transaction = buildQueryTransaction(
  528. query,
  529. rowIndex,
  530. resultType,
  531. queryOptions,
  532. range,
  533. queryIntervals,
  534. scanning
  535. );
  536. dispatch(queryTransactionStartAction({ exploreId, resultType, rowIndex, transaction }));
  537. try {
  538. const now = Date.now();
  539. const res = await datasourceInstance.query(transaction.options);
  540. eventBridge.emit('data-received', res.data || []);
  541. const latency = Date.now() - now;
  542. const results = resultGetter ? resultGetter(res.data) : res.data;
  543. dispatch(queryTransactionSuccess(exploreId, transaction.id, results, latency, queries, datasourceId));
  544. } catch (response) {
  545. eventBridge.emit('data-error', response);
  546. dispatch(queryTransactionFailure(exploreId, transaction.id, response, datasourceId));
  547. }
  548. });
  549. };
  550. }
  551. /**
  552. * Start a scan for more results using the given scanner.
  553. * @param exploreId Explore area
  554. * @param scanner Function that a) returns a new time range and b) triggers a query run for the new range
  555. */
  556. export function scanStart(exploreId: ExploreId, scanner: RangeScanner): ThunkResult<void> {
  557. return dispatch => {
  558. // Register the scanner
  559. dispatch(scanStartAction({ exploreId, scanner }));
  560. // Scanning must trigger query run, and return the new range
  561. const range = scanner();
  562. // Set the new range to be displayed
  563. dispatch(scanRangeAction({ exploreId, range }));
  564. };
  565. }
  566. /**
  567. * Reset queries to the given queries. Any modifications will be discarded.
  568. * Use this action for clicks on query examples. Triggers a query run.
  569. */
  570. export function setQueries(exploreId: ExploreId, rawQueries: DataQuery[]): ThunkResult<void> {
  571. return dispatch => {
  572. // Inject react keys into query objects
  573. const queries = rawQueries.map(q => ({ ...q, ...generateEmptyQuery() }));
  574. dispatch(setQueriesAction({ exploreId, queries }));
  575. dispatch(runQueries(exploreId));
  576. };
  577. }
  578. /**
  579. * Close the split view and save URL state.
  580. */
  581. export function splitClose(): ThunkResult<void> {
  582. return dispatch => {
  583. dispatch(splitCloseAction());
  584. dispatch(stateSave());
  585. };
  586. }
  587. /**
  588. * Open the split view and copy the left state to be the right state.
  589. * The right state is automatically initialized.
  590. * The copy keeps all query modifications but wipes the query results.
  591. */
  592. export function splitOpen(): ThunkResult<void> {
  593. return (dispatch, getState) => {
  594. // Clone left state to become the right state
  595. const leftState = getState().explore.left;
  596. const itemState = {
  597. ...leftState,
  598. queryTransactions: [],
  599. queries: leftState.queries.slice(),
  600. };
  601. dispatch(splitOpenAction({ itemState }));
  602. dispatch(stateSave());
  603. };
  604. }
  605. /**
  606. * Saves Explore state to URL using the `left` and `right` parameters.
  607. * If split view is not active, `right` will not be set.
  608. */
  609. export function stateSave() {
  610. return (dispatch, getState) => {
  611. const { left, right, split } = getState().explore;
  612. const urlStates: { [index: string]: string } = {};
  613. const leftUrlState: ExploreUrlState = {
  614. datasource: left.datasourceInstance.name,
  615. queries: left.queries.map(clearQueryKeys),
  616. range: left.range,
  617. ui: {
  618. showingGraph: left.showingGraph,
  619. showingLogs: left.showingLogs,
  620. showingTable: left.showingTable,
  621. dedupStrategy: left.dedupStrategy,
  622. },
  623. };
  624. urlStates.left = serializeStateToUrlParam(leftUrlState, true);
  625. if (split) {
  626. const rightUrlState: ExploreUrlState = {
  627. datasource: right.datasourceInstance.name,
  628. queries: right.queries.map(clearQueryKeys),
  629. range: right.range,
  630. ui: {
  631. showingGraph: right.showingGraph,
  632. showingLogs: right.showingLogs,
  633. showingTable: right.showingTable,
  634. dedupStrategy: right.dedupStrategy,
  635. },
  636. };
  637. urlStates.right = serializeStateToUrlParam(rightUrlState, true);
  638. }
  639. dispatch(updateLocation({ query: urlStates }));
  640. };
  641. }
  642. /**
  643. * Creates action to collapse graph/logs/table panel. When panel is collapsed,
  644. * queries won't be run
  645. */
  646. const togglePanelActionCreator = (
  647. actionCreator:
  648. | ActionCreator<ToggleGraphPayload>
  649. | ActionCreator<ToggleLogsPayload>
  650. | ActionCreator<ToggleTablePayload>
  651. ) => (exploreId: ExploreId, isPanelVisible: boolean) => {
  652. return dispatch => {
  653. let uiFragmentStateUpdate: Partial<ExploreUIState>;
  654. const shouldRunQueries = !isPanelVisible;
  655. switch (actionCreator.type) {
  656. case toggleGraphAction.type:
  657. uiFragmentStateUpdate = { showingGraph: !isPanelVisible };
  658. break;
  659. case toggleLogsAction.type:
  660. uiFragmentStateUpdate = { showingLogs: !isPanelVisible };
  661. break;
  662. case toggleTableAction.type:
  663. uiFragmentStateUpdate = { showingTable: !isPanelVisible };
  664. break;
  665. }
  666. dispatch(actionCreator({ exploreId }));
  667. dispatch(updateExploreUIState(exploreId, uiFragmentStateUpdate));
  668. if (shouldRunQueries) {
  669. dispatch(runQueries(exploreId));
  670. }
  671. };
  672. };
  673. /**
  674. * Expand/collapse the graph result viewer. When collapsed, graph queries won't be run.
  675. */
  676. export const toggleGraph = togglePanelActionCreator(toggleGraphAction);
  677. /**
  678. * Expand/collapse the logs result viewer. When collapsed, log queries won't be run.
  679. */
  680. export const toggleLogs = togglePanelActionCreator(toggleLogsAction);
  681. /**
  682. * Expand/collapse the table result viewer. When collapsed, table queries won't be run.
  683. */
  684. export const toggleTable = togglePanelActionCreator(toggleTableAction);
  685. /**
  686. * Change logs deduplication strategy and update URL.
  687. */
  688. export const changeDedupStrategy = (exploreId, dedupStrategy: LogsDedupStrategy) => {
  689. return dispatch => {
  690. dispatch(updateExploreUIState(exploreId, { dedupStrategy }));
  691. };
  692. };