results.tsx 20 KB

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