results.tsx 19 KB

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