groupDetails.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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 {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. // Will be updated by StacktraceLink if there is a stacktrace link
  152. stacktrace_link_viewed: false,
  153. });
  154. }
  155. remountComponent = () => {
  156. this.setState(this.initialState);
  157. this.fetchData();
  158. };
  159. canLoadEventEarly(props: Props) {
  160. return !props.params.eventId || ['oldest', 'latest'].includes(props.params.eventId);
  161. }
  162. get groupDetailsEndpoint() {
  163. return `/issues/${this.props.params.groupId}/`;
  164. }
  165. get groupReleaseEndpoint() {
  166. return `/issues/${this.props.params.groupId}/first-last-release/`;
  167. }
  168. async getEvent(group?: Group) {
  169. if (group) {
  170. this.setState({loadingEvent: true, eventError: false});
  171. }
  172. const {params, environments, api, organization} = this.props;
  173. const orgSlug = organization.slug;
  174. const groupId = params.groupId;
  175. const eventId = params.eventId ?? 'latest';
  176. const projectId = group?.project?.slug;
  177. try {
  178. const event = await fetchGroupEvent(
  179. api,
  180. orgSlug,
  181. groupId,
  182. eventId,
  183. environments,
  184. projectId
  185. );
  186. this.setState({event, loading: false, eventError: false, loadingEvent: false});
  187. } catch (err) {
  188. // This is an expected error, capture to Sentry so that it is not considered as an unhandled error
  189. Sentry.captureException(err);
  190. this.setState({eventError: true, loading: false, loadingEvent: false});
  191. }
  192. }
  193. getCurrentTab() {
  194. const {router, routes} = this.props;
  195. const currentRoute = routes[routes.length - 1];
  196. // If we're in the tag details page ("/tags/:tagKey/")
  197. if (router.params.tagKey) {
  198. return Tab.TAGS;
  199. }
  200. return (
  201. Object.values(Tab).find(tab => currentRoute.path === TabPaths[tab]) ?? Tab.DETAILS
  202. );
  203. }
  204. getCurrentRouteInfo(group: Group): {baseUrl: string; currentTab: Tab} {
  205. const {organization, params} = this.props;
  206. const {event} = this.state;
  207. const currentTab = this.getCurrentTab();
  208. const baseUrl = normalizeUrl(
  209. `/organizations/${organization.slug}/issues/${group.id}/${
  210. params.eventId && event ? `events/${event.id}/` : ''
  211. }`
  212. );
  213. return {baseUrl, currentTab};
  214. }
  215. updateReprocessingProgress() {
  216. const hasReprocessingV2Feature = this.hasReprocessingV2Feature();
  217. if (!hasReprocessingV2Feature) {
  218. return;
  219. }
  220. if (this.refetchInterval) {
  221. window.clearInterval(this.refetchInterval);
  222. }
  223. this.refetchInterval = window.setInterval(this.refetchGroup, 30000);
  224. }
  225. hasReprocessingV2Feature() {
  226. const {organization} = this.props;
  227. return organization.features?.includes('reprocessing-v2');
  228. }
  229. getReprocessingNewRoute(data: Group) {
  230. const {routes, location, params} = this.props;
  231. const {groupId} = params;
  232. const {id: nextGroupId} = data;
  233. const hasReprocessingV2Feature = this.hasReprocessingV2Feature();
  234. const reprocessingStatus = getGroupReprocessingStatus(data);
  235. const {currentTab, baseUrl} = this.getCurrentRouteInfo(data);
  236. if (groupId !== nextGroupId) {
  237. if (hasReprocessingV2Feature) {
  238. // Redirects to the Activities tab
  239. if (
  240. reprocessingStatus === ReprocessingStatus.REPROCESSED_AND_HASNT_EVENT &&
  241. currentTab !== Tab.ACTIVITY
  242. ) {
  243. return {
  244. pathname: `${baseUrl}${Tab.ACTIVITY}/`,
  245. query: {...params, groupId: nextGroupId},
  246. };
  247. }
  248. }
  249. return recreateRoute('', {
  250. routes,
  251. location,
  252. params: {...params, groupId: nextGroupId},
  253. });
  254. }
  255. if (hasReprocessingV2Feature) {
  256. if (
  257. reprocessingStatus === ReprocessingStatus.REPROCESSING &&
  258. currentTab !== Tab.DETAILS
  259. ) {
  260. return {
  261. pathname: baseUrl,
  262. query: params,
  263. };
  264. }
  265. if (
  266. reprocessingStatus === ReprocessingStatus.REPROCESSED_AND_HASNT_EVENT &&
  267. currentTab !== Tab.ACTIVITY &&
  268. currentTab !== Tab.USER_FEEDBACK
  269. ) {
  270. return {
  271. pathname: `${baseUrl}${Tab.ACTIVITY}/`,
  272. query: params,
  273. };
  274. }
  275. }
  276. return undefined;
  277. }
  278. getGroupQuery(): Record<string, string | string[]> {
  279. const {environments} = this.props;
  280. // Note, we do not want to include the environment key at all if there are no environments
  281. const query: Record<string, string | string[]> = {
  282. ...(environments ? {environment: environments} : {}),
  283. expand: ['inbox', 'owners'],
  284. collapse: 'release',
  285. };
  286. return query;
  287. }
  288. getFetchDataRequestErrorType(status: any): Error {
  289. if (!status) {
  290. return null;
  291. }
  292. if (status === 404) {
  293. return ERROR_TYPES.GROUP_NOT_FOUND;
  294. }
  295. if (status === 403) {
  296. return ERROR_TYPES.MISSING_MEMBERSHIP;
  297. }
  298. return null;
  299. }
  300. handleRequestError(error: any) {
  301. Sentry.captureException(error);
  302. const errorType = this.getFetchDataRequestErrorType(error?.status);
  303. this.setState({
  304. loadingGroup: false,
  305. loading: false,
  306. error: true,
  307. errorType,
  308. });
  309. }
  310. refetchGroup = async () => {
  311. const {loadingGroup, loading, loadingEvent, group} = this.state;
  312. if (
  313. group?.status !== ReprocessingStatus.REPROCESSING ||
  314. loadingGroup ||
  315. loading ||
  316. loadingEvent
  317. ) {
  318. return;
  319. }
  320. const {api} = this.props;
  321. this.setState({loadingGroup: true});
  322. try {
  323. const updatedGroup = await api.requestPromise(this.groupDetailsEndpoint, {
  324. query: this.getGroupQuery(),
  325. });
  326. const reprocessingNewRoute = this.getReprocessingNewRoute(updatedGroup);
  327. if (reprocessingNewRoute) {
  328. browserHistory.push(reprocessingNewRoute);
  329. return;
  330. }
  331. this.setState({group: updatedGroup, loadingGroup: false});
  332. } catch (error) {
  333. this.handleRequestError(error);
  334. }
  335. };
  336. async fetchGroupReleases() {
  337. const {api} = this.props;
  338. const releases = await api.requestPromise(this.groupReleaseEndpoint);
  339. GroupStore.onPopulateReleases(this.props.params.groupId, releases);
  340. }
  341. async fetchData(trackView = false) {
  342. const {api, isGlobalSelectionReady, organization, params} = this.props;
  343. // Need to wait for global selection store to be ready before making request
  344. if (!isGlobalSelectionReady) {
  345. return;
  346. }
  347. try {
  348. const eventPromise = this.canLoadEventEarly(this.props)
  349. ? this.getEvent()
  350. : undefined;
  351. const groupPromise = await api.requestPromise(this.groupDetailsEndpoint, {
  352. query: this.getGroupQuery(),
  353. });
  354. const [data] = await Promise.all([groupPromise, eventPromise]);
  355. const groupReleasePromise = this.fetchGroupReleases();
  356. const reprocessingNewRoute = this.getReprocessingNewRoute(data);
  357. if (reprocessingNewRoute) {
  358. browserHistory.push(reprocessingNewRoute);
  359. return;
  360. }
  361. const project = this.props.projects.find(p => p.id === data.project.id);
  362. if (!project) {
  363. Sentry.withScope(scope => {
  364. const projectIds = this.props.projects.map(item => item.id);
  365. scope.setContext('missingProject', {
  366. projectId: data.project.id,
  367. availableProjects: projectIds,
  368. });
  369. Sentry.captureException(new Error('Project not found'));
  370. });
  371. } else {
  372. markEventSeen(api, organization.slug, project.slug, params.groupId);
  373. const locationWithProject = {...this.props.location};
  374. if (
  375. locationWithProject.query.project === undefined &&
  376. locationWithProject.query._allp === undefined
  377. ) {
  378. // We use _allp as a temporary measure to know they came from the
  379. // issue list page with no project selected (all projects included in
  380. // filter).
  381. //
  382. // If it is not defined, we add the locked project id to the URL
  383. // (this is because if someone navigates directly to an issue on
  384. // single-project priveleges, then goes back - they were getting
  385. // assigned to the first project).
  386. //
  387. // If it is defined, we do not so that our back button will bring us
  388. // to the issue list page with no project selected instead of the
  389. // locked project.
  390. locationWithProject.query = {...locationWithProject.query, project: project.id};
  391. }
  392. // We delete _allp from the URL to keep the hack a bit cleaner, but
  393. // this is not an ideal solution and will ultimately be replaced with
  394. // something smarter.
  395. delete locationWithProject.query._allp;
  396. browserHistory.replace(locationWithProject);
  397. }
  398. this.setState({project: project || data.project, loadingGroup: false});
  399. GroupStore.loadInitialData([data]);
  400. if (trackView) {
  401. // make sure releases have loaded before we track the view
  402. groupReleasePromise.then(() => project && this.trackView(project));
  403. }
  404. } catch (error) {
  405. this.handleRequestError(error);
  406. }
  407. }
  408. listener = GroupStore.listen(itemIds => this.onGroupChange(itemIds), undefined);
  409. onGroupChange(itemIds: Set<string>) {
  410. const id = this.props.params.groupId;
  411. if (itemIds.has(id)) {
  412. const group = GroupStore.get(id) as Group;
  413. if (group) {
  414. // TODO(ts) This needs a better approach. issueActions is splicing attributes onto
  415. // group objects to cheat here.
  416. if ((group as Group & {stale?: boolean}).stale) {
  417. this.fetchData();
  418. return;
  419. }
  420. this.setState({
  421. group,
  422. });
  423. }
  424. }
  425. }
  426. getTitle() {
  427. const {organization} = this.props;
  428. const {group} = this.state;
  429. const defaultTitle = 'Sentry';
  430. if (!group) {
  431. return defaultTitle;
  432. }
  433. const {title} = getTitle(group, organization?.features);
  434. const message = getMessage(group);
  435. const {project} = group;
  436. const eventDetails = `${organization.slug} - ${project.slug}`;
  437. if (title && message) {
  438. return `${title}: ${message} - ${eventDetails}`;
  439. }
  440. return `${title || message || defaultTitle} - ${eventDetails}`;
  441. }
  442. tabClickAnalyticsEvent(tab: Tab) {
  443. const {organization} = this.props;
  444. const {project, group, event} = this.state;
  445. if (!project || !group) {
  446. return;
  447. }
  448. trackAdvancedAnalyticsEvent('issue_details.tab_changed', {
  449. organization,
  450. project_id: parseInt(project.id, 10),
  451. tab,
  452. ...getAnalyticsDataForGroup(group),
  453. });
  454. if (group.issueCategory !== IssueCategory.ERROR) {
  455. return;
  456. }
  457. const analyticsData = event
  458. ? event.tags
  459. .filter(({key}) => ['device', 'os', 'browser'].includes(key))
  460. .reduce((acc, {key, value}) => {
  461. acc[key] = value;
  462. return acc;
  463. }, {})
  464. : {};
  465. trackAdvancedAnalyticsEvent('issue_group_details.tab.clicked', {
  466. organization,
  467. tab,
  468. platform: project.platform,
  469. ...analyticsData,
  470. });
  471. }
  472. renderError() {
  473. const {projects, location} = this.props;
  474. const projectId = location.query.project;
  475. const project = projects.find(proj => proj.id === projectId);
  476. switch (this.state.errorType) {
  477. case ERROR_TYPES.GROUP_NOT_FOUND:
  478. return (
  479. <StyledLoadingError
  480. message={t('The issue you were looking for was not found.')}
  481. />
  482. );
  483. case ERROR_TYPES.MISSING_MEMBERSHIP:
  484. return (
  485. <MissingProjectMembership
  486. organization={this.props.organization}
  487. project={project}
  488. />
  489. );
  490. default:
  491. return <StyledLoadingError onRetry={this.remountComponent} />;
  492. }
  493. }
  494. renderContent(project: AvatarProject, group: Group) {
  495. const {children, environments, organization, router} = this.props;
  496. const {loadingEvent, eventError, event} = this.state;
  497. const {currentTab, baseUrl} = this.getCurrentRouteInfo(group);
  498. const groupReprocessingStatus = getGroupReprocessingStatus(group);
  499. let childProps: Record<string, any> = {
  500. environments,
  501. group,
  502. project,
  503. };
  504. if (currentTab === Tab.DETAILS) {
  505. if (group.id !== event?.groupID && !eventError) {
  506. // if user pastes only the event id into the url, but it's from another group, redirect to correct group/event
  507. const redirectUrl = `/organizations/${organization.slug}/issues/${event?.groupID}/events/${event?.id}/`;
  508. router.push(normalizeUrl(redirectUrl));
  509. } else {
  510. childProps = {
  511. ...childProps,
  512. event,
  513. loadingEvent,
  514. eventError,
  515. groupReprocessingStatus,
  516. onRetry: () => this.remountComponent(),
  517. };
  518. }
  519. }
  520. if (currentTab === Tab.TAGS) {
  521. childProps = {...childProps, event, baseUrl};
  522. }
  523. return (
  524. <Tabs value={currentTab} onChange={tab => this.tabClickAnalyticsEvent(tab)}>
  525. <GroupHeader
  526. organization={organization}
  527. groupReprocessingStatus={groupReprocessingStatus}
  528. event={event}
  529. group={group}
  530. baseUrl={baseUrl}
  531. project={project as Project}
  532. />
  533. <GroupTabPanels>
  534. <TabPanels.Item key={currentTab}>
  535. {isValidElement(children) ? cloneElement(children, childProps) : children}
  536. </TabPanels.Item>
  537. </GroupTabPanels>
  538. </Tabs>
  539. );
  540. }
  541. renderPageContent() {
  542. const {error: isError, group, project, loading} = this.state;
  543. const isLoading = loading || (!group && !isError);
  544. if (isLoading) {
  545. return <LoadingIndicator />;
  546. }
  547. if (isError) {
  548. return this.renderError();
  549. }
  550. const {organization} = this.props;
  551. return (
  552. <Projects
  553. orgId={organization.slug}
  554. slugs={[project?.slug ?? '']}
  555. data-test-id="group-projects-container"
  556. >
  557. {({projects, initiallyLoaded, fetchError}) =>
  558. initiallyLoaded ? (
  559. fetchError ? (
  560. <StyledLoadingError message={t('Error loading the specified project')} />
  561. ) : (
  562. // TODO(ts): Update renderContent function to deal with empty group
  563. this.renderContent(projects[0], group!)
  564. )
  565. ) : (
  566. <LoadingIndicator />
  567. )
  568. }
  569. </Projects>
  570. );
  571. }
  572. render() {
  573. const {project, group} = this.state;
  574. const {organization} = this.props;
  575. const isSampleError = group?.tags?.some(tag => tag.key === 'sample_event');
  576. return (
  577. <Fragment>
  578. {isSampleError && project && (
  579. <SampleEventAlert project={project} organization={organization} />
  580. )}
  581. <SentryDocumentTitle noSuffix title={this.getTitle()}>
  582. <PageFiltersContainer
  583. skipLoadLastUsed
  584. forceProject={project}
  585. shouldForceProject
  586. >
  587. {this.renderPageContent()}
  588. </PageFiltersContainer>
  589. </SentryDocumentTitle>
  590. </Fragment>
  591. );
  592. }
  593. }
  594. export default withRouteAnalytics(withApi(Sentry.withProfiler(GroupDetails)));
  595. const StyledLoadingError = styled(LoadingError)`
  596. margin: ${space(2)};
  597. `;
  598. const GroupTabPanels = styled(TabPanels)`
  599. flex-grow: 1;
  600. display: flex;
  601. flex-direction: column;
  602. justify-content: stretch;
  603. `;