results.tsx 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. import {Component, Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import type {Location} from 'history';
  5. import isEqual from 'lodash/isEqual';
  6. import omit from 'lodash/omit';
  7. import {updateSavedQueryVisit} from 'sentry/actionCreators/discoverSavedQueries';
  8. import {fetchTotalCount} from 'sentry/actionCreators/events';
  9. import {fetchProjectsCount} from 'sentry/actionCreators/projects';
  10. import {loadOrganizationTags} from 'sentry/actionCreators/tags';
  11. import {Client} from 'sentry/api';
  12. import {Alert} from 'sentry/components/alert';
  13. import {Button} from 'sentry/components/button';
  14. import Confirm from 'sentry/components/confirm';
  15. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  16. import SearchBar from 'sentry/components/events/searchBar';
  17. import * as Layout from 'sentry/components/layouts/thirds';
  18. import ExternalLink from 'sentry/components/links/externalLink';
  19. import LoadingIndicator from 'sentry/components/loadingIndicator';
  20. import {DatePageFilter} from 'sentry/components/organizations/datePageFilter';
  21. import {EnvironmentPageFilter} from 'sentry/components/organizations/environmentPageFilter';
  22. import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  23. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  24. import {
  25. normalizeDateTimeParams,
  26. normalizeDateTimeString,
  27. } from 'sentry/components/organizations/pageFilters/parse';
  28. import {ProjectPageFilter} from 'sentry/components/organizations/projectPageFilter';
  29. import type {CursorHandler} from 'sentry/components/pagination';
  30. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  31. import {MAX_QUERY_LENGTH} from 'sentry/constants';
  32. import {IconClose} from 'sentry/icons/iconClose';
  33. import {t, tct} from 'sentry/locale';
  34. import {space} from 'sentry/styles/space';
  35. import type {PageFilters} from 'sentry/types/core';
  36. import {SavedSearchType} from 'sentry/types/group';
  37. import type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  38. import type {NewQuery, Organization, SavedQuery} from 'sentry/types/organization';
  39. import {defined, generateQueryWithTag} from 'sentry/utils';
  40. import {trackAnalytics} from 'sentry/utils/analytics';
  41. import {browserHistory} from 'sentry/utils/browserHistory';
  42. import type {CustomMeasurementCollection} from 'sentry/utils/customMeasurements/customMeasurements';
  43. import {CustomMeasurementsContext} from 'sentry/utils/customMeasurements/customMeasurementsContext';
  44. import {CustomMeasurementsProvider} from 'sentry/utils/customMeasurements/customMeasurementsProvider';
  45. import EventView, {isAPIPayloadSimilar} from 'sentry/utils/discover/eventView';
  46. import {formatTagKey, generateAggregateFields} from 'sentry/utils/discover/fields';
  47. import {
  48. DatasetSource,
  49. DiscoverDatasets,
  50. DisplayModes,
  51. MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES,
  52. SavedQueryDatasets,
  53. } from 'sentry/utils/discover/types';
  54. import localStorage from 'sentry/utils/localStorage';
  55. import marked from 'sentry/utils/marked';
  56. import {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
  57. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  58. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  59. import withApi from 'sentry/utils/withApi';
  60. import withOrganization from 'sentry/utils/withOrganization';
  61. import withPageFilters from 'sentry/utils/withPageFilters';
  62. import {hasDatasetSelector} from 'sentry/views/dashboards/utils';
  63. import {DATASET_LABEL_MAP} from 'sentry/views/discover/savedQuery/datasetSelectorTabs';
  64. import {
  65. getDatasetFromLocationOrSavedQueryDataset,
  66. getSavedQueryDataset,
  67. getSavedQueryWithDataset,
  68. } from 'sentry/views/discover/savedQuery/utils';
  69. import {addRoutePerformanceContext} from '../performance/utils';
  70. import {DEFAULT_EVENT_VIEW, DEFAULT_EVENT_VIEW_MAP} from './data';
  71. import ResultsChart from './resultsChart';
  72. import ResultsHeader from './resultsHeader';
  73. import ResultsSearchQueryBuilder from './resultsSearchQueryBuilder';
  74. import {SampleDataAlert} from './sampleDataAlert';
  75. import Table from './table';
  76. import Tags from './tags';
  77. import {generateTitle} from './utils';
  78. type Props = {
  79. api: Client;
  80. loading: boolean;
  81. location: Location;
  82. organization: Organization;
  83. router: InjectedRouter;
  84. selection: PageFilters;
  85. setSavedQuery: (savedQuery?: SavedQuery) => void;
  86. isHomepage?: boolean;
  87. savedQuery?: SavedQuery;
  88. };
  89. type State = {
  90. confirmedQuery: boolean;
  91. error: string;
  92. errorCode: number;
  93. eventView: EventView;
  94. needConfirmation: boolean;
  95. showTags: boolean;
  96. tips: string[];
  97. totalValues: null | number;
  98. homepageQuery?: SavedQuery;
  99. savedQuery?: SavedQuery;
  100. savedQueryDataset?: SavedQueryDatasets;
  101. showForcedDatasetAlert?: boolean;
  102. showMetricsAlert?: boolean;
  103. showQueryIncompatibleWithDataset?: boolean;
  104. showUnparameterizedBanner?: boolean;
  105. splitDecision?: SavedQueryDatasets;
  106. };
  107. const SHOW_TAGS_STORAGE_KEY = 'discover2:show-tags';
  108. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  109. function readShowTagsState() {
  110. const value = localStorage.getItem(SHOW_TAGS_STORAGE_KEY);
  111. return value === '1';
  112. }
  113. function getYAxis(location: Location, eventView: EventView, savedQuery?: SavedQuery) {
  114. if (location.query.yAxis) {
  115. return decodeList(location.query.yAxis);
  116. }
  117. if (location.query.yAxis === null) {
  118. return [];
  119. }
  120. return savedQuery?.yAxis && savedQuery?.yAxis.length > 0
  121. ? decodeList(savedQuery?.yAxis)
  122. : [eventView.getYAxis()];
  123. }
  124. export class Results extends Component<Props, State> {
  125. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State): State {
  126. const savedQueryDataset = getSavedQueryDataset(
  127. nextProps.organization,
  128. nextProps.location,
  129. nextProps.savedQuery,
  130. undefined
  131. );
  132. const eventViewFromQuery = EventView.fromSavedQueryOrLocation(
  133. nextProps.savedQuery,
  134. nextProps.location
  135. );
  136. const eventView =
  137. hasDatasetSelector(nextProps.organization) && !eventViewFromQuery.dataset
  138. ? eventViewFromQuery.withDataset(
  139. getDatasetFromLocationOrSavedQueryDataset(undefined, savedQueryDataset)
  140. )
  141. : eventViewFromQuery;
  142. return {...prevState, eventView, savedQuery: nextProps.savedQuery, savedQueryDataset};
  143. }
  144. state: State = {
  145. eventView: EventView.fromSavedQueryOrLocation(
  146. this.props.savedQuery,
  147. this.props.location
  148. ),
  149. savedQueryDataset: getSavedQueryDataset(
  150. this.props.organization,
  151. this.props.location,
  152. this.props.savedQuery,
  153. undefined
  154. ),
  155. error: '',
  156. homepageQuery: undefined,
  157. errorCode: 200,
  158. totalValues: null,
  159. showTags: readShowTagsState(),
  160. needConfirmation: false,
  161. confirmedQuery: false,
  162. tips: [],
  163. showForcedDatasetAlert: true,
  164. showQueryIncompatibleWithDataset: false,
  165. };
  166. componentDidMount() {
  167. const {organization, selection, location, isHomepage} = this.props;
  168. if (location.query.fromMetric) {
  169. this.setState({showMetricsAlert: true});
  170. browserHistory.replace({
  171. ...location,
  172. query: {...location.query, fromMetric: undefined},
  173. });
  174. }
  175. if (location.query[SHOW_UNPARAM_BANNER]) {
  176. this.setState({showUnparameterizedBanner: true});
  177. browserHistory.replace({
  178. ...location,
  179. query: {...location.query, [SHOW_UNPARAM_BANNER]: undefined},
  180. });
  181. }
  182. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  183. addRoutePerformanceContext(selection);
  184. this.checkEventView();
  185. this.canLoadEvents();
  186. if (!isHomepage && defined(location.query.id)) {
  187. updateSavedQueryVisit(organization.slug, location.query.id);
  188. }
  189. }
  190. componentDidUpdate(prevProps: Props, prevState: State) {
  191. const {location, organization, selection} = this.props;
  192. const {eventView, confirmedQuery, savedQuery} = this.state;
  193. if (location.query.incompatible) {
  194. this.setState({showQueryIncompatibleWithDataset: true});
  195. browserHistory.replace({
  196. ...location,
  197. query: {...location.query, incompatible: undefined},
  198. });
  199. }
  200. this.checkEventView();
  201. const currentQuery = eventView.getEventsAPIPayload(location);
  202. const prevQuery = prevState.eventView.getEventsAPIPayload(prevProps.location);
  203. const yAxisArray = getYAxis(location, eventView, savedQuery);
  204. const prevYAxisArray = getYAxis(prevProps.location, eventView, prevState.savedQuery);
  205. const savedQueryDataset =
  206. decodeScalar(location.query.queryDataset) ?? savedQuery?.queryDataset;
  207. const prevSavedQueryDataset =
  208. decodeScalar(prevProps.location.query.queryDataset) ??
  209. prevState.savedQuery?.queryDataset;
  210. const datasetChanged = !isEqual(savedQueryDataset, prevSavedQueryDataset);
  211. if (
  212. !isAPIPayloadSimilar(currentQuery, prevQuery) ||
  213. this.hasChartParametersChanged(
  214. prevState.eventView,
  215. eventView,
  216. prevYAxisArray,
  217. yAxisArray
  218. ) ||
  219. datasetChanged
  220. ) {
  221. this.canLoadEvents();
  222. }
  223. if (
  224. !isEqual(prevProps.selection.datetime, selection.datetime) ||
  225. !isEqual(prevProps.selection.projects, selection.projects)
  226. ) {
  227. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  228. addRoutePerformanceContext(selection);
  229. }
  230. if (prevState.confirmedQuery !== confirmedQuery) {
  231. this.fetchTotalCount();
  232. }
  233. }
  234. tagsApi: Client = new Client();
  235. hasChartParametersChanged(
  236. prevEventView: EventView,
  237. eventView: EventView,
  238. prevYAxisArray: string[],
  239. yAxisArray: string[]
  240. ) {
  241. if (!isEqual(prevYAxisArray, yAxisArray)) {
  242. return true;
  243. }
  244. const prevDisplay = prevEventView.getDisplayMode();
  245. const display = eventView.getDisplayMode();
  246. return prevDisplay !== display;
  247. }
  248. canLoadEvents = async () => {
  249. const {api, location, organization} = this.props;
  250. const {eventView} = this.state;
  251. let needConfirmation = false;
  252. let confirmedQuery = true;
  253. const currentQuery = eventView.getEventsAPIPayload(location);
  254. const duration = eventView.getDays();
  255. if (duration > 30 && currentQuery.project) {
  256. let projectLength = currentQuery.project.length;
  257. if (
  258. projectLength === 0 ||
  259. (projectLength === 1 && currentQuery.project[0] === '-1')
  260. ) {
  261. try {
  262. const results = await fetchProjectsCount(api, organization.slug);
  263. if (projectLength === 0) {
  264. projectLength = results.myProjects;
  265. } else {
  266. projectLength = results.allProjects;
  267. }
  268. } catch (err) {
  269. // do nothing, so the length is 0 or 1 and the query is assumed safe
  270. }
  271. }
  272. if (projectLength > 10) {
  273. needConfirmation = true;
  274. confirmedQuery = false;
  275. }
  276. }
  277. // Once confirmed, a change of project or datetime will happen before this can set it to false,
  278. // this means a query will still happen even if the new conditions need confirmation
  279. // using a state callback to return this to false
  280. this.setState({needConfirmation, confirmedQuery}, () => {
  281. this.setState({confirmedQuery: false});
  282. });
  283. if (needConfirmation) {
  284. this.openConfirm();
  285. }
  286. };
  287. openConfirm = () => {};
  288. setOpenFunction = ({open}) => {
  289. this.openConfirm = open;
  290. return null;
  291. };
  292. handleConfirmed = () => {
  293. this.setState({needConfirmation: false, confirmedQuery: true}, () => {
  294. this.setState({confirmedQuery: false});
  295. });
  296. };
  297. handleCancelled = () => {
  298. this.setState({needConfirmation: false, confirmedQuery: false});
  299. };
  300. async fetchTotalCount() {
  301. const {api, organization, location} = this.props;
  302. const {eventView, confirmedQuery} = this.state;
  303. if (confirmedQuery === false || !eventView.isValid()) {
  304. return;
  305. }
  306. try {
  307. const totals = await fetchTotalCount(
  308. api,
  309. organization.slug,
  310. eventView.getEventsAPIPayload(location)
  311. );
  312. this.setState({totalValues: totals});
  313. } catch (err) {
  314. Sentry.captureException(err);
  315. }
  316. }
  317. checkEventView() {
  318. const {eventView, splitDecision, savedQueryDataset} = this.state;
  319. const {loading} = this.props;
  320. if (eventView.isValid() || loading) {
  321. return;
  322. }
  323. // If the view is not valid, redirect to a known valid state.
  324. const {location, organization, selection, isHomepage, savedQuery} = this.props;
  325. const value = getSavedQueryDataset(organization, location, savedQuery, splitDecision);
  326. const defaultEventView = hasDatasetSelector(organization)
  327. ? (getSavedQueryWithDataset(DEFAULT_EVENT_VIEW_MAP[value]) as NewQuery)
  328. : DEFAULT_EVENT_VIEW;
  329. const query = isHomepage && savedQuery ? omit(savedQuery, 'id') : defaultEventView;
  330. const nextEventView = EventView.fromNewQueryWithLocation(query, location);
  331. if (nextEventView.project.length === 0 && selection.projects) {
  332. nextEventView.project = selection.projects;
  333. }
  334. if (selection.datetime) {
  335. const {period, utc, start, end} = selection.datetime;
  336. nextEventView.statsPeriod = period ?? undefined;
  337. nextEventView.utc = utc?.toString();
  338. nextEventView.start = normalizeDateTimeString(start);
  339. nextEventView.end = normalizeDateTimeString(end);
  340. }
  341. if (location.query?.query) {
  342. nextEventView.query = decodeScalar(location.query.query, '');
  343. }
  344. if (isHomepage && !this.state.savedQuery) {
  345. this.setState({savedQuery, eventView: nextEventView});
  346. }
  347. browserHistory.replace(
  348. normalizeUrl(
  349. nextEventView.getResultsViewUrlTarget(
  350. organization.slug,
  351. isHomepage,
  352. hasDatasetSelector(organization) ? savedQueryDataset : undefined
  353. )
  354. )
  355. );
  356. }
  357. handleCursor: CursorHandler = (cursor, path, query, _direction) => {
  358. const {router} = this.props;
  359. router.push({
  360. pathname: path,
  361. query: {...query, cursor},
  362. });
  363. // Treat pagination like the user already confirmed the query
  364. if (!this.state.needConfirmation) {
  365. this.handleConfirmed();
  366. }
  367. };
  368. handleChangeShowTags = () => {
  369. const {organization} = this.props;
  370. trackAnalytics('discover_v2.results.toggle_tag_facets', {
  371. organization,
  372. });
  373. this.setState(state => {
  374. const newValue = !state.showTags;
  375. localStorage.setItem(SHOW_TAGS_STORAGE_KEY, newValue ? '1' : '0');
  376. return {...state, showTags: newValue};
  377. });
  378. };
  379. handleSearch = (query: string) => {
  380. const {router, location} = this.props;
  381. const queryParams = normalizeDateTimeParams({
  382. ...(location.query || {}),
  383. query,
  384. });
  385. // do not propagate pagination when making a new search
  386. const searchQueryParams = omit(queryParams, 'cursor');
  387. router.push({
  388. pathname: location.pathname,
  389. query: searchQueryParams,
  390. });
  391. };
  392. handleYAxisChange = (value: string[]) => {
  393. const {router, location} = this.props;
  394. const isDisplayMultiYAxisSupported = MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES.includes(
  395. location.query.display as DisplayModes
  396. );
  397. const newQuery = {
  398. ...location.query,
  399. yAxis: value.length > 0 ? value : [null],
  400. // If using Multi Y-axis and not in a supported display, change to the default display mode
  401. display:
  402. value.length > 1 && !isDisplayMultiYAxisSupported
  403. ? location.query.display === DisplayModes.DAILYTOP5
  404. ? DisplayModes.DAILY
  405. : DisplayModes.DEFAULT
  406. : location.query.display,
  407. };
  408. router.push({
  409. pathname: location.pathname,
  410. query: newQuery,
  411. });
  412. // Treat axis changing like the user already confirmed the query
  413. if (!this.state.needConfirmation) {
  414. this.handleConfirmed();
  415. }
  416. trackAnalytics('discover_v2.y_axis_change', {
  417. organization: this.props.organization,
  418. y_axis_value: value,
  419. });
  420. };
  421. handleDisplayChange = (value: string) => {
  422. const {router, location} = this.props;
  423. const newQuery = {
  424. ...location.query,
  425. display: value,
  426. };
  427. router.push({
  428. pathname: location.pathname,
  429. query: newQuery,
  430. });
  431. // Treat display changing like the user already confirmed the query
  432. if (!this.state.needConfirmation) {
  433. this.handleConfirmed();
  434. }
  435. };
  436. handleIntervalChange = (value: string | undefined) => {
  437. const {router, location} = this.props;
  438. const newQuery = {
  439. ...location.query,
  440. interval: value,
  441. };
  442. if (location.query.interval !== value) {
  443. router.push({
  444. pathname: location.pathname,
  445. query: newQuery,
  446. });
  447. // Treat display changing like the user already confirmed the query
  448. if (!this.state.needConfirmation) {
  449. this.handleConfirmed();
  450. }
  451. }
  452. };
  453. handleTopEventsChange = (value: string) => {
  454. const {router, location} = this.props;
  455. const newQuery = {
  456. ...location.query,
  457. topEvents: value,
  458. };
  459. router.push({
  460. pathname: location.pathname,
  461. query: newQuery,
  462. });
  463. // Treat display changing like the user already confirmed the query
  464. if (!this.state.needConfirmation) {
  465. this.handleConfirmed();
  466. }
  467. };
  468. getDocumentTitle(): string {
  469. const {eventView} = this.state;
  470. const {isHomepage} = this.props;
  471. if (!eventView) {
  472. return '';
  473. }
  474. return generateTitle({eventView, isHomepage});
  475. }
  476. renderTagsTable() {
  477. const {organization, location} = this.props;
  478. const {eventView, totalValues, confirmedQuery} = this.state;
  479. return (
  480. <Layout.Side>
  481. <Tags
  482. generateUrl={this.generateTagUrl}
  483. totalValues={totalValues}
  484. eventView={eventView}
  485. organization={organization}
  486. location={location}
  487. confirmedQuery={confirmedQuery}
  488. />
  489. </Layout.Side>
  490. );
  491. }
  492. generateTagUrl = (key: string, value: string) => {
  493. const {organization, isHomepage} = this.props;
  494. const {eventView, savedQueryDataset} = this.state;
  495. const url = eventView.getResultsViewUrlTarget(
  496. organization.slug,
  497. isHomepage,
  498. hasDatasetSelector(organization) ? savedQueryDataset : undefined
  499. );
  500. url.query = generateQueryWithTag(url.query, {
  501. key: formatTagKey(key),
  502. value,
  503. });
  504. return url;
  505. };
  506. renderError(error: string) {
  507. if (!error) {
  508. return null;
  509. }
  510. return (
  511. <Alert type="error" showIcon>
  512. {error}
  513. </Alert>
  514. );
  515. }
  516. setError = (error: string, errorCode: number) => {
  517. this.setState({error, errorCode});
  518. };
  519. renderMetricsFallbackBanner() {
  520. const {organization} = this.props;
  521. if (
  522. !organization.features.includes('performance-mep-bannerless-ui') &&
  523. this.state.showMetricsAlert
  524. ) {
  525. return (
  526. <Alert type="info" showIcon>
  527. {t(
  528. "You've navigated to this page from a performance metric widget generated from processed events. The results here only show indexed events."
  529. )}
  530. </Alert>
  531. );
  532. }
  533. if (this.state.showUnparameterizedBanner) {
  534. return (
  535. <Alert type="info" showIcon>
  536. {tct(
  537. 'These are unparameterized transactions. To better organize your transactions, [link:set transaction names manually].',
  538. {
  539. link: (
  540. <ExternalLink href="https://docs.sentry.io/platforms/javascript/tracing/instrumentation/automatic-instrumentation/#beforenavigate" />
  541. ),
  542. }
  543. )}
  544. </Alert>
  545. );
  546. }
  547. return null;
  548. }
  549. renderQueryIncompatibleWithDatasetBanner() {
  550. const {organization} = this.props;
  551. if (hasDatasetSelector(organization) && this.state.showQueryIncompatibleWithDataset) {
  552. return (
  553. <Alert
  554. type="warning"
  555. showIcon
  556. trailingItems={
  557. <StyledCloseButton
  558. icon={<IconClose size="sm" />}
  559. aria-label={t('Close')}
  560. onClick={() => {
  561. this.setState({showQueryIncompatibleWithDataset: false});
  562. }}
  563. size="zero"
  564. borderless
  565. />
  566. }
  567. >
  568. {t('Your query was updated to make it compatible with this dataset.')}
  569. </Alert>
  570. );
  571. }
  572. return null;
  573. }
  574. renderForcedDatasetBanner() {
  575. const {organization, savedQuery} = this.props;
  576. if (
  577. hasDatasetSelector(organization) &&
  578. this.state.showForcedDatasetAlert &&
  579. (this.state.splitDecision || savedQuery?.datasetSource === DatasetSource.FORCED)
  580. ) {
  581. const splitDecision = this.state.splitDecision ?? savedQuery?.queryDataset;
  582. if (!splitDecision) {
  583. return null;
  584. }
  585. return (
  586. <Alert
  587. type="warning"
  588. showIcon
  589. trailingItems={
  590. <StyledCloseButton
  591. icon={<IconClose size="sm" />}
  592. aria-label={t('Close')}
  593. onClick={() => {
  594. this.setState({showForcedDatasetAlert: false});
  595. }}
  596. size="zero"
  597. borderless
  598. />
  599. }
  600. >
  601. {tct(
  602. "We're splitting our datasets up to make it a bit easier to digest. We defaulted this query to [splitDecision]. Edit as you see fit.",
  603. {splitDecision: DATASET_LABEL_MAP[splitDecision]}
  604. )}
  605. </Alert>
  606. );
  607. }
  608. return null;
  609. }
  610. renderTips() {
  611. const {tips} = this.state;
  612. if (tips) {
  613. return tips.map((tip, index) => (
  614. <Alert type="info" showIcon key={`tip-${index}`}>
  615. <TipContainer dangerouslySetInnerHTML={{__html: marked(tip)}} />
  616. </Alert>
  617. ));
  618. }
  619. return null;
  620. }
  621. setTips = (tips: string[]) => {
  622. // If there are currently no tips set and the new tips are empty, do nothing
  623. // and bail out of an expensive entire table rerender
  624. if (!tips.length && !this.state.tips.length) {
  625. return;
  626. }
  627. this.setState({tips});
  628. };
  629. setSplitDecision = (value?: SavedQueryDatasets) => {
  630. const {eventView} = this.state;
  631. const newEventView = eventView.withDataset(
  632. getDatasetFromLocationOrSavedQueryDataset(undefined, value)
  633. );
  634. this.setState({
  635. splitDecision: value,
  636. savedQueryDataset: value,
  637. eventView: newEventView,
  638. });
  639. };
  640. renderSearchBar(customMeasurements: CustomMeasurementCollection | undefined) {
  641. const {organization} = this.props;
  642. const {eventView} = this.state;
  643. const fields = eventView.hasAggregateField()
  644. ? generateAggregateFields(organization, eventView.fields)
  645. : eventView.fields;
  646. if (organization.features.includes('search-query-builder-discover')) {
  647. return (
  648. <Wrapper>
  649. <ResultsSearchQueryBuilder
  650. projectIds={eventView.project}
  651. query={eventView.query}
  652. fields={fields}
  653. onSearch={this.handleSearch}
  654. customMeasurements={customMeasurements}
  655. dataset={eventView.dataset}
  656. includeTransactions
  657. />
  658. </Wrapper>
  659. );
  660. }
  661. let savedSearchType: SavedSearchType | undefined = SavedSearchType.EVENT;
  662. if (hasDatasetSelector(organization)) {
  663. savedSearchType =
  664. eventView.dataset === DiscoverDatasets.TRANSACTIONS
  665. ? SavedSearchType.TRANSACTION
  666. : SavedSearchType.ERROR;
  667. }
  668. return (
  669. <StyledSearchBar
  670. searchSource="eventsv2"
  671. organization={organization}
  672. projectIds={eventView.project}
  673. query={eventView.query}
  674. fields={fields}
  675. onSearch={this.handleSearch}
  676. maxQueryLength={MAX_QUERY_LENGTH}
  677. customMeasurements={customMeasurements}
  678. dataset={eventView.dataset}
  679. includeTransactions
  680. savedSearchType={savedSearchType}
  681. />
  682. );
  683. }
  684. render() {
  685. const {organization, location, router, selection, api, setSavedQuery, isHomepage} =
  686. this.props;
  687. const {
  688. eventView,
  689. error,
  690. errorCode,
  691. totalValues,
  692. showTags,
  693. confirmedQuery,
  694. savedQuery,
  695. splitDecision,
  696. savedQueryDataset,
  697. } = this.state;
  698. const hasDatasetSelectorFeature = hasDatasetSelector(organization);
  699. const query = eventView.query;
  700. const title = this.getDocumentTitle();
  701. const yAxisArray = getYAxis(location, eventView, savedQuery);
  702. if (!eventView.isValid()) {
  703. return <LoadingIndicator />;
  704. }
  705. return (
  706. <SentryDocumentTitle title={title} orgSlug={organization.slug}>
  707. <Fragment>
  708. <ResultsHeader
  709. setSavedQuery={setSavedQuery}
  710. errorCode={errorCode}
  711. organization={organization}
  712. location={location}
  713. eventView={eventView}
  714. yAxis={yAxisArray}
  715. router={router}
  716. isHomepage={isHomepage}
  717. splitDecision={splitDecision}
  718. />
  719. <Layout.Body>
  720. <CustomMeasurementsProvider organization={organization} selection={selection}>
  721. <Top fullWidth>
  722. {this.renderMetricsFallbackBanner()}
  723. {this.renderError(error)}
  724. {this.renderTips()}
  725. {this.renderForcedDatasetBanner()}
  726. {this.renderQueryIncompatibleWithDatasetBanner()}
  727. {!hasDatasetSelectorFeature && <SampleDataAlert query={query} />}
  728. <Wrapper>
  729. <PageFilterBar condensed>
  730. <ProjectPageFilter />
  731. <EnvironmentPageFilter />
  732. <DatePageFilter />
  733. </PageFilterBar>
  734. </Wrapper>
  735. <CustomMeasurementsContext.Consumer>
  736. {contextValue =>
  737. this.renderSearchBar(contextValue?.customMeasurements ?? undefined)
  738. }
  739. </CustomMeasurementsContext.Consumer>
  740. <MetricsCardinalityProvider
  741. organization={organization}
  742. location={location}
  743. >
  744. <ResultsChart
  745. api={api}
  746. router={router}
  747. organization={organization}
  748. eventView={eventView}
  749. location={location}
  750. onAxisChange={this.handleYAxisChange}
  751. onDisplayChange={this.handleDisplayChange}
  752. onTopEventsChange={this.handleTopEventsChange}
  753. onIntervalChange={this.handleIntervalChange}
  754. total={totalValues}
  755. confirmedQuery={confirmedQuery}
  756. yAxis={yAxisArray}
  757. />
  758. </MetricsCardinalityProvider>
  759. </Top>
  760. <Layout.Main fullWidth={!showTags}>
  761. <Table
  762. organization={organization}
  763. eventView={eventView}
  764. location={location}
  765. title={title}
  766. setError={this.setError}
  767. onChangeShowTags={this.handleChangeShowTags}
  768. showTags={showTags}
  769. confirmedQuery={confirmedQuery}
  770. onCursor={this.handleCursor}
  771. isHomepage={isHomepage}
  772. setTips={this.setTips}
  773. queryDataset={savedQueryDataset}
  774. setSplitDecision={(value?: SavedQueryDatasets) => {
  775. if (
  776. hasDatasetSelectorFeature &&
  777. value !== SavedQueryDatasets.DISCOVER &&
  778. value !== savedQuery?.dataset
  779. ) {
  780. this.setSplitDecision(value);
  781. }
  782. }}
  783. dataset={hasDatasetSelectorFeature ? eventView.dataset : undefined}
  784. />
  785. </Layout.Main>
  786. {showTags ? this.renderTagsTable() : null}
  787. <Confirm
  788. priority="primary"
  789. header={<strong>{t('May lead to thumb twiddling')}</strong>}
  790. confirmText={t('Do it')}
  791. cancelText={t('Nevermind')}
  792. onConfirm={this.handleConfirmed}
  793. onCancel={this.handleCancelled}
  794. message={
  795. <p>
  796. {tct(
  797. `You've created a query that will search for events made
  798. [dayLimit:over more than 30 days] for [projectLimit:more than 10 projects].
  799. A lot has happened during that time, so this might take awhile.
  800. Are you sure you want to do this?`,
  801. {
  802. dayLimit: <strong />,
  803. projectLimit: <strong />,
  804. }
  805. )}
  806. </p>
  807. }
  808. >
  809. {this.setOpenFunction}
  810. </Confirm>
  811. </CustomMeasurementsProvider>
  812. </Layout.Body>
  813. </Fragment>
  814. </SentryDocumentTitle>
  815. );
  816. }
  817. }
  818. const Wrapper = styled('div')`
  819. display: flex;
  820. flex-direction: row;
  821. gap: ${space(1)};
  822. margin-bottom: ${space(2)};
  823. @media (max-width: ${p => p.theme.breakpoints.small}) {
  824. display: grid;
  825. grid-auto-flow: row;
  826. }
  827. `;
  828. const StyledSearchBar = styled(SearchBar)`
  829. margin-bottom: ${space(2)};
  830. `;
  831. const Top = styled(Layout.Main)`
  832. flex-grow: 0;
  833. `;
  834. const TipContainer = styled('span')`
  835. > p {
  836. margin: 0;
  837. }
  838. `;
  839. type SavedQueryState = DeprecatedAsyncComponent['state'] & {
  840. savedQuery?: SavedQuery | null;
  841. };
  842. class SavedQueryAPI extends DeprecatedAsyncComponent<Props, SavedQueryState> {
  843. shouldReload = true;
  844. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  845. const {organization, location} = this.props;
  846. const endpoints: ReturnType<DeprecatedAsyncComponent['getEndpoints']> = [];
  847. if (location.query.id) {
  848. endpoints.push([
  849. 'savedQuery',
  850. `/organizations/${organization.slug}/discover/saved/${location.query.id}/`,
  851. ]);
  852. return endpoints;
  853. }
  854. return endpoints;
  855. }
  856. setSavedQuery = (newSavedQuery?: SavedQuery) => {
  857. this.setState({savedQuery: newSavedQuery});
  858. };
  859. renderBody(): React.ReactNode {
  860. const {organization} = this.props;
  861. const {savedQuery, loading} = this.state;
  862. let savedQueryWithDataset = savedQuery;
  863. if (hasDatasetSelector(organization) && savedQuery) {
  864. savedQueryWithDataset = getSavedQueryWithDataset(savedQuery) as SavedQuery;
  865. }
  866. return (
  867. <Results
  868. {...this.props}
  869. savedQuery={savedQueryWithDataset ?? undefined}
  870. loading={loading}
  871. setSavedQuery={this.setSavedQuery}
  872. />
  873. );
  874. }
  875. }
  876. function ResultsContainer(props: Props) {
  877. /**
  878. * Block `<Results>` from mounting until GSH is ready since there are API
  879. * requests being performed on mount.
  880. *
  881. * Also, we skip loading last used projects if you have multiple projects feature as
  882. * you no longer need to enforce a project if it is empty. We assume an empty project is
  883. * the desired behavior because saved queries can contain a project filter. The only
  884. * exception is if we are showing a prebuilt saved query in which case we want to
  885. * respect pinned filters.
  886. */
  887. return (
  888. <PageFiltersContainer
  889. disablePersistence={
  890. props.organization.features.includes('discover-query') &&
  891. !!(props.savedQuery || props.location.query.id)
  892. }
  893. skipLoadLastUsed={
  894. props.organization.features.includes('global-views') && !!props.savedQuery
  895. }
  896. // The Discover Results component will manage URL params, including page filters state
  897. // This avoids an unnecessary re-render when forcing a project filter for team plan users
  898. skipInitializeUrlParams
  899. >
  900. <SavedQueryAPI {...props} />
  901. </PageFiltersContainer>
  902. );
  903. }
  904. export default withApi(withOrganization(withPageFilters(ResultsContainer)));
  905. const StyledCloseButton = styled(Button)`
  906. background-color: transparent;
  907. transition: opacity 0.1s linear;
  908. &:hover,
  909. &:focus {
  910. background-color: transparent;
  911. opacity: 1;
  912. }
  913. `;