groupDetails.tsx 20 KB

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