actions.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. // Libraries
  2. import _ from 'lodash';
  3. // Services & Utils
  4. import store from 'app/core/store';
  5. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  6. import { Emitter } from 'app/core/core';
  7. import {
  8. LAST_USED_DATASOURCE_KEY,
  9. clearQueryKeys,
  10. ensureQueries,
  11. generateEmptyQuery,
  12. hasNonEmptyQuery,
  13. makeTimeSeriesList,
  14. updateHistory,
  15. buildQueryTransaction,
  16. serializeStateToUrlParam,
  17. parseUrlState,
  18. } from 'app/core/utils/explore';
  19. // Actions
  20. import { updateLocation } from 'app/core/actions';
  21. // Types
  22. import {
  23. RawTimeRange,
  24. TimeRange,
  25. DataSourceApi,
  26. DataQuery,
  27. DataSourceSelectItem,
  28. QueryHint,
  29. QueryFixAction,
  30. } from '@grafana/ui/src/types';
  31. import { ExploreId, ExploreUrlState, RangeScanner, ResultType, QueryOptions, ExploreUIState } from 'app/types/explore';
  32. import {
  33. updateDatasourceInstanceAction,
  34. changeQueryAction,
  35. changeSizeAction,
  36. ChangeSizePayload,
  37. changeTimeAction,
  38. scanStopAction,
  39. clearQueriesAction,
  40. initializeExploreAction,
  41. loadDatasourceMissingAction,
  42. loadDatasourceFailureAction,
  43. loadDatasourcePendingAction,
  44. queriesImportedAction,
  45. LoadDatasourceSuccessPayload,
  46. loadDatasourceSuccessAction,
  47. modifyQueriesAction,
  48. queryTransactionFailureAction,
  49. queryTransactionStartAction,
  50. queryTransactionSuccessAction,
  51. scanRangeAction,
  52. scanStartAction,
  53. setQueriesAction,
  54. splitCloseAction,
  55. splitOpenAction,
  56. addQueryRowAction,
  57. toggleGraphAction,
  58. toggleLogsAction,
  59. toggleTableAction,
  60. ToggleGraphPayload,
  61. ToggleLogsPayload,
  62. ToggleTablePayload,
  63. updateUIStateAction,
  64. runQueriesAction,
  65. } from './actionTypes';
  66. import { ActionOf, ActionCreator } from 'app/core/redux/actionCreatorFactory';
  67. import { LogsDedupStrategy } from 'app/core/logs_model';
  68. import { ThunkResult } from 'app/types';
  69. import { parseTime } from '../TimePicker';
  70. /**
  71. * Updates UI state and save it to the URL
  72. */
  73. const updateExploreUIState = (exploreId, uiStateFragment: Partial<ExploreUIState>) => {
  74. return dispatch => {
  75. dispatch(updateUIStateAction({ exploreId, ...uiStateFragment }));
  76. dispatch(stateSave());
  77. };
  78. };
  79. /**
  80. * Adds a query row after the row with the given index.
  81. */
  82. export function addQueryRow(exploreId: ExploreId, index: number): ThunkResult<void> {
  83. return (dispatch, getState) => {
  84. const query = generateEmptyQuery(getState().explore[exploreId].queries, index);
  85. dispatch(addQueryRowAction({ exploreId, index, query }));
  86. };
  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, getState) => {
  118. // Null query means reset
  119. if (query === null) {
  120. query = { ...generateEmptyQuery(getState().explore[exploreId].queries) };
  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(queries),
  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(clearQueriesAction({ 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. dispatch(runQueriesAction());
  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(itemId: ExploreId): ThunkResult<void> {
  584. return dispatch => {
  585. dispatch(splitCloseAction({ itemId }));
  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[ExploreId.left];
  598. const queryState = getState().location.query[ExploreId.left] as string;
  599. const urlState = parseUrlState(queryState);
  600. const itemState = {
  601. ...leftState,
  602. queryTransactions: [],
  603. queries: leftState.queries.slice(),
  604. exploreId: ExploreId.right,
  605. urlState,
  606. };
  607. dispatch(splitOpenAction({ itemState }));
  608. dispatch(stateSave());
  609. };
  610. }
  611. /**
  612. * Saves Explore state to URL using the `left` and `right` parameters.
  613. * If split view is not active, `right` will not be set.
  614. */
  615. export function stateSave() {
  616. return (dispatch, getState) => {
  617. const { left, right, split } = getState().explore;
  618. const urlStates: { [index: string]: string } = {};
  619. const leftUrlState: ExploreUrlState = {
  620. datasource: left.datasourceInstance.name,
  621. queries: left.queries.map(clearQueryKeys),
  622. range: left.range,
  623. ui: {
  624. showingGraph: left.showingGraph,
  625. showingLogs: left.showingLogs,
  626. showingTable: left.showingTable,
  627. dedupStrategy: left.dedupStrategy,
  628. },
  629. };
  630. urlStates.left = serializeStateToUrlParam(leftUrlState, true);
  631. if (split) {
  632. const rightUrlState: ExploreUrlState = {
  633. datasource: right.datasourceInstance.name,
  634. queries: right.queries.map(clearQueryKeys),
  635. range: right.range,
  636. ui: {
  637. showingGraph: right.showingGraph,
  638. showingLogs: right.showingLogs,
  639. showingTable: right.showingTable,
  640. dedupStrategy: right.dedupStrategy,
  641. },
  642. };
  643. urlStates.right = serializeStateToUrlParam(rightUrlState, true);
  644. }
  645. dispatch(updateLocation({ query: urlStates }));
  646. };
  647. }
  648. /**
  649. * Creates action to collapse graph/logs/table panel. When panel is collapsed,
  650. * queries won't be run
  651. */
  652. const togglePanelActionCreator = (
  653. actionCreator:
  654. | ActionCreator<ToggleGraphPayload>
  655. | ActionCreator<ToggleLogsPayload>
  656. | ActionCreator<ToggleTablePayload>
  657. ) => (exploreId: ExploreId, isPanelVisible: boolean) => {
  658. return dispatch => {
  659. let uiFragmentStateUpdate: Partial<ExploreUIState>;
  660. const shouldRunQueries = !isPanelVisible;
  661. switch (actionCreator.type) {
  662. case toggleGraphAction.type:
  663. uiFragmentStateUpdate = { showingGraph: !isPanelVisible };
  664. break;
  665. case toggleLogsAction.type:
  666. uiFragmentStateUpdate = { showingLogs: !isPanelVisible };
  667. break;
  668. case toggleTableAction.type:
  669. uiFragmentStateUpdate = { showingTable: !isPanelVisible };
  670. break;
  671. }
  672. dispatch(actionCreator({ exploreId }));
  673. dispatch(updateExploreUIState(exploreId, uiFragmentStateUpdate));
  674. if (shouldRunQueries) {
  675. dispatch(runQueries(exploreId));
  676. }
  677. };
  678. };
  679. /**
  680. * Expand/collapse the graph result viewer. When collapsed, graph queries won't be run.
  681. */
  682. export const toggleGraph = togglePanelActionCreator(toggleGraphAction);
  683. /**
  684. * Expand/collapse the logs result viewer. When collapsed, log queries won't be run.
  685. */
  686. export const toggleLogs = togglePanelActionCreator(toggleLogsAction);
  687. /**
  688. * Expand/collapse the table result viewer. When collapsed, table queries won't be run.
  689. */
  690. export const toggleTable = togglePanelActionCreator(toggleTableAction);
  691. /**
  692. * Change logs deduplication strategy and update URL.
  693. */
  694. export const changeDedupStrategy = (exploreId, dedupStrategy: LogsDedupStrategy) => {
  695. return dispatch => {
  696. dispatch(updateExploreUIState(exploreId, { dedupStrategy }));
  697. };
  698. };
  699. export function refreshExplore(exploreId: ExploreId): ThunkResult<void> {
  700. return (dispatch, getState) => {
  701. const itemState = getState().explore[exploreId];
  702. if (!itemState.initialized) {
  703. return;
  704. }
  705. const { urlState, update, containerWidth, eventBridge } = itemState;
  706. const { datasource, queries, range, ui } = urlState;
  707. const refreshQueries = queries.map(q => ({ ...q, ...generateEmptyQuery(itemState.queries) }));
  708. const refreshRange = { from: parseTime(range.from), to: parseTime(range.to) };
  709. // need to refresh datasource
  710. if (update.datasource) {
  711. const initialQueries = ensureQueries(queries);
  712. const initialRange = { from: parseTime(range.from), to: parseTime(range.to) };
  713. dispatch(initializeExplore(exploreId, datasource, initialQueries, initialRange, containerWidth, eventBridge, ui));
  714. return;
  715. }
  716. if (update.range) {
  717. dispatch(changeTimeAction({ exploreId, range: refreshRange as TimeRange }));
  718. }
  719. // need to refresh ui state
  720. if (update.ui) {
  721. dispatch(updateUIStateAction({ ...ui, exploreId }));
  722. }
  723. // need to refresh queries
  724. if (update.queries) {
  725. dispatch(setQueriesAction({ exploreId, queries: refreshQueries }));
  726. }
  727. // always run queries when refresh is needed
  728. if (update.queries || update.ui || update.range) {
  729. dispatch(runQueries(exploreId));
  730. }
  731. };
  732. }