groupDetails.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. import {cloneElement, Component, Fragment, isValidElement} from 'react';
  2. import {browserHistory, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import * as PropTypes from 'prop-types';
  6. import {Client} from 'sentry/api';
  7. import LoadingError from 'sentry/components/loadingError';
  8. import LoadingIndicator from 'sentry/components/loadingIndicator';
  9. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  10. import MissingProjectMembership from 'sentry/components/projects/missingProjectMembership';
  11. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  12. import {t} from 'sentry/locale';
  13. import SentryTypes from 'sentry/sentryTypes';
  14. import GroupStore from 'sentry/stores/groupStore';
  15. import space from 'sentry/styles/space';
  16. import {AvatarProject, Group, Organization, Project} from 'sentry/types';
  17. import {Event} from 'sentry/types/event';
  18. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  19. import {callIfFunction} from 'sentry/utils/callIfFunction';
  20. import {getUtcDateString} from 'sentry/utils/dates';
  21. import {TableData} from 'sentry/utils/discover/discoverQuery';
  22. import EventView from 'sentry/utils/discover/eventView';
  23. import {doDiscoverQuery} from 'sentry/utils/discover/genericDiscoverQuery';
  24. import {getMessage, getTitle} from 'sentry/utils/events';
  25. import Projects from 'sentry/utils/projects';
  26. import recreateRoute from 'sentry/utils/recreateRoute';
  27. import withApi from 'sentry/utils/withApi';
  28. import {ERROR_TYPES} from './constants';
  29. import GroupHeader from './header';
  30. import SampleEventAlert from './sampleEventAlert';
  31. import {Tab} from './types';
  32. import {
  33. fetchGroupEvent,
  34. getGroupReprocessingStatus,
  35. markEventSeen,
  36. ReprocessingStatus,
  37. } from './utils';
  38. type Error = typeof ERROR_TYPES[keyof typeof ERROR_TYPES] | null;
  39. type Props = {
  40. api: Client;
  41. children: React.ReactNode;
  42. environments: string[];
  43. isGlobalSelectionReady: boolean;
  44. organization: Organization;
  45. projects: Project[];
  46. } & RouteComponentProps<{groupId: string; orgId: string; eventId?: string}, {}>;
  47. type State = {
  48. error: boolean;
  49. errorType: Error;
  50. eventError: boolean;
  51. group: Group | null;
  52. loading: boolean;
  53. loadingEvent: boolean;
  54. loadingGroup: boolean;
  55. loadingReplaysCount: boolean;
  56. project: null | (Pick<Project, 'id' | 'slug'> & Partial<Pick<Project, 'platform'>>);
  57. replaysCount: number | null;
  58. event?: Event;
  59. };
  60. class GroupDetails extends Component<Props, State> {
  61. static childContextTypes = {
  62. group: SentryTypes.Group,
  63. location: PropTypes.object,
  64. };
  65. state = this.initialState;
  66. getChildContext() {
  67. return {
  68. group: this.state.group,
  69. location: this.props.location,
  70. };
  71. }
  72. componentDidMount() {
  73. this.fetchData(true);
  74. this.fetchReplaysCount();
  75. this.updateReprocessingProgress();
  76. }
  77. componentDidUpdate(prevProps: Props, prevState: State) {
  78. const globalSelectionReadyChanged =
  79. prevProps.isGlobalSelectionReady !== this.props.isGlobalSelectionReady;
  80. if (
  81. globalSelectionReadyChanged ||
  82. prevProps.location.pathname !== this.props.location.pathname
  83. ) {
  84. // Skip tracking for other navigation events like switching events
  85. this.fetchData(globalSelectionReadyChanged);
  86. }
  87. if (
  88. (!this.canLoadEventEarly(prevProps) && !prevState?.group && this.state.group) ||
  89. (prevProps.params?.eventId !== this.props.params?.eventId && this.state.group)
  90. ) {
  91. this.getEvent(this.state.group);
  92. }
  93. }
  94. componentWillUnmount() {
  95. GroupStore.reset();
  96. callIfFunction(this.listener);
  97. if (this.refetchInterval) {
  98. window.clearInterval(this.refetchInterval);
  99. }
  100. }
  101. refetchInterval: number | null = null;
  102. get initialState(): State {
  103. return {
  104. group: null,
  105. loading: true,
  106. loadingEvent: true,
  107. loadingGroup: true,
  108. loadingReplaysCount: true,
  109. error: false,
  110. eventError: false,
  111. errorType: null,
  112. project: null,
  113. replaysCount: null,
  114. };
  115. }
  116. trackView(project: Project) {
  117. const {organization, params, location} = this.props;
  118. const {alert_date, alert_rule_id, alert_type} = location.query;
  119. trackAdvancedAnalyticsEvent('issue_details.viewed', {
  120. organization,
  121. project_id: parseInt(project.id, 10),
  122. group_id: parseInt(params.groupId, 10),
  123. // Alert properties track if the user came from email/slack alerts
  124. alert_date:
  125. typeof alert_date === 'string' ? getUtcDateString(Number(alert_date)) : undefined,
  126. alert_rule_id: typeof alert_rule_id === 'string' ? alert_rule_id : undefined,
  127. alert_type: typeof alert_type === 'string' ? alert_type : undefined,
  128. });
  129. }
  130. remountComponent = () => {
  131. this.setState(this.initialState);
  132. this.fetchData();
  133. };
  134. canLoadEventEarly(props: Props) {
  135. return !props.params.eventId || ['oldest', 'latest'].includes(props.params.eventId);
  136. }
  137. get groupDetailsEndpoint() {
  138. return `/issues/${this.props.params.groupId}/`;
  139. }
  140. get groupReleaseEndpoint() {
  141. return `/issues/${this.props.params.groupId}/first-last-release/`;
  142. }
  143. async getEvent(group?: Group) {
  144. if (group) {
  145. this.setState({loadingEvent: true, eventError: false});
  146. }
  147. const {params, environments, api} = this.props;
  148. const orgSlug = params.orgId;
  149. const groupId = params.groupId;
  150. const eventId = params?.eventId || 'latest';
  151. const projectId = group?.project?.slug;
  152. try {
  153. const event = await fetchGroupEvent(
  154. api,
  155. orgSlug,
  156. groupId,
  157. eventId,
  158. environments,
  159. projectId
  160. );
  161. this.setState({event, loading: false, eventError: false, loadingEvent: false});
  162. } catch (err) {
  163. // This is an expected error, capture to Sentry so that it is not considered as an unhandled error
  164. Sentry.captureException(err);
  165. this.setState({eventError: true, loading: false, loadingEvent: false});
  166. }
  167. }
  168. getCurrentRouteInfo(group: Group): {baseUrl: string; currentTab: Tab} {
  169. const {routes, organization} = this.props;
  170. const {event} = this.state;
  171. // All the routes under /organizations/:orgId/issues/:groupId have a defined props
  172. const {currentTab, isEventRoute} = routes[routes.length - 1].props as {
  173. currentTab: Tab;
  174. isEventRoute: boolean;
  175. };
  176. const baseUrl =
  177. isEventRoute && event
  178. ? `/organizations/${organization.slug}/issues/${group.id}/events/${event.id}/`
  179. : `/organizations/${organization.slug}/issues/${group.id}/`;
  180. return {currentTab, baseUrl};
  181. }
  182. updateReprocessingProgress() {
  183. const hasReprocessingV2Feature = this.hasReprocessingV2Feature();
  184. if (!hasReprocessingV2Feature) {
  185. return;
  186. }
  187. if (this.refetchInterval) {
  188. window.clearInterval(this.refetchInterval);
  189. }
  190. this.refetchInterval = window.setInterval(this.refetchGroup, 30000);
  191. }
  192. hasReprocessingV2Feature() {
  193. const {organization} = this.props;
  194. return organization.features?.includes('reprocessing-v2');
  195. }
  196. getReprocessingNewRoute(data: Group) {
  197. const {routes, location, params} = this.props;
  198. const {groupId} = params;
  199. const {id: nextGroupId} = data;
  200. const hasReprocessingV2Feature = this.hasReprocessingV2Feature();
  201. const reprocessingStatus = getGroupReprocessingStatus(data);
  202. const {currentTab, baseUrl} = this.getCurrentRouteInfo(data);
  203. if (groupId !== nextGroupId) {
  204. if (hasReprocessingV2Feature) {
  205. // Redirects to the Activities tab
  206. if (
  207. reprocessingStatus === ReprocessingStatus.REPROCESSED_AND_HASNT_EVENT &&
  208. currentTab !== Tab.ACTIVITY
  209. ) {
  210. return {
  211. pathname: `${baseUrl}${Tab.ACTIVITY}/`,
  212. query: {...params, groupId: nextGroupId},
  213. };
  214. }
  215. }
  216. return recreateRoute('', {
  217. routes,
  218. location,
  219. params: {...params, groupId: nextGroupId},
  220. });
  221. }
  222. if (hasReprocessingV2Feature) {
  223. if (
  224. reprocessingStatus === ReprocessingStatus.REPROCESSING &&
  225. currentTab !== Tab.DETAILS
  226. ) {
  227. return {
  228. pathname: baseUrl,
  229. query: params,
  230. };
  231. }
  232. if (
  233. reprocessingStatus === ReprocessingStatus.REPROCESSED_AND_HASNT_EVENT &&
  234. currentTab !== Tab.ACTIVITY &&
  235. currentTab !== Tab.USER_FEEDBACK
  236. ) {
  237. return {
  238. pathname: `${baseUrl}${Tab.ACTIVITY}/`,
  239. query: params,
  240. };
  241. }
  242. }
  243. return undefined;
  244. }
  245. getGroupQuery(): Record<string, string | string[]> {
  246. const {environments} = this.props;
  247. // Note, we do not want to include the environment key at all if there are no environments
  248. const query: Record<string, string | string[]> = {
  249. ...(environments ? {environment: environments} : {}),
  250. expand: 'inbox',
  251. collapse: 'release',
  252. };
  253. return query;
  254. }
  255. getFetchDataRequestErrorType(status: any): Error {
  256. if (!status) {
  257. return null;
  258. }
  259. if (status === 404) {
  260. return ERROR_TYPES.GROUP_NOT_FOUND;
  261. }
  262. if (status === 403) {
  263. return ERROR_TYPES.MISSING_MEMBERSHIP;
  264. }
  265. return null;
  266. }
  267. handleRequestError(error: any) {
  268. Sentry.captureException(error);
  269. const errorType = this.getFetchDataRequestErrorType(error?.status);
  270. this.setState({
  271. loadingGroup: false,
  272. loading: false,
  273. error: true,
  274. errorType,
  275. });
  276. }
  277. refetchGroup = async () => {
  278. const {loadingGroup, loading, loadingEvent, group} = this.state;
  279. if (
  280. group?.status !== ReprocessingStatus.REPROCESSING ||
  281. loadingGroup ||
  282. loading ||
  283. loadingEvent
  284. ) {
  285. return;
  286. }
  287. const {api} = this.props;
  288. this.setState({loadingGroup: true});
  289. try {
  290. const updatedGroup = await api.requestPromise(this.groupDetailsEndpoint, {
  291. query: this.getGroupQuery(),
  292. });
  293. const reprocessingNewRoute = this.getReprocessingNewRoute(updatedGroup);
  294. if (reprocessingNewRoute) {
  295. browserHistory.push(reprocessingNewRoute);
  296. return;
  297. }
  298. this.setState({group: updatedGroup, loadingGroup: false});
  299. } catch (error) {
  300. this.handleRequestError(error);
  301. }
  302. };
  303. async fetchGroupReleases() {
  304. const {api} = this.props;
  305. const releases = await api.requestPromise(this.groupReleaseEndpoint);
  306. GroupStore.onPopulateReleases(this.props.params.groupId, releases);
  307. }
  308. async fetchReplaysCount() {
  309. const {api, location, organization, params} = this.props;
  310. const {groupId} = params;
  311. this.setState({loadingReplaysCount: true});
  312. const eventView = EventView.fromSavedQuery({
  313. id: '',
  314. name: `Replays in issue ${groupId}`,
  315. version: 2,
  316. fields: ['count()'],
  317. query: `issue.id:${groupId}`,
  318. projects: [],
  319. });
  320. try {
  321. const [data] = await doDiscoverQuery<TableData>(
  322. api,
  323. `/organizations/${organization.slug}/events/`,
  324. eventView.getEventsAPIPayload(location)
  325. );
  326. const replaysCount = data.data[0]['count()'].toString();
  327. this.setState({
  328. replaysCount: parseInt(replaysCount, 10),
  329. loadingReplaysCount: false,
  330. });
  331. } catch (err) {
  332. this.setState({loadingReplaysCount: false});
  333. }
  334. }
  335. async fetchData(trackView = false) {
  336. const {api, isGlobalSelectionReady, params} = this.props;
  337. // Need to wait for global selection store to be ready before making request
  338. if (!isGlobalSelectionReady) {
  339. return;
  340. }
  341. try {
  342. const eventPromise = this.canLoadEventEarly(this.props)
  343. ? this.getEvent()
  344. : undefined;
  345. const groupPromise = await api.requestPromise(this.groupDetailsEndpoint, {
  346. query: this.getGroupQuery(),
  347. });
  348. const [data] = await Promise.all([groupPromise, eventPromise]);
  349. this.fetchGroupReleases();
  350. const reprocessingNewRoute = this.getReprocessingNewRoute(data);
  351. if (reprocessingNewRoute) {
  352. browserHistory.push(reprocessingNewRoute);
  353. return;
  354. }
  355. const project = data.project;
  356. markEventSeen(api, params.orgId, project.slug, params.groupId);
  357. if (!project) {
  358. Sentry.withScope(() => {
  359. Sentry.captureException(new Error('Project not found'));
  360. });
  361. } else {
  362. const locationWithProject = {...this.props.location};
  363. if (
  364. locationWithProject.query.project === undefined &&
  365. locationWithProject.query._allp === undefined
  366. ) {
  367. // We use _allp as a temporary measure to know they came from the
  368. // issue list page with no project selected (all projects included in
  369. // filter).
  370. //
  371. // If it is not defined, we add the locked project id to the URL
  372. // (this is because if someone navigates directly to an issue on
  373. // single-project priveleges, then goes back - they were getting
  374. // assigned to the first project).
  375. //
  376. // If it is defined, we do not so that our back button will bring us
  377. // to the issue list page with no project selected instead of the
  378. // locked project.
  379. locationWithProject.query = {...locationWithProject.query, project: project.id};
  380. }
  381. // We delete _allp from the URL to keep the hack a bit cleaner, but
  382. // this is not an ideal solution and will ultimately be replaced with
  383. // something smarter.
  384. delete locationWithProject.query._allp;
  385. browserHistory.replace(locationWithProject);
  386. }
  387. this.setState({project, loadingGroup: false});
  388. GroupStore.loadInitialData([data]);
  389. if (trackView) {
  390. this.trackView(project);
  391. }
  392. } catch (error) {
  393. this.handleRequestError(error);
  394. }
  395. }
  396. listener = GroupStore.listen(itemIds => this.onGroupChange(itemIds), undefined);
  397. onGroupChange(itemIds: Set<string>) {
  398. const id = this.props.params.groupId;
  399. if (itemIds.has(id)) {
  400. const group = GroupStore.get(id) as Group;
  401. if (group) {
  402. // TODO(ts) This needs a better approach. issueActions is splicing attributes onto
  403. // group objects to cheat here.
  404. if ((group as Group & {stale?: boolean}).stale) {
  405. this.fetchData();
  406. return;
  407. }
  408. this.setState({
  409. group,
  410. });
  411. }
  412. }
  413. }
  414. getTitle() {
  415. const {organization} = this.props;
  416. const {group} = this.state;
  417. const defaultTitle = 'Sentry';
  418. if (!group) {
  419. return defaultTitle;
  420. }
  421. const {title} = getTitle(group, organization?.features);
  422. const message = getMessage(group);
  423. const {project} = group;
  424. const eventDetails = `${organization.slug} - ${project.slug}`;
  425. if (title && message) {
  426. return `${title}: ${message} - ${eventDetails}`;
  427. }
  428. return `${title || message || defaultTitle} - ${eventDetails}`;
  429. }
  430. renderError() {
  431. const {projects, location} = this.props;
  432. const projectId = location.query.project;
  433. const project = projects.find(proj => proj.id === projectId);
  434. switch (this.state.errorType) {
  435. case ERROR_TYPES.GROUP_NOT_FOUND:
  436. return (
  437. <StyledLoadingError
  438. message={t('The issue you were looking for was not found.')}
  439. />
  440. );
  441. case ERROR_TYPES.MISSING_MEMBERSHIP:
  442. return (
  443. <MissingProjectMembership
  444. organization={this.props.organization}
  445. project={project}
  446. />
  447. );
  448. default:
  449. return <StyledLoadingError onRetry={this.remountComponent} />;
  450. }
  451. }
  452. renderContent(project: AvatarProject, group: Group) {
  453. const {children, environments, organization} = this.props;
  454. const {loadingEvent, eventError, event, replaysCount} = this.state;
  455. const {currentTab, baseUrl} = this.getCurrentRouteInfo(group);
  456. const groupReprocessingStatus = getGroupReprocessingStatus(group);
  457. let childProps: Record<string, any> = {
  458. environments,
  459. group,
  460. project,
  461. };
  462. if (currentTab === Tab.DETAILS) {
  463. if (group.id !== event?.groupID && !eventError) {
  464. // if user pastes only the event id into the url, but it's from another group, redirect to correct group/event
  465. const redirectUrl = `/organizations/${organization.slug}/issues/${event?.groupID}/events/${event?.id}/`;
  466. this.props.router.push(redirectUrl);
  467. } else {
  468. childProps = {
  469. ...childProps,
  470. event,
  471. loadingEvent,
  472. eventError,
  473. groupReprocessingStatus,
  474. onRetry: () => this.remountComponent(),
  475. };
  476. }
  477. }
  478. if (currentTab === Tab.TAGS) {
  479. childProps = {...childProps, event, baseUrl};
  480. }
  481. return (
  482. <Fragment>
  483. <GroupHeader
  484. groupReprocessingStatus={groupReprocessingStatus}
  485. project={project as Project}
  486. event={event}
  487. group={group}
  488. replaysCount={replaysCount}
  489. currentTab={currentTab}
  490. baseUrl={baseUrl}
  491. />
  492. {isValidElement(children) ? cloneElement(children, childProps) : children}
  493. </Fragment>
  494. );
  495. }
  496. renderPageContent() {
  497. const {error: isError, group, project, loading} = this.state;
  498. const isLoading = loading || (!group && !isError);
  499. if (isLoading) {
  500. return <LoadingIndicator />;
  501. }
  502. if (isError) {
  503. return this.renderError();
  504. }
  505. const {organization} = this.props;
  506. return (
  507. <Projects
  508. orgId={organization.slug}
  509. slugs={[project?.slug ?? '']}
  510. data-test-id="group-projects-container"
  511. >
  512. {({projects, initiallyLoaded, fetchError}) =>
  513. initiallyLoaded ? (
  514. fetchError ? (
  515. <StyledLoadingError message={t('Error loading the specified project')} />
  516. ) : (
  517. // TODO(ts): Update renderContent function to deal with empty group
  518. this.renderContent(projects[0], group!)
  519. )
  520. ) : (
  521. <LoadingIndicator />
  522. )
  523. }
  524. </Projects>
  525. );
  526. }
  527. render() {
  528. const {project, group} = this.state;
  529. const {organization} = this.props;
  530. const isSampleError = group?.tags.some(tag => tag.key === 'sample_event');
  531. return (
  532. <Fragment>
  533. {isSampleError && project && (
  534. <SampleEventAlert project={project} organization={organization} />
  535. )}
  536. <SentryDocumentTitle noSuffix title={this.getTitle()}>
  537. <PageFiltersContainer
  538. skipLoadLastUsed
  539. forceProject={project}
  540. shouldForceProject
  541. >
  542. {this.renderPageContent()}
  543. </PageFiltersContainer>
  544. </SentryDocumentTitle>
  545. </Fragment>
  546. );
  547. }
  548. }
  549. export default withApi(Sentry.withProfiler(GroupDetails));
  550. const StyledLoadingError = styled(LoadingError)`
  551. margin: ${space(2)};
  552. `;