results.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. import {Component} from 'react';
  2. import {browserHistory, InjectedRouter} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import {Location} from 'history';
  6. import isEqual from 'lodash/isEqual';
  7. import omit from 'lodash/omit';
  8. import {updateSavedQueryVisit} from 'sentry/actionCreators/discoverSavedQueries';
  9. import {fetchTotalCount} from 'sentry/actionCreators/events';
  10. import {fetchProjectsCount} from 'sentry/actionCreators/projects';
  11. import {loadOrganizationTags} from 'sentry/actionCreators/tags';
  12. import {Client} from 'sentry/api';
  13. import Alert from 'sentry/components/alert';
  14. import AsyncComponent from 'sentry/components/asyncComponent';
  15. import Confirm from 'sentry/components/confirm';
  16. import DatePageFilter from 'sentry/components/datePageFilter';
  17. import EnvironmentPageFilter from 'sentry/components/environmentPageFilter';
  18. import SearchBar from 'sentry/components/events/searchBar';
  19. import * as Layout from 'sentry/components/layouts/thirds';
  20. import ExternalLink from 'sentry/components/links/externalLink';
  21. import NoProjectMessage from 'sentry/components/noProjectMessage';
  22. import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  23. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  24. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  25. import ProjectPageFilter from 'sentry/components/projectPageFilter';
  26. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  27. import {MAX_QUERY_LENGTH} from 'sentry/constants';
  28. import {t, tct} from 'sentry/locale';
  29. import {PageContent} from 'sentry/styles/organization';
  30. import space from 'sentry/styles/space';
  31. import {Organization, PageFilters, SavedQuery} from 'sentry/types';
  32. import {defined, generateQueryWithTag} from 'sentry/utils';
  33. import {trackAnalyticsEvent} from 'sentry/utils/analytics';
  34. import {CustomMeasurementsProvider} from 'sentry/utils/customMeasurements/customMeasurementsProvider';
  35. import EventView, {isAPIPayloadSimilar} from 'sentry/utils/discover/eventView';
  36. import {formatTagKey, generateAggregateFields} from 'sentry/utils/discover/fields';
  37. import {
  38. DisplayModes,
  39. MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES,
  40. } from 'sentry/utils/discover/types';
  41. import localStorage from 'sentry/utils/localStorage';
  42. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  43. import withApi from 'sentry/utils/withApi';
  44. import withOrganization from 'sentry/utils/withOrganization';
  45. import withPageFilters from 'sentry/utils/withPageFilters';
  46. import {addRoutePerformanceContext} from '../performance/utils';
  47. import {DEFAULT_EVENT_VIEW} from './data';
  48. import ResultsChart from './resultsChart';
  49. import ResultsHeader from './resultsHeader';
  50. import Table from './table';
  51. import Tags from './tags';
  52. import {generateTitle} from './utils';
  53. type Props = {
  54. api: Client;
  55. loading: boolean;
  56. location: Location;
  57. organization: Organization;
  58. router: InjectedRouter;
  59. selection: PageFilters;
  60. savedQuery?: SavedQuery;
  61. };
  62. type State = {
  63. confirmedQuery: boolean;
  64. error: string;
  65. errorCode: number;
  66. eventView: EventView;
  67. needConfirmation: boolean;
  68. showTags: boolean;
  69. totalValues: null | number;
  70. savedQuery?: SavedQuery;
  71. showMetricsAlert?: boolean;
  72. showUnparameterizedBanner?: boolean;
  73. };
  74. const SHOW_TAGS_STORAGE_KEY = 'discover2:show-tags';
  75. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  76. function readShowTagsState() {
  77. const value = localStorage.getItem(SHOW_TAGS_STORAGE_KEY);
  78. return value === '1';
  79. }
  80. function getYAxis(location: Location, eventView: EventView, savedQuery?: SavedQuery) {
  81. if (location.query.yAxis) {
  82. return decodeList(location.query.yAxis);
  83. }
  84. if (location.query.yAxis === null) {
  85. return [];
  86. }
  87. return savedQuery?.yAxis && savedQuery?.yAxis.length > 0
  88. ? decodeList(savedQuery?.yAxis)
  89. : [eventView.getYAxis()];
  90. }
  91. class Results extends Component<Props, State> {
  92. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State): State {
  93. if (nextProps.savedQuery || !nextProps.loading) {
  94. const eventView = EventView.fromSavedQueryOrLocation(
  95. nextProps.savedQuery,
  96. nextProps.location
  97. );
  98. return {...prevState, eventView, savedQuery: nextProps.savedQuery};
  99. }
  100. return prevState;
  101. }
  102. state: State = {
  103. eventView: EventView.fromSavedQueryOrLocation(
  104. this.props.savedQuery,
  105. this.props.location
  106. ),
  107. error: '',
  108. errorCode: 200,
  109. totalValues: null,
  110. showTags: readShowTagsState(),
  111. needConfirmation: false,
  112. confirmedQuery: false,
  113. };
  114. componentDidMount() {
  115. const {organization, selection, location} = this.props;
  116. if (location.query.fromMetric) {
  117. this.setState({showMetricsAlert: true});
  118. browserHistory.replace({
  119. ...location,
  120. query: {...location.query, fromMetric: undefined},
  121. });
  122. }
  123. if (location.query[SHOW_UNPARAM_BANNER]) {
  124. this.setState({showUnparameterizedBanner: true});
  125. browserHistory.replace({
  126. ...location,
  127. query: {...location.query, [SHOW_UNPARAM_BANNER]: undefined},
  128. });
  129. }
  130. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  131. addRoutePerformanceContext(selection);
  132. this.checkEventView();
  133. this.canLoadEvents();
  134. if (defined(location.query.id)) {
  135. updateSavedQueryVisit(organization.slug, location.query.id);
  136. }
  137. }
  138. componentDidUpdate(prevProps: Props, prevState: State) {
  139. const {api, location, organization, selection} = this.props;
  140. const {eventView, confirmedQuery, savedQuery} = this.state;
  141. this.checkEventView();
  142. const currentQuery = eventView.getEventsAPIPayload(location);
  143. const prevQuery = prevState.eventView.getEventsAPIPayload(prevProps.location);
  144. const yAxisArray = getYAxis(location, eventView, savedQuery);
  145. const prevYAxisArray = getYAxis(prevProps.location, eventView, prevState.savedQuery);
  146. if (
  147. !isAPIPayloadSimilar(currentQuery, prevQuery) ||
  148. this.hasChartParametersChanged(
  149. prevState.eventView,
  150. eventView,
  151. prevYAxisArray,
  152. yAxisArray
  153. )
  154. ) {
  155. api.clear();
  156. this.canLoadEvents();
  157. }
  158. if (
  159. !isEqual(prevProps.selection.datetime, selection.datetime) ||
  160. !isEqual(prevProps.selection.projects, selection.projects)
  161. ) {
  162. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  163. addRoutePerformanceContext(selection);
  164. }
  165. if (prevState.confirmedQuery !== confirmedQuery) {
  166. this.fetchTotalCount();
  167. }
  168. }
  169. tagsApi: Client = new Client();
  170. hasChartParametersChanged(
  171. prevEventView: EventView,
  172. eventView: EventView,
  173. prevYAxisArray: string[],
  174. yAxisArray: string[]
  175. ) {
  176. if (!isEqual(prevYAxisArray, yAxisArray)) {
  177. return true;
  178. }
  179. const prevDisplay = prevEventView.getDisplayMode();
  180. const display = eventView.getDisplayMode();
  181. return prevDisplay !== display;
  182. }
  183. canLoadEvents = async () => {
  184. const {api, location, organization} = this.props;
  185. const {eventView} = this.state;
  186. let needConfirmation = false;
  187. let confirmedQuery = true;
  188. const currentQuery = eventView.getEventsAPIPayload(location);
  189. const duration = eventView.getDays();
  190. if (duration > 30 && currentQuery.project) {
  191. let projectLength = currentQuery.project.length;
  192. if (
  193. projectLength === 0 ||
  194. (projectLength === 1 && currentQuery.project[0] === '-1')
  195. ) {
  196. try {
  197. const results = await fetchProjectsCount(api, organization.slug);
  198. if (projectLength === 0) {
  199. projectLength = results.myProjects;
  200. } else {
  201. projectLength = results.allProjects;
  202. }
  203. } catch (err) {
  204. // do nothing, so the length is 0 or 1 and the query is assumed safe
  205. }
  206. }
  207. if (projectLength > 10) {
  208. needConfirmation = true;
  209. confirmedQuery = false;
  210. }
  211. }
  212. // Once confirmed, a change of project or datetime will happen before this can set it to false,
  213. // this means a query will still happen even if the new conditions need confirmation
  214. // using a state callback to return this to false
  215. this.setState({needConfirmation, confirmedQuery}, () => {
  216. this.setState({confirmedQuery: false});
  217. });
  218. if (needConfirmation) {
  219. this.openConfirm();
  220. }
  221. };
  222. openConfirm = () => {};
  223. setOpenFunction = ({open}) => {
  224. this.openConfirm = open;
  225. return null;
  226. };
  227. handleConfirmed = () => {
  228. this.setState({needConfirmation: false, confirmedQuery: true}, () => {
  229. this.setState({confirmedQuery: false});
  230. });
  231. };
  232. handleCancelled = () => {
  233. this.setState({needConfirmation: false, confirmedQuery: false});
  234. };
  235. async fetchTotalCount() {
  236. const {api, organization, location} = this.props;
  237. const {eventView, confirmedQuery} = this.state;
  238. if (confirmedQuery === false || !eventView.isValid()) {
  239. return;
  240. }
  241. try {
  242. const totals = await fetchTotalCount(
  243. api,
  244. organization.slug,
  245. eventView.getEventsAPIPayload(location)
  246. );
  247. this.setState({totalValues: totals});
  248. } catch (err) {
  249. Sentry.captureException(err);
  250. }
  251. }
  252. checkEventView() {
  253. const {eventView} = this.state;
  254. const {loading} = this.props;
  255. if (eventView.isValid() || loading) {
  256. return;
  257. }
  258. // If the view is not valid, redirect to a known valid state.
  259. const {location, organization, selection} = this.props;
  260. const nextEventView = EventView.fromNewQueryWithLocation(
  261. DEFAULT_EVENT_VIEW,
  262. location
  263. );
  264. if (nextEventView.project.length === 0 && selection.projects) {
  265. nextEventView.project = selection.projects;
  266. }
  267. if (location.query?.query) {
  268. nextEventView.query = decodeScalar(location.query.query, '');
  269. }
  270. browserHistory.replace(nextEventView.getResultsViewUrlTarget(organization.slug));
  271. }
  272. handleChangeShowTags = () => {
  273. const {organization} = this.props;
  274. trackAnalyticsEvent({
  275. eventKey: 'discover_v2.results.toggle_tag_facets',
  276. eventName: 'Discoverv2: Toggle Tag Facets',
  277. organization_id: parseInt(organization.id, 10),
  278. });
  279. this.setState(state => {
  280. const newValue = !state.showTags;
  281. localStorage.setItem(SHOW_TAGS_STORAGE_KEY, newValue ? '1' : '0');
  282. return {...state, showTags: newValue};
  283. });
  284. };
  285. handleSearch = (query: string) => {
  286. const {router, location} = this.props;
  287. const queryParams = normalizeDateTimeParams({
  288. ...(location.query || {}),
  289. query,
  290. });
  291. // do not propagate pagination when making a new search
  292. const searchQueryParams = omit(queryParams, 'cursor');
  293. router.push({
  294. pathname: location.pathname,
  295. query: searchQueryParams,
  296. });
  297. };
  298. handleYAxisChange = (value: string[]) => {
  299. const {router, location} = this.props;
  300. const isDisplayMultiYAxisSupported = MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES.includes(
  301. location.query.display as DisplayModes
  302. );
  303. const newQuery = {
  304. ...location.query,
  305. yAxis: value.length > 0 ? value : [null],
  306. // If using Multi Y-axis and not in a supported display, change to the default display mode
  307. display:
  308. value.length > 1 && !isDisplayMultiYAxisSupported
  309. ? location.query.display === DisplayModes.DAILYTOP5
  310. ? DisplayModes.DAILY
  311. : DisplayModes.DEFAULT
  312. : location.query.display,
  313. };
  314. router.push({
  315. pathname: location.pathname,
  316. query: newQuery,
  317. });
  318. // Treat axis changing like the user already confirmed the query
  319. if (!this.state.needConfirmation) {
  320. this.handleConfirmed();
  321. }
  322. trackAnalyticsEvent({
  323. eventKey: 'discover_v2.y_axis_change',
  324. eventName: "Discoverv2: Change chart's y axis",
  325. organization_id: parseInt(this.props.organization.id, 10),
  326. y_axis_value: value,
  327. });
  328. };
  329. handleDisplayChange = (value: string) => {
  330. const {router, location} = this.props;
  331. const newQuery = {
  332. ...location.query,
  333. display: value,
  334. };
  335. router.push({
  336. pathname: location.pathname,
  337. query: newQuery,
  338. });
  339. // Treat display changing like the user already confirmed the query
  340. if (!this.state.needConfirmation) {
  341. this.handleConfirmed();
  342. }
  343. };
  344. handleTopEventsChange = (value: string) => {
  345. const {router, location} = this.props;
  346. const newQuery = {
  347. ...location.query,
  348. topEvents: value,
  349. };
  350. router.push({
  351. pathname: location.pathname,
  352. query: newQuery,
  353. });
  354. // Treat display changing like the user already confirmed the query
  355. if (!this.state.needConfirmation) {
  356. this.handleConfirmed();
  357. }
  358. };
  359. getDocumentTitle(): string {
  360. const {organization} = this.props;
  361. const {eventView} = this.state;
  362. if (!eventView) {
  363. return '';
  364. }
  365. return generateTitle({eventView, organization});
  366. }
  367. renderTagsTable() {
  368. const {organization, location} = this.props;
  369. const {eventView, totalValues, confirmedQuery} = this.state;
  370. return (
  371. <Layout.Side>
  372. <Tags
  373. generateUrl={this.generateTagUrl}
  374. totalValues={totalValues}
  375. eventView={eventView}
  376. organization={organization}
  377. location={location}
  378. confirmedQuery={confirmedQuery}
  379. />
  380. </Layout.Side>
  381. );
  382. }
  383. generateTagUrl = (key: string, value: string) => {
  384. const {organization} = this.props;
  385. const {eventView} = this.state;
  386. const url = eventView.getResultsViewUrlTarget(organization.slug);
  387. url.query = generateQueryWithTag(url.query, {
  388. key: formatTagKey(key),
  389. value,
  390. });
  391. return url;
  392. };
  393. renderError(error: string) {
  394. if (!error) {
  395. return null;
  396. }
  397. return (
  398. <Alert type="error" showIcon>
  399. {error}
  400. </Alert>
  401. );
  402. }
  403. setError = (error: string, errorCode: number) => {
  404. this.setState({error, errorCode});
  405. };
  406. renderMetricsFallbackBanner() {
  407. if (this.state.showMetricsAlert) {
  408. return (
  409. <Alert type="info" showIcon>
  410. {t(
  411. "You've navigated to this page from a performance metric widget generated from processed events. The results here only show indexed events."
  412. )}
  413. </Alert>
  414. );
  415. }
  416. if (this.state.showUnparameterizedBanner) {
  417. return (
  418. <Alert type="info" showIcon>
  419. {tct(
  420. 'These are unparameterized transactions. To better organize your transactions, [link:set transaction names manually].',
  421. {
  422. link: (
  423. <ExternalLink href="https://docs.sentry.io/platforms/javascript/guides/react/configuration/integrations/react-router/#parameterized-transaction-names" />
  424. ),
  425. }
  426. )}
  427. </Alert>
  428. );
  429. }
  430. return null;
  431. }
  432. render() {
  433. const {organization, location, router, selection} = this.props;
  434. const {
  435. eventView,
  436. error,
  437. errorCode,
  438. totalValues,
  439. showTags,
  440. confirmedQuery,
  441. savedQuery,
  442. } = this.state;
  443. const fields = eventView.hasAggregateField()
  444. ? generateAggregateFields(organization, eventView.fields)
  445. : eventView.fields;
  446. const query = eventView.query;
  447. const title = this.getDocumentTitle();
  448. const yAxisArray = getYAxis(location, eventView, savedQuery);
  449. return (
  450. <SentryDocumentTitle title={title} orgSlug={organization.slug}>
  451. <StyledPageContent>
  452. <NoProjectMessage organization={organization}>
  453. <ResultsHeader
  454. errorCode={errorCode}
  455. organization={organization}
  456. location={location}
  457. eventView={eventView}
  458. yAxis={yAxisArray}
  459. router={router}
  460. />
  461. <Layout.Body>
  462. <CustomMeasurementsProvider
  463. organization={organization}
  464. selection={selection}
  465. >
  466. <Top fullWidth>
  467. {this.renderMetricsFallbackBanner()}
  468. {this.renderError(error)}
  469. <StyledPageFilterBar condensed>
  470. <ProjectPageFilter />
  471. <EnvironmentPageFilter />
  472. <DatePageFilter alignDropdown="left" />
  473. </StyledPageFilterBar>
  474. <StyledSearchBar
  475. searchSource="eventsv2"
  476. organization={organization}
  477. projectIds={eventView.project}
  478. query={query}
  479. fields={fields}
  480. onSearch={this.handleSearch}
  481. maxQueryLength={MAX_QUERY_LENGTH}
  482. />
  483. <ResultsChart
  484. router={router}
  485. organization={organization}
  486. eventView={eventView}
  487. location={location}
  488. onAxisChange={this.handleYAxisChange}
  489. onDisplayChange={this.handleDisplayChange}
  490. onTopEventsChange={this.handleTopEventsChange}
  491. total={totalValues}
  492. confirmedQuery={confirmedQuery}
  493. yAxis={yAxisArray}
  494. />
  495. </Top>
  496. <Layout.Main fullWidth={!showTags}>
  497. <Table
  498. organization={organization}
  499. eventView={eventView}
  500. location={location}
  501. title={title}
  502. setError={this.setError}
  503. onChangeShowTags={this.handleChangeShowTags}
  504. showTags={showTags}
  505. confirmedQuery={confirmedQuery}
  506. />
  507. </Layout.Main>
  508. {showTags ? this.renderTagsTable() : null}
  509. <Confirm
  510. priority="primary"
  511. header={<strong>{t('May lead to thumb twiddling')}</strong>}
  512. confirmText={t('Do it')}
  513. cancelText={t('Nevermind')}
  514. onConfirm={this.handleConfirmed}
  515. onCancel={this.handleCancelled}
  516. message={
  517. <p>
  518. {tct(
  519. `You've created a query that will search for events made
  520. [dayLimit:over more than 30 days] for [projectLimit:more than 10 projects].
  521. A lot has happened during that time, so this might take awhile.
  522. Are you sure you want to do this?`,
  523. {
  524. dayLimit: <strong />,
  525. projectLimit: <strong />,
  526. }
  527. )}
  528. </p>
  529. }
  530. >
  531. {this.setOpenFunction}
  532. </Confirm>
  533. </CustomMeasurementsProvider>
  534. </Layout.Body>
  535. </NoProjectMessage>
  536. </StyledPageContent>
  537. </SentryDocumentTitle>
  538. );
  539. }
  540. }
  541. const StyledPageContent = styled(PageContent)`
  542. padding: 0;
  543. `;
  544. const StyledPageFilterBar = styled(PageFilterBar)`
  545. margin-bottom: ${space(1)};
  546. `;
  547. const StyledSearchBar = styled(SearchBar)`
  548. margin-bottom: ${space(2)};
  549. `;
  550. const Top = styled(Layout.Main)`
  551. flex-grow: 0;
  552. `;
  553. type SavedQueryState = AsyncComponent['state'] & {
  554. savedQuery?: SavedQuery | null;
  555. };
  556. class SavedQueryAPI extends AsyncComponent<Props, SavedQueryState> {
  557. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  558. const {organization, location} = this.props;
  559. if (location.query.id) {
  560. return [
  561. [
  562. 'savedQuery',
  563. `/organizations/${organization.slug}/discover/saved/${location.query.id}/`,
  564. ],
  565. ];
  566. }
  567. return [];
  568. }
  569. renderLoading() {
  570. return this.renderBody();
  571. }
  572. renderBody(): React.ReactNode {
  573. const {savedQuery, loading} = this.state;
  574. return (
  575. <Results {...this.props} savedQuery={savedQuery ?? undefined} loading={loading} />
  576. );
  577. }
  578. }
  579. function ResultsContainer(props: Props) {
  580. /**
  581. * Block `<Results>` from mounting until GSH is ready since there are API
  582. * requests being performed on mount.
  583. *
  584. * Also, we skip loading last used projects if you have multiple projects feature as
  585. * you no longer need to enforce a project if it is empty. We assume an empty project is
  586. * the desired behavior because saved queries can contain a project filter. The only
  587. * exception is if we are showing a prebuilt saved query in which case we want to
  588. * respect pinned filters.
  589. */
  590. return (
  591. <PageFiltersContainer
  592. skipLoadLastUsed={
  593. props.organization.features.includes('global-views') && !!props.savedQuery
  594. }
  595. >
  596. <SavedQueryAPI {...props} />
  597. </PageFiltersContainer>
  598. );
  599. }
  600. export default withApi(withOrganization(withPageFilters(ResultsContainer)));