results.tsx 19 KB

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