groupDetails.tsx 17 KB

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