groupDetails.tsx 20 KB

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