groupDetails.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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, IssueCategory, 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. loadingReplayIds: boolean;
  56. project: null | (Pick<Project, 'id' | 'slug'> & Partial<Pick<Project, 'platform'>>);
  57. replayIds: null | string[];
  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. if (this.props.organization.features.includes('session-replay-ui')) {
  75. this.fetchReplayIds();
  76. }
  77. this.updateReprocessingProgress();
  78. }
  79. componentDidUpdate(prevProps: Props, prevState: State) {
  80. const globalSelectionReadyChanged =
  81. prevProps.isGlobalSelectionReady !== this.props.isGlobalSelectionReady;
  82. if (
  83. globalSelectionReadyChanged ||
  84. prevProps.location.pathname !== this.props.location.pathname
  85. ) {
  86. // Skip tracking for other navigation events like switching events
  87. this.fetchData(globalSelectionReadyChanged);
  88. }
  89. if (
  90. (!this.canLoadEventEarly(prevProps) && !prevState?.group && this.state.group) ||
  91. (prevProps.params?.eventId !== this.props.params?.eventId && this.state.group)
  92. ) {
  93. this.getEvent(this.state.group);
  94. }
  95. }
  96. componentWillUnmount() {
  97. GroupStore.reset();
  98. callIfFunction(this.listener);
  99. if (this.refetchInterval) {
  100. window.clearInterval(this.refetchInterval);
  101. }
  102. }
  103. refetchInterval: number | null = null;
  104. get initialState(): State {
  105. return {
  106. group: null,
  107. loading: true,
  108. loadingReplayIds: true,
  109. loadingEvent: true,
  110. loadingGroup: true,
  111. error: false,
  112. eventError: false,
  113. errorType: null,
  114. project: null,
  115. replayIds: null,
  116. };
  117. }
  118. trackView(project: Project) {
  119. const {organization, params, location} = this.props;
  120. const {alert_date, alert_rule_id, alert_type} = location.query;
  121. trackAdvancedAnalyticsEvent('issue_details.viewed', {
  122. organization,
  123. project_id: parseInt(project.id, 10),
  124. group_id: parseInt(params.groupId, 10),
  125. issue_category: this.state.group?.issueCategory ?? IssueCategory.ERROR,
  126. // Alert properties track if the user came from email/slack alerts
  127. alert_date:
  128. typeof alert_date === 'string' ? getUtcDateString(Number(alert_date)) : undefined,
  129. alert_rule_id: typeof alert_rule_id === 'string' ? alert_rule_id : undefined,
  130. alert_type: typeof alert_type === 'string' ? alert_type : undefined,
  131. });
  132. }
  133. remountComponent = () => {
  134. this.setState(this.initialState);
  135. this.fetchData();
  136. };
  137. canLoadEventEarly(props: Props) {
  138. return !props.params.eventId || ['oldest', 'latest'].includes(props.params.eventId);
  139. }
  140. get groupDetailsEndpoint() {
  141. return `/issues/${this.props.params.groupId}/`;
  142. }
  143. get groupReleaseEndpoint() {
  144. return `/issues/${this.props.params.groupId}/first-last-release/`;
  145. }
  146. async getEvent(group?: Group) {
  147. if (group) {
  148. this.setState({loadingEvent: true, eventError: false});
  149. }
  150. const {params, environments, api} = this.props;
  151. const orgSlug = params.orgId;
  152. const groupId = params.groupId;
  153. const eventId = params?.eventId || 'latest';
  154. const projectId = group?.project?.slug;
  155. try {
  156. const event = await fetchGroupEvent(
  157. api,
  158. orgSlug,
  159. groupId,
  160. eventId,
  161. environments,
  162. projectId
  163. );
  164. this.setState({event, loading: false, eventError: false, loadingEvent: false});
  165. } catch (err) {
  166. // This is an expected error, capture to Sentry so that it is not considered as an unhandled error
  167. Sentry.captureException(err);
  168. this.setState({eventError: true, loading: false, loadingEvent: false});
  169. }
  170. }
  171. getCurrentRouteInfo(group: Group): {baseUrl: string; currentTab: Tab} {
  172. const {routes, organization} = this.props;
  173. const {event} = this.state;
  174. // All the routes under /organizations/:orgId/issues/:groupId have a defined props
  175. const {currentTab, isEventRoute} = routes[routes.length - 1].props as {
  176. currentTab: Tab;
  177. isEventRoute: boolean;
  178. };
  179. const baseUrl =
  180. isEventRoute && event
  181. ? `/organizations/${organization.slug}/issues/${group.id}/events/${event.id}/`
  182. : `/organizations/${organization.slug}/issues/${group.id}/`;
  183. return {currentTab, baseUrl};
  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',
  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 fetchReplayIds() {
  312. const {api, location, organization, params} = this.props;
  313. const {groupId} = params;
  314. this.setState({loadingReplayIds: true});
  315. const eventView = EventView.fromNewQueryWithLocation(
  316. {
  317. id: '',
  318. name: `Errors within replay`,
  319. version: 2,
  320. fields: ['replayId', 'count()'],
  321. query: `issue.id:${groupId} !replayId:""`,
  322. projects: [],
  323. },
  324. location
  325. );
  326. try {
  327. const [data] = await doDiscoverQuery<TableData>(
  328. api,
  329. `/organizations/${organization.slug}/events/`,
  330. eventView.getEventsAPIPayload(location)
  331. );
  332. const replayIds = data.data.map(record => String(record.replayId));
  333. this.setState({
  334. replayIds,
  335. loadingReplayIds: false,
  336. });
  337. } catch (err) {
  338. this.setState({loadingReplayIds: false});
  339. }
  340. }
  341. async fetchData(trackView = false) {
  342. const {api, isGlobalSelectionReady, 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. this.fetchGroupReleases();
  356. const reprocessingNewRoute = this.getReprocessingNewRoute(data);
  357. if (reprocessingNewRoute) {
  358. browserHistory.push(reprocessingNewRoute);
  359. return;
  360. }
  361. const project = data.project;
  362. markEventSeen(api, params.orgId, project.slug, params.groupId);
  363. if (!project) {
  364. Sentry.withScope(() => {
  365. Sentry.captureException(new Error('Project not found'));
  366. });
  367. } else {
  368. const locationWithProject = {...this.props.location};
  369. if (
  370. locationWithProject.query.project === undefined &&
  371. locationWithProject.query._allp === undefined
  372. ) {
  373. // We use _allp as a temporary measure to know they came from the
  374. // issue list page with no project selected (all projects included in
  375. // filter).
  376. //
  377. // If it is not defined, we add the locked project id to the URL
  378. // (this is because if someone navigates directly to an issue on
  379. // single-project priveleges, then goes back - they were getting
  380. // assigned to the first project).
  381. //
  382. // If it is defined, we do not so that our back button will bring us
  383. // to the issue list page with no project selected instead of the
  384. // locked project.
  385. locationWithProject.query = {...locationWithProject.query, project: project.id};
  386. }
  387. // We delete _allp from the URL to keep the hack a bit cleaner, but
  388. // this is not an ideal solution and will ultimately be replaced with
  389. // something smarter.
  390. delete locationWithProject.query._allp;
  391. browserHistory.replace(locationWithProject);
  392. }
  393. this.setState({project, loadingGroup: false});
  394. GroupStore.loadInitialData([data]);
  395. if (trackView) {
  396. this.trackView(project);
  397. }
  398. } catch (error) {
  399. this.handleRequestError(error);
  400. }
  401. }
  402. listener = GroupStore.listen(itemIds => this.onGroupChange(itemIds), undefined);
  403. onGroupChange(itemIds: Set<string>) {
  404. const id = this.props.params.groupId;
  405. if (itemIds.has(id)) {
  406. const group = GroupStore.get(id) as Group;
  407. if (group) {
  408. // TODO(ts) This needs a better approach. issueActions is splicing attributes onto
  409. // group objects to cheat here.
  410. if ((group as Group & {stale?: boolean}).stale) {
  411. this.fetchData();
  412. return;
  413. }
  414. this.setState({
  415. group,
  416. });
  417. }
  418. }
  419. }
  420. getTitle() {
  421. const {organization} = this.props;
  422. const {group} = this.state;
  423. const defaultTitle = 'Sentry';
  424. if (!group) {
  425. return defaultTitle;
  426. }
  427. const {title} = getTitle(group, organization?.features);
  428. const message = getMessage(group);
  429. const {project} = group;
  430. const eventDetails = `${organization.slug} - ${project.slug}`;
  431. if (title && message) {
  432. return `${title}: ${message} - ${eventDetails}`;
  433. }
  434. return `${title || message || defaultTitle} - ${eventDetails}`;
  435. }
  436. renderError() {
  437. const {projects, location} = this.props;
  438. const projectId = location.query.project;
  439. const project = projects.find(proj => proj.id === projectId);
  440. switch (this.state.errorType) {
  441. case ERROR_TYPES.GROUP_NOT_FOUND:
  442. return (
  443. <StyledLoadingError
  444. message={t('The issue you were looking for was not found.')}
  445. />
  446. );
  447. case ERROR_TYPES.MISSING_MEMBERSHIP:
  448. return (
  449. <MissingProjectMembership
  450. organization={this.props.organization}
  451. project={project}
  452. />
  453. );
  454. default:
  455. return <StyledLoadingError onRetry={this.remountComponent} />;
  456. }
  457. }
  458. renderContent(project: AvatarProject, group: Group) {
  459. const {children, environments, organization} = this.props;
  460. const {loadingEvent, eventError, event, replayIds} = this.state;
  461. const {currentTab, baseUrl} = this.getCurrentRouteInfo(group);
  462. const groupReprocessingStatus = getGroupReprocessingStatus(group);
  463. let childProps: Record<string, any> = {
  464. environments,
  465. group,
  466. project,
  467. };
  468. if (currentTab === Tab.DETAILS) {
  469. if (group.id !== event?.groupID && !eventError) {
  470. // if user pastes only the event id into the url, but it's from another group, redirect to correct group/event
  471. const redirectUrl = `/organizations/${organization.slug}/issues/${event?.groupID}/events/${event?.id}/`;
  472. this.props.router.push(redirectUrl);
  473. } else {
  474. childProps = {
  475. ...childProps,
  476. event,
  477. loadingEvent,
  478. eventError,
  479. groupReprocessingStatus,
  480. onRetry: () => this.remountComponent(),
  481. };
  482. }
  483. }
  484. if (currentTab === Tab.TAGS) {
  485. childProps = {...childProps, event, baseUrl};
  486. } else if (currentTab === Tab.REPLAYS) {
  487. childProps = {...childProps, replayIds};
  488. }
  489. return (
  490. <Fragment>
  491. <GroupHeader
  492. groupReprocessingStatus={groupReprocessingStatus}
  493. project={project as Project}
  494. event={event}
  495. group={group}
  496. replaysCount={replayIds?.length}
  497. currentTab={currentTab}
  498. baseUrl={baseUrl}
  499. />
  500. {isValidElement(children) ? cloneElement(children, childProps) : children}
  501. </Fragment>
  502. );
  503. }
  504. renderPageContent() {
  505. const {error: isError, group, project, loading} = this.state;
  506. const isLoading = loading || (!group && !isError);
  507. if (isLoading) {
  508. return <LoadingIndicator />;
  509. }
  510. if (isError) {
  511. return this.renderError();
  512. }
  513. const {organization} = this.props;
  514. return (
  515. <Projects
  516. orgId={organization.slug}
  517. slugs={[project?.slug ?? '']}
  518. data-test-id="group-projects-container"
  519. >
  520. {({projects, initiallyLoaded, fetchError}) =>
  521. initiallyLoaded ? (
  522. fetchError ? (
  523. <StyledLoadingError message={t('Error loading the specified project')} />
  524. ) : (
  525. // TODO(ts): Update renderContent function to deal with empty group
  526. this.renderContent(projects[0], group!)
  527. )
  528. ) : (
  529. <LoadingIndicator />
  530. )
  531. }
  532. </Projects>
  533. );
  534. }
  535. render() {
  536. const {project, group} = this.state;
  537. const {organization} = this.props;
  538. const isSampleError = group?.tags?.some(tag => tag.key === 'sample_event');
  539. return (
  540. <Fragment>
  541. {isSampleError && project && (
  542. <SampleEventAlert project={project} organization={organization} />
  543. )}
  544. <SentryDocumentTitle noSuffix title={this.getTitle()}>
  545. <PageFiltersContainer
  546. skipLoadLastUsed
  547. forceProject={project}
  548. shouldForceProject
  549. >
  550. {this.renderPageContent()}
  551. </PageFiltersContainer>
  552. </SentryDocumentTitle>
  553. </Fragment>
  554. );
  555. }
  556. }
  557. export default withApi(Sentry.withProfiler(GroupDetails));
  558. const StyledLoadingError = styled(LoadingError)`
  559. margin: ${space(2)};
  560. `;