results.tsx 21 KB

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