actions.ts 23 KB

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