results.tsx 20 KB

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