actions.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. getTimeRange,
  19. getTimeRangeFromUrl,
  20. generateNewKeyAndAddRefIdIfMissing,
  21. instanceOfDataQueryError,
  22. getRefIds,
  23. } from 'app/core/utils/explore';
  24. // Actions
  25. import { updateLocation } from 'app/core/actions';
  26. // Types
  27. import { ThunkResult } from 'app/types';
  28. import {
  29. RawTimeRange,
  30. DataSourceApi,
  31. DataQuery,
  32. DataSourceSelectItem,
  33. QueryFixAction,
  34. TimeRange,
  35. } from '@grafana/ui/src/types';
  36. import {
  37. ExploreId,
  38. ExploreUrlState,
  39. RangeScanner,
  40. ResultType,
  41. QueryOptions,
  42. ExploreUIState,
  43. QueryTransaction,
  44. ExploreMode,
  45. } from 'app/types/explore';
  46. import {
  47. updateDatasourceInstanceAction,
  48. changeQueryAction,
  49. changeRefreshIntervalAction,
  50. ChangeRefreshIntervalPayload,
  51. changeSizeAction,
  52. ChangeSizePayload,
  53. changeTimeAction,
  54. scanStopAction,
  55. clearQueriesAction,
  56. initializeExploreAction,
  57. loadDatasourceMissingAction,
  58. loadDatasourcePendingAction,
  59. queriesImportedAction,
  60. LoadDatasourceReadyPayload,
  61. loadDatasourceReadyAction,
  62. modifyQueriesAction,
  63. queryFailureAction,
  64. querySuccessAction,
  65. scanRangeAction,
  66. scanStartAction,
  67. setQueriesAction,
  68. splitCloseAction,
  69. splitOpenAction,
  70. addQueryRowAction,
  71. toggleGraphAction,
  72. toggleTableAction,
  73. ToggleGraphPayload,
  74. ToggleTablePayload,
  75. updateUIStateAction,
  76. runQueriesAction,
  77. testDataSourcePendingAction,
  78. testDataSourceSuccessAction,
  79. testDataSourceFailureAction,
  80. loadExploreDatasources,
  81. queryStartAction,
  82. historyUpdatedAction,
  83. resetQueryErrorAction,
  84. changeModeAction,
  85. } from './actionTypes';
  86. import { ActionOf, ActionCreator } from 'app/core/redux/actionCreatorFactory';
  87. import { LogsDedupStrategy } from 'app/core/logs_model';
  88. import { getTimeZone } from 'app/features/profile/state/selectors';
  89. import { isDateTime } from '@grafana/ui/src/utils/moment_wrapper';
  90. import { toDataQueryError } from 'app/features/dashboard/state/PanelQueryState';
  91. import { startSubscriptionsAction, subscriptionDataReceivedAction } from 'app/features/explore/state/epics';
  92. /**
  93. * Updates UI state and save it to the URL
  94. */
  95. const updateExploreUIState = (exploreId: ExploreId, uiStateFragment: Partial<ExploreUIState>): ThunkResult<void> => {
  96. return dispatch => {
  97. dispatch(updateUIStateAction({ exploreId, ...uiStateFragment }));
  98. dispatch(stateSave());
  99. };
  100. };
  101. /**
  102. * Adds a query row after the row with the given index.
  103. */
  104. export function addQueryRow(exploreId: ExploreId, index: number): ThunkResult<void> {
  105. return (dispatch, getState) => {
  106. const queries = getState().explore[exploreId].queries;
  107. const query = generateEmptyQuery(queries, index);
  108. dispatch(addQueryRowAction({ exploreId, index, query }));
  109. };
  110. }
  111. /**
  112. * Loads a new datasource identified by the given name.
  113. */
  114. export function changeDatasource(exploreId: ExploreId, datasource: string, replaceUrl = false): ThunkResult<void> {
  115. return async (dispatch, getState) => {
  116. let newDataSourceInstance: DataSourceApi = null;
  117. if (!datasource) {
  118. newDataSourceInstance = await getDatasourceSrv().get();
  119. } else {
  120. newDataSourceInstance = await getDatasourceSrv().get(datasource);
  121. }
  122. const currentDataSourceInstance = getState().explore[exploreId].datasourceInstance;
  123. const queries = getState().explore[exploreId].queries;
  124. await dispatch(importQueries(exploreId, queries, currentDataSourceInstance, newDataSourceInstance));
  125. dispatch(updateDatasourceInstanceAction({ exploreId, datasourceInstance: newDataSourceInstance }));
  126. await dispatch(loadDatasource(exploreId, newDataSourceInstance));
  127. dispatch(runQueries(exploreId, false, replaceUrl));
  128. };
  129. }
  130. /**
  131. * Change the display mode in Explore.
  132. */
  133. export function changeMode(exploreId: ExploreId, mode: ExploreMode): ThunkResult<void> {
  134. return dispatch => {
  135. dispatch(changeModeAction({ exploreId, mode }));
  136. dispatch(runQueries(exploreId));
  137. };
  138. }
  139. /**
  140. * Query change handler for the query row with the given index.
  141. * If `override` is reset the query modifications and run the queries. Use this to set queries via a link.
  142. */
  143. export function changeQuery(
  144. exploreId: ExploreId,
  145. query: DataQuery,
  146. index: number,
  147. override: boolean
  148. ): ThunkResult<void> {
  149. return (dispatch, getState) => {
  150. // Null query means reset
  151. if (query === null) {
  152. const queries = getState().explore[exploreId].queries;
  153. const { refId, key } = queries[index];
  154. query = generateNewKeyAndAddRefIdIfMissing({ refId, key }, queries, index);
  155. }
  156. dispatch(changeQueryAction({ exploreId, query, index, override }));
  157. if (override) {
  158. dispatch(runQueries(exploreId));
  159. }
  160. };
  161. }
  162. /**
  163. * Keep track of the Explore container size, in particular the width.
  164. * The width will be used to calculate graph intervals (number of datapoints).
  165. */
  166. export function changeSize(
  167. exploreId: ExploreId,
  168. { height, width }: { height: number; width: number }
  169. ): ActionOf<ChangeSizePayload> {
  170. return changeSizeAction({ exploreId, height, width });
  171. }
  172. /**
  173. * Change the time range of Explore. Usually called from the Time picker or a graph interaction.
  174. */
  175. export function changeTime(exploreId: ExploreId, rawRange: RawTimeRange): ThunkResult<void> {
  176. return (dispatch, getState) => {
  177. const timeZone = getTimeZone(getState().user);
  178. const range = getTimeRange(timeZone, rawRange);
  179. dispatch(changeTimeAction({ exploreId, range }));
  180. dispatch(runQueries(exploreId));
  181. };
  182. }
  183. /**
  184. * Change the refresh interval of Explore. Called from the Refresh picker.
  185. */
  186. export function changeRefreshInterval(
  187. exploreId: ExploreId,
  188. refreshInterval: string
  189. ): ActionOf<ChangeRefreshIntervalPayload> {
  190. return changeRefreshIntervalAction({ exploreId, refreshInterval });
  191. }
  192. /**
  193. * Clear all queries and results.
  194. */
  195. export function clearQueries(exploreId: ExploreId): ThunkResult<void> {
  196. return dispatch => {
  197. dispatch(scanStopAction({ exploreId }));
  198. dispatch(clearQueriesAction({ exploreId }));
  199. dispatch(stateSave());
  200. };
  201. }
  202. /**
  203. * Loads all explore data sources and sets the chosen datasource.
  204. * If there are no datasources a missing datasource action is dispatched.
  205. */
  206. export function loadExploreDatasourcesAndSetDatasource(
  207. exploreId: ExploreId,
  208. datasourceName: string
  209. ): ThunkResult<void> {
  210. return dispatch => {
  211. const exploreDatasources: DataSourceSelectItem[] = getDatasourceSrv()
  212. .getExternal()
  213. .map(
  214. (ds: any) =>
  215. ({
  216. value: ds.name,
  217. name: ds.name,
  218. meta: ds.meta,
  219. } as DataSourceSelectItem)
  220. );
  221. dispatch(loadExploreDatasources({ exploreId, exploreDatasources }));
  222. if (exploreDatasources.length >= 1) {
  223. dispatch(changeDatasource(exploreId, datasourceName, true));
  224. } else {
  225. dispatch(loadDatasourceMissingAction({ exploreId }));
  226. }
  227. };
  228. }
  229. /**
  230. * Initialize Explore state with state from the URL and the React component.
  231. * Call this only on components for with the Explore state has not been initialized.
  232. */
  233. export function initializeExplore(
  234. exploreId: ExploreId,
  235. datasourceName: string,
  236. queries: DataQuery[],
  237. rawRange: RawTimeRange,
  238. containerWidth: number,
  239. eventBridge: Emitter,
  240. ui: ExploreUIState
  241. ): ThunkResult<void> {
  242. return async (dispatch, getState) => {
  243. const timeZone = getTimeZone(getState().user);
  244. const range = getTimeRange(timeZone, rawRange);
  245. dispatch(loadExploreDatasourcesAndSetDatasource(exploreId, datasourceName));
  246. dispatch(
  247. initializeExploreAction({
  248. exploreId,
  249. containerWidth,
  250. eventBridge,
  251. queries,
  252. range,
  253. ui,
  254. })
  255. );
  256. };
  257. }
  258. /**
  259. * Datasource loading was successfully completed.
  260. */
  261. export const loadDatasourceReady = (
  262. exploreId: ExploreId,
  263. instance: DataSourceApi
  264. ): ActionOf<LoadDatasourceReadyPayload> => {
  265. const historyKey = `grafana.explore.history.${instance.meta.id}`;
  266. const history = store.getObject(historyKey, []);
  267. // Save last-used datasource
  268. store.set(LAST_USED_DATASOURCE_KEY, instance.name);
  269. return loadDatasourceReadyAction({
  270. exploreId,
  271. history,
  272. });
  273. };
  274. export function importQueries(
  275. exploreId: ExploreId,
  276. queries: DataQuery[],
  277. sourceDataSource: DataSourceApi,
  278. targetDataSource: DataSourceApi
  279. ): ThunkResult<void> {
  280. return async dispatch => {
  281. if (!sourceDataSource) {
  282. // explore not initialized
  283. dispatch(queriesImportedAction({ exploreId, queries }));
  284. return;
  285. }
  286. let importedQueries = queries;
  287. // Check if queries can be imported from previously selected datasource
  288. if (sourceDataSource.meta.id === targetDataSource.meta.id) {
  289. // Keep same queries if same type of datasource
  290. importedQueries = [...queries];
  291. } else if (targetDataSource.importQueries) {
  292. // Datasource-specific importers
  293. importedQueries = await targetDataSource.importQueries(queries, sourceDataSource.meta);
  294. } else {
  295. // Default is blank queries
  296. importedQueries = ensureQueries();
  297. }
  298. const nextQueries = ensureQueries(importedQueries);
  299. dispatch(queriesImportedAction({ exploreId, queries: nextQueries }));
  300. };
  301. }
  302. /**
  303. * Tests datasource.
  304. */
  305. export const testDatasource = (exploreId: ExploreId, instance: DataSourceApi): ThunkResult<void> => {
  306. return async dispatch => {
  307. let datasourceError = null;
  308. dispatch(testDataSourcePendingAction({ exploreId }));
  309. try {
  310. const testResult = await instance.testDatasource();
  311. datasourceError = testResult.status === 'success' ? null : testResult.message;
  312. } catch (error) {
  313. datasourceError = (error && error.statusText) || 'Network error';
  314. }
  315. if (datasourceError) {
  316. dispatch(testDataSourceFailureAction({ exploreId, error: datasourceError }));
  317. return;
  318. }
  319. dispatch(testDataSourceSuccessAction({ exploreId }));
  320. };
  321. };
  322. /**
  323. * Reconnects datasource when there is a connection failure.
  324. */
  325. export const reconnectDatasource = (exploreId: ExploreId): ThunkResult<void> => {
  326. return async (dispatch, getState) => {
  327. const instance = getState().explore[exploreId].datasourceInstance;
  328. dispatch(changeDatasource(exploreId, instance.name));
  329. };
  330. };
  331. /**
  332. * Main action to asynchronously load a datasource. Dispatches lots of smaller actions for feedback.
  333. */
  334. export function loadDatasource(exploreId: ExploreId, instance: DataSourceApi): ThunkResult<void> {
  335. return async (dispatch, getState) => {
  336. const datasourceName = instance.name;
  337. // Keep ID to track selection
  338. dispatch(loadDatasourcePendingAction({ exploreId, requestedDatasourceName: datasourceName }));
  339. await dispatch(testDatasource(exploreId, instance));
  340. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  341. // User already changed datasource again, discard results
  342. return;
  343. }
  344. if (instance.init) {
  345. try {
  346. instance.init();
  347. } catch (err) {
  348. console.log(err);
  349. }
  350. }
  351. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  352. // User already changed datasource again, discard results
  353. return;
  354. }
  355. dispatch(loadDatasourceReady(exploreId, instance));
  356. };
  357. }
  358. /**
  359. * Action to modify a query given a datasource-specific modifier action.
  360. * @param exploreId Explore area
  361. * @param modification Action object with a type, e.g., ADD_FILTER
  362. * @param index Optional query row index. If omitted, the modification is applied to all query rows.
  363. * @param modifier Function that executes the modification, typically `datasourceInstance.modifyQueries`.
  364. */
  365. export function modifyQueries(
  366. exploreId: ExploreId,
  367. modification: QueryFixAction,
  368. index: number,
  369. modifier: any
  370. ): ThunkResult<void> {
  371. return dispatch => {
  372. dispatch(modifyQueriesAction({ exploreId, modification, index, modifier }));
  373. if (!modification.preventSubmit) {
  374. dispatch(runQueries(exploreId));
  375. }
  376. };
  377. }
  378. export function processQueryErrors(
  379. exploreId: ExploreId,
  380. response: any,
  381. resultType: ResultType,
  382. datasourceId: string
  383. ): ThunkResult<void> {
  384. return (dispatch, getState) => {
  385. const { datasourceInstance } = getState().explore[exploreId];
  386. if (datasourceInstance.meta.id !== datasourceId || response.cancelled) {
  387. // Navigated away, queries did not matter
  388. return;
  389. }
  390. console.error(response); // To help finding problems with query syntax
  391. if (!instanceOfDataQueryError(response)) {
  392. response = toDataQueryError(response);
  393. }
  394. dispatch(
  395. queryFailureAction({
  396. exploreId,
  397. response,
  398. resultType,
  399. })
  400. );
  401. };
  402. }
  403. /**
  404. * @param exploreId Explore area
  405. * @param response Response from `datasourceInstance.query()`
  406. * @param latency Duration between request and response
  407. * @param resultType The type of result
  408. * @param datasourceId Origin datasource instance, used to discard results if current datasource is different
  409. */
  410. export function processQueryResults(
  411. exploreId: ExploreId,
  412. response: any,
  413. latency: number,
  414. resultType: ResultType,
  415. datasourceId: string
  416. ): ThunkResult<void> {
  417. return (dispatch, getState) => {
  418. const { datasourceInstance, scanning, scanner } = getState().explore[exploreId];
  419. // If datasource already changed, results do not matter
  420. if (datasourceInstance.meta.id !== datasourceId) {
  421. return;
  422. }
  423. const series: any[] = response.data;
  424. const refIds = getRefIds(series);
  425. // Clears any previous errors that now have a successful query, important so Angular editors are updated correctly
  426. dispatch(
  427. resetQueryErrorAction({
  428. exploreId,
  429. refIds,
  430. })
  431. );
  432. const resultGetter =
  433. resultType === 'Graph' ? makeTimeSeriesList : resultType === 'Table' ? (data: any[]) => data : null;
  434. const result = resultGetter ? resultGetter(series, null, []) : series;
  435. dispatch(
  436. querySuccessAction({
  437. exploreId,
  438. result,
  439. resultType,
  440. latency,
  441. })
  442. );
  443. // Keep scanning for results if this was the last scanning transaction
  444. if (scanning) {
  445. if (_.size(result) === 0) {
  446. const range = scanner();
  447. dispatch(scanRangeAction({ exploreId, range }));
  448. } else {
  449. // We can stop scanning if we have a result
  450. dispatch(scanStopAction({ exploreId }));
  451. }
  452. }
  453. };
  454. }
  455. /**
  456. * Main action to run queries and dispatches sub-actions based on which result viewers are active
  457. */
  458. export function runQueries(exploreId: ExploreId, ignoreUIState = false, replaceUrl = false): ThunkResult<void> {
  459. return (dispatch, getState) => {
  460. const {
  461. datasourceInstance,
  462. queries,
  463. showingGraph,
  464. showingTable,
  465. datasourceError,
  466. containerWidth,
  467. mode,
  468. } = getState().explore[exploreId];
  469. if (datasourceError) {
  470. // let's not run any queries if data source is in a faulty state
  471. return;
  472. }
  473. if (!hasNonEmptyQuery(queries)) {
  474. dispatch(clearQueriesAction({ exploreId }));
  475. dispatch(stateSave(replaceUrl)); // Remember to save to state and update location
  476. return;
  477. }
  478. // Some datasource's query builders allow per-query interval limits,
  479. // but we're using the datasource interval limit for now
  480. const interval = datasourceInstance.interval;
  481. dispatch(runQueriesAction({ exploreId }));
  482. // Keep table queries first since they need to return quickly
  483. if ((ignoreUIState || showingTable) && mode === ExploreMode.Metrics) {
  484. dispatch(
  485. runQueriesForType(exploreId, 'Table', {
  486. interval,
  487. format: 'table',
  488. instant: true,
  489. valueWithRefId: true,
  490. })
  491. );
  492. }
  493. if ((ignoreUIState || showingGraph) && mode === ExploreMode.Metrics) {
  494. dispatch(
  495. runQueriesForType(exploreId, 'Graph', {
  496. interval,
  497. format: 'time_series',
  498. instant: false,
  499. maxDataPoints: containerWidth,
  500. })
  501. );
  502. }
  503. if (mode === ExploreMode.Logs) {
  504. dispatch(runQueriesForType(exploreId, 'Logs', { interval, format: 'logs' }));
  505. }
  506. dispatch(stateSave(replaceUrl));
  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. ): ThunkResult<void> {
  521. return async (dispatch, getState) => {
  522. const { datasourceInstance, eventBridge, queries, queryIntervals, range, scanning, history } = getState().explore[
  523. exploreId
  524. ];
  525. if (resultType === 'Logs' && datasourceInstance.convertToStreamTargets) {
  526. dispatch(
  527. startSubscriptionsAction({
  528. exploreId,
  529. dataReceivedActionCreator: subscriptionDataReceivedAction,
  530. })
  531. );
  532. }
  533. const datasourceId = datasourceInstance.meta.id;
  534. const transaction = buildQueryTransaction(queries, resultType, queryOptions, range, queryIntervals, scanning);
  535. dispatch(queryStartAction({ exploreId, resultType, rowIndex: 0, transaction }));
  536. try {
  537. const now = Date.now();
  538. const response = await datasourceInstance.query(transaction.options);
  539. eventBridge.emit('data-received', response.data || []);
  540. const latency = Date.now() - now;
  541. // Side-effect: Saving history in localstorage
  542. const nextHistory = updateHistory(history, datasourceId, queries);
  543. dispatch(historyUpdatedAction({ exploreId, history: nextHistory }));
  544. dispatch(processQueryResults(exploreId, response, latency, resultType, datasourceId));
  545. } catch (err) {
  546. eventBridge.emit('data-error', err);
  547. dispatch(processQueryErrors(exploreId, err, resultType, datasourceId));
  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, getState) => {
  572. // Inject react keys into query objects
  573. const queries = getState().explore[exploreId].queries;
  574. const nextQueries = rawQueries.map((query, index) => generateNewKeyAndAddRefIdIfMissing(query, queries, index));
  575. dispatch(setQueriesAction({ exploreId, queries: nextQueries }));
  576. dispatch(runQueries(exploreId));
  577. };
  578. }
  579. /**
  580. * Close the split view and save URL state.
  581. */
  582. export function splitClose(itemId: ExploreId): ThunkResult<void> {
  583. return dispatch => {
  584. dispatch(splitCloseAction({ itemId }));
  585. dispatch(stateSave());
  586. };
  587. }
  588. /**
  589. * Open the split view and copy the left state to be the right state.
  590. * The right state is automatically initialized.
  591. * The copy keeps all query modifications but wipes the query results.
  592. */
  593. export function splitOpen(): ThunkResult<void> {
  594. return (dispatch, getState) => {
  595. // Clone left state to become the right state
  596. const leftState = getState().explore[ExploreId.left];
  597. const queryState = getState().location.query[ExploreId.left] as string;
  598. const urlState = parseUrlState(queryState);
  599. const queryTransactions: QueryTransaction[] = [];
  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. const toRawTimeRange = (range: TimeRange): RawTimeRange => {
  612. let from = range.raw.from;
  613. if (isDateTime(from)) {
  614. from = from.valueOf().toString(10);
  615. }
  616. let to = range.raw.to;
  617. if (isDateTime(to)) {
  618. to = to.valueOf().toString(10);
  619. }
  620. return {
  621. from,
  622. to,
  623. };
  624. };
  625. /**
  626. * Saves Explore state to URL using the `left` and `right` parameters.
  627. * If split view is not active, `right` will not be set.
  628. */
  629. export function stateSave(replaceUrl = false): ThunkResult<void> {
  630. return (dispatch, getState) => {
  631. const { left, right, split } = getState().explore;
  632. const urlStates: { [index: string]: string } = {};
  633. const leftUrlState: ExploreUrlState = {
  634. datasource: left.datasourceInstance.name,
  635. queries: left.queries.map(clearQueryKeys),
  636. range: toRawTimeRange(left.range),
  637. ui: {
  638. showingGraph: left.showingGraph,
  639. showingLogs: true,
  640. showingTable: left.showingTable,
  641. dedupStrategy: left.dedupStrategy,
  642. },
  643. };
  644. urlStates.left = serializeStateToUrlParam(leftUrlState, true);
  645. if (split) {
  646. const rightUrlState: ExploreUrlState = {
  647. datasource: right.datasourceInstance.name,
  648. queries: right.queries.map(clearQueryKeys),
  649. range: toRawTimeRange(right.range),
  650. ui: {
  651. showingGraph: right.showingGraph,
  652. showingLogs: true,
  653. showingTable: right.showingTable,
  654. dedupStrategy: right.dedupStrategy,
  655. },
  656. };
  657. urlStates.right = serializeStateToUrlParam(rightUrlState, true);
  658. }
  659. dispatch(updateLocation({ query: urlStates, replace: replaceUrl }));
  660. };
  661. }
  662. /**
  663. * Creates action to collapse graph/logs/table panel. When panel is collapsed,
  664. * queries won't be run
  665. */
  666. const togglePanelActionCreator = (
  667. actionCreator: ActionCreator<ToggleGraphPayload> | ActionCreator<ToggleTablePayload>
  668. ) => (exploreId: ExploreId, isPanelVisible: boolean): ThunkResult<void> => {
  669. return dispatch => {
  670. let uiFragmentStateUpdate: Partial<ExploreUIState>;
  671. const shouldRunQueries = !isPanelVisible;
  672. switch (actionCreator.type) {
  673. case toggleGraphAction.type:
  674. uiFragmentStateUpdate = { showingGraph: !isPanelVisible };
  675. break;
  676. case toggleTableAction.type:
  677. uiFragmentStateUpdate = { showingTable: !isPanelVisible };
  678. break;
  679. }
  680. dispatch(actionCreator({ exploreId }));
  681. dispatch(updateExploreUIState(exploreId, uiFragmentStateUpdate));
  682. if (shouldRunQueries) {
  683. dispatch(runQueries(exploreId));
  684. }
  685. };
  686. };
  687. /**
  688. * Expand/collapse the graph result viewer. When collapsed, graph queries won't be run.
  689. */
  690. export const toggleGraph = togglePanelActionCreator(toggleGraphAction);
  691. /**
  692. * Expand/collapse the table result viewer. When collapsed, table queries won't be run.
  693. */
  694. export const toggleTable = togglePanelActionCreator(toggleTableAction);
  695. /**
  696. * Change logs deduplication strategy and update URL.
  697. */
  698. export const changeDedupStrategy = (exploreId: ExploreId, dedupStrategy: LogsDedupStrategy): ThunkResult<void> => {
  699. return dispatch => {
  700. dispatch(updateExploreUIState(exploreId, { dedupStrategy }));
  701. };
  702. };
  703. export function refreshExplore(exploreId: ExploreId): ThunkResult<void> {
  704. return (dispatch, getState) => {
  705. const itemState = getState().explore[exploreId];
  706. if (!itemState.initialized) {
  707. return;
  708. }
  709. const { urlState, update, containerWidth, eventBridge } = itemState;
  710. const { datasource, queries, range: urlRange, ui } = urlState;
  711. const refreshQueries: DataQuery[] = [];
  712. for (let index = 0; index < queries.length; index++) {
  713. const query = queries[index];
  714. refreshQueries.push(generateNewKeyAndAddRefIdIfMissing(query, refreshQueries, index));
  715. }
  716. const timeZone = getTimeZone(getState().user);
  717. const range = getTimeRangeFromUrl(urlRange, timeZone);
  718. // need to refresh datasource
  719. if (update.datasource) {
  720. const initialQueries = ensureQueries(queries);
  721. dispatch(initializeExplore(exploreId, datasource, initialQueries, range, containerWidth, eventBridge, ui));
  722. return;
  723. }
  724. if (update.range) {
  725. dispatch(changeTimeAction({ exploreId, range }));
  726. }
  727. // need to refresh ui state
  728. if (update.ui) {
  729. dispatch(updateUIStateAction({ ...ui, exploreId }));
  730. }
  731. // need to refresh queries
  732. if (update.queries) {
  733. dispatch(setQueriesAction({ exploreId, queries: refreshQueries }));
  734. }
  735. // always run queries when refresh is needed
  736. if (update.queries || update.ui || update.range) {
  737. dispatch(runQueries(exploreId));
  738. }
  739. };
  740. }