results.tsx 20 KB

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