groupDetails.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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, Organization, Project} from 'sentry/types';
  17. import {EntrySpanTree, EntryType, 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. loadingReplaysCount: boolean;
  56. project: null | (Pick<Project, 'id' | 'slug'> & Partial<Pick<Project, 'platform'>>);
  57. replaysCount: number | null;
  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. this.fetchReplaysCount();
  75. this.updateReprocessingProgress();
  76. }
  77. componentDidUpdate(prevProps: Props, prevState: State) {
  78. const globalSelectionReadyChanged =
  79. prevProps.isGlobalSelectionReady !== this.props.isGlobalSelectionReady;
  80. if (
  81. globalSelectionReadyChanged ||
  82. prevProps.location.pathname !== this.props.location.pathname
  83. ) {
  84. // Skip tracking for other navigation events like switching events
  85. this.fetchData(globalSelectionReadyChanged);
  86. }
  87. if (
  88. (!this.canLoadEventEarly(prevProps) && !prevState?.group && this.state.group) ||
  89. (prevProps.params?.eventId !== this.props.params?.eventId && this.state.group)
  90. ) {
  91. this.getEvent(this.state.group);
  92. }
  93. }
  94. componentWillUnmount() {
  95. GroupStore.reset();
  96. callIfFunction(this.listener);
  97. if (this.refetchInterval) {
  98. window.clearInterval(this.refetchInterval);
  99. }
  100. }
  101. refetchInterval: number | null = null;
  102. get initialState(): State {
  103. return {
  104. group: null,
  105. loading: true,
  106. loadingEvent: true,
  107. loadingGroup: true,
  108. loadingReplaysCount: true,
  109. error: false,
  110. eventError: false,
  111. errorType: null,
  112. project: null,
  113. replaysCount: null,
  114. };
  115. }
  116. trackView(project: Project) {
  117. const {organization, params, location} = this.props;
  118. const {alert_date, alert_rule_id, alert_type} = location.query;
  119. trackAdvancedAnalyticsEvent('issue_details.viewed', {
  120. organization,
  121. project_id: parseInt(project.id, 10),
  122. group_id: parseInt(params.groupId, 10),
  123. // Alert properties track if the user came from email/slack alerts
  124. alert_date:
  125. typeof alert_date === 'string' ? getUtcDateString(Number(alert_date)) : undefined,
  126. alert_rule_id: typeof alert_rule_id === 'string' ? alert_rule_id : undefined,
  127. alert_type: typeof alert_type === 'string' ? alert_type : undefined,
  128. });
  129. }
  130. remountComponent = () => {
  131. this.setState(this.initialState);
  132. this.fetchData();
  133. };
  134. canLoadEventEarly(props: Props) {
  135. return !props.params.eventId || ['oldest', 'latest'].includes(props.params.eventId);
  136. }
  137. get groupDetailsEndpoint() {
  138. return `/issues/${this.props.params.groupId}/`;
  139. }
  140. get groupReleaseEndpoint() {
  141. return `/issues/${this.props.params.groupId}/first-last-release/`;
  142. }
  143. addPerformanceSpecificEntries(event: Event) {
  144. const performanceData = event.contexts.performance_issue;
  145. const spanTreeEntry: EntrySpanTree = {
  146. data: {
  147. focusedSpanIds: performanceData.spans,
  148. },
  149. type: EntryType.SPANTREE,
  150. };
  151. const performanceEntry = {
  152. data: {},
  153. type: EntryType.PERFORMANCE,
  154. };
  155. const updatedEvent = {
  156. ...event,
  157. entries: [performanceEntry, spanTreeEntry, ...event.entries],
  158. };
  159. return updatedEvent;
  160. }
  161. async getEvent(group?: Group) {
  162. if (group) {
  163. this.setState({loadingEvent: true, eventError: false});
  164. }
  165. const {params, environments, api, organization} = this.props;
  166. const orgSlug = params.orgId;
  167. const groupId = params.groupId;
  168. const eventId = params?.eventId || 'latest';
  169. const projectId = group?.project?.slug;
  170. try {
  171. let event = await fetchGroupEvent(
  172. api,
  173. orgSlug,
  174. groupId,
  175. eventId,
  176. environments,
  177. projectId
  178. );
  179. // add extra perf issue specific entries like span tree and duration and span count charts
  180. if (
  181. organization.features.includes('performance-extraneous-spans-poc') &&
  182. event.contexts.performance_issue
  183. ) {
  184. const updatedEvent = this.addPerformanceSpecificEntries(event);
  185. event = updatedEvent as Event;
  186. }
  187. this.setState({event, loading: false, eventError: false, loadingEvent: false});
  188. } catch (err) {
  189. // This is an expected error, capture to Sentry so that it is not considered as an unhandled error
  190. Sentry.captureException(err);
  191. this.setState({eventError: true, loading: false, loadingEvent: false});
  192. }
  193. }
  194. getCurrentRouteInfo(group: Group): {baseUrl: string; currentTab: Tab} {
  195. const {routes, organization} = this.props;
  196. const {event} = this.state;
  197. // All the routes under /organizations/:orgId/issues/:groupId have a defined props
  198. const {currentTab, isEventRoute} = routes[routes.length - 1].props as {
  199. currentTab: Tab;
  200. isEventRoute: boolean;
  201. };
  202. const baseUrl =
  203. isEventRoute && event
  204. ? `/organizations/${organization.slug}/issues/${group.id}/events/${event.id}/`
  205. : `/organizations/${organization.slug}/issues/${group.id}/`;
  206. return {currentTab, baseUrl};
  207. }
  208. updateReprocessingProgress() {
  209. const hasReprocessingV2Feature = this.hasReprocessingV2Feature();
  210. if (!hasReprocessingV2Feature) {
  211. return;
  212. }
  213. if (this.refetchInterval) {
  214. window.clearInterval(this.refetchInterval);
  215. }
  216. this.refetchInterval = window.setInterval(this.refetchGroup, 30000);
  217. }
  218. hasReprocessingV2Feature() {
  219. const {organization} = this.props;
  220. return organization.features?.includes('reprocessing-v2');
  221. }
  222. getReprocessingNewRoute(data: Group) {
  223. const {routes, location, params} = this.props;
  224. const {groupId} = params;
  225. const {id: nextGroupId} = data;
  226. const hasReprocessingV2Feature = this.hasReprocessingV2Feature();
  227. const reprocessingStatus = getGroupReprocessingStatus(data);
  228. const {currentTab, baseUrl} = this.getCurrentRouteInfo(data);
  229. if (groupId !== nextGroupId) {
  230. if (hasReprocessingV2Feature) {
  231. // Redirects to the Activities tab
  232. if (
  233. reprocessingStatus === ReprocessingStatus.REPROCESSED_AND_HASNT_EVENT &&
  234. currentTab !== Tab.ACTIVITY
  235. ) {
  236. return {
  237. pathname: `${baseUrl}${Tab.ACTIVITY}/`,
  238. query: {...params, groupId: nextGroupId},
  239. };
  240. }
  241. }
  242. return recreateRoute('', {
  243. routes,
  244. location,
  245. params: {...params, groupId: nextGroupId},
  246. });
  247. }
  248. if (hasReprocessingV2Feature) {
  249. if (
  250. reprocessingStatus === ReprocessingStatus.REPROCESSING &&
  251. currentTab !== Tab.DETAILS
  252. ) {
  253. return {
  254. pathname: baseUrl,
  255. query: params,
  256. };
  257. }
  258. if (
  259. reprocessingStatus === ReprocessingStatus.REPROCESSED_AND_HASNT_EVENT &&
  260. currentTab !== Tab.ACTIVITY &&
  261. currentTab !== Tab.USER_FEEDBACK
  262. ) {
  263. return {
  264. pathname: `${baseUrl}${Tab.ACTIVITY}/`,
  265. query: params,
  266. };
  267. }
  268. }
  269. return undefined;
  270. }
  271. getGroupQuery(): Record<string, string | string[]> {
  272. const {environments} = this.props;
  273. // Note, we do not want to include the environment key at all if there are no environments
  274. const query: Record<string, string | string[]> = {
  275. ...(environments ? {environment: environments} : {}),
  276. expand: 'inbox',
  277. collapse: 'release',
  278. };
  279. return query;
  280. }
  281. getFetchDataRequestErrorType(status: any): Error {
  282. if (!status) {
  283. return null;
  284. }
  285. if (status === 404) {
  286. return ERROR_TYPES.GROUP_NOT_FOUND;
  287. }
  288. if (status === 403) {
  289. return ERROR_TYPES.MISSING_MEMBERSHIP;
  290. }
  291. return null;
  292. }
  293. handleRequestError(error: any) {
  294. Sentry.captureException(error);
  295. const errorType = this.getFetchDataRequestErrorType(error?.status);
  296. this.setState({
  297. loadingGroup: false,
  298. loading: false,
  299. error: true,
  300. errorType,
  301. });
  302. }
  303. refetchGroup = async () => {
  304. const {loadingGroup, loading, loadingEvent, group} = this.state;
  305. if (
  306. group?.status !== ReprocessingStatus.REPROCESSING ||
  307. loadingGroup ||
  308. loading ||
  309. loadingEvent
  310. ) {
  311. return;
  312. }
  313. const {api} = this.props;
  314. this.setState({loadingGroup: true});
  315. try {
  316. const updatedGroup = await api.requestPromise(this.groupDetailsEndpoint, {
  317. query: this.getGroupQuery(),
  318. });
  319. const reprocessingNewRoute = this.getReprocessingNewRoute(updatedGroup);
  320. if (reprocessingNewRoute) {
  321. browserHistory.push(reprocessingNewRoute);
  322. return;
  323. }
  324. this.setState({group: updatedGroup, loadingGroup: false});
  325. } catch (error) {
  326. this.handleRequestError(error);
  327. }
  328. };
  329. async fetchGroupReleases() {
  330. const {api} = this.props;
  331. const releases = await api.requestPromise(this.groupReleaseEndpoint);
  332. GroupStore.onPopulateReleases(this.props.params.groupId, releases);
  333. }
  334. async fetchReplaysCount() {
  335. const {api, location, organization, params} = this.props;
  336. const {groupId} = params;
  337. this.setState({loadingReplaysCount: true});
  338. const eventView = EventView.fromSavedQuery({
  339. id: '',
  340. name: `Replays in issue ${groupId}`,
  341. version: 2,
  342. fields: ['count()'],
  343. query: `issue.id:${groupId}`,
  344. projects: [],
  345. });
  346. try {
  347. const [data] = await doDiscoverQuery<TableData>(
  348. api,
  349. `/organizations/${organization.slug}/events/`,
  350. eventView.getEventsAPIPayload(location)
  351. );
  352. const replaysCount = data.data[0]['count()'].toString();
  353. this.setState({
  354. replaysCount: parseInt(replaysCount, 10),
  355. loadingReplaysCount: false,
  356. });
  357. } catch (err) {
  358. this.setState({loadingReplaysCount: false});
  359. }
  360. }
  361. async fetchData(trackView = false) {
  362. const {api, isGlobalSelectionReady, params} = this.props;
  363. // Need to wait for global selection store to be ready before making request
  364. if (!isGlobalSelectionReady) {
  365. return;
  366. }
  367. try {
  368. const eventPromise = this.canLoadEventEarly(this.props)
  369. ? this.getEvent()
  370. : undefined;
  371. const groupPromise = await api.requestPromise(this.groupDetailsEndpoint, {
  372. query: this.getGroupQuery(),
  373. });
  374. const [data] = await Promise.all([groupPromise, eventPromise]);
  375. this.fetchGroupReleases();
  376. const reprocessingNewRoute = this.getReprocessingNewRoute(data);
  377. if (reprocessingNewRoute) {
  378. browserHistory.push(reprocessingNewRoute);
  379. return;
  380. }
  381. const project = data.project;
  382. markEventSeen(api, params.orgId, project.slug, params.groupId);
  383. if (!project) {
  384. Sentry.withScope(() => {
  385. Sentry.captureException(new Error('Project not found'));
  386. });
  387. } else {
  388. const locationWithProject = {...this.props.location};
  389. if (
  390. locationWithProject.query.project === undefined &&
  391. locationWithProject.query._allp === undefined
  392. ) {
  393. // We use _allp as a temporary measure to know they came from the
  394. // issue list page with no project selected (all projects included in
  395. // filter).
  396. //
  397. // If it is not defined, we add the locked project id to the URL
  398. // (this is because if someone navigates directly to an issue on
  399. // single-project priveleges, then goes back - they were getting
  400. // assigned to the first project).
  401. //
  402. // If it is defined, we do not so that our back button will bring us
  403. // to the issue list page with no project selected instead of the
  404. // locked project.
  405. locationWithProject.query = {...locationWithProject.query, project: project.id};
  406. }
  407. // We delete _allp from the URL to keep the hack a bit cleaner, but
  408. // this is not an ideal solution and will ultimately be replaced with
  409. // something smarter.
  410. delete locationWithProject.query._allp;
  411. browserHistory.replace(locationWithProject);
  412. }
  413. this.setState({project, loadingGroup: false});
  414. GroupStore.loadInitialData([data]);
  415. if (trackView) {
  416. this.trackView(project);
  417. }
  418. } catch (error) {
  419. this.handleRequestError(error);
  420. }
  421. }
  422. listener = GroupStore.listen(itemIds => this.onGroupChange(itemIds), undefined);
  423. onGroupChange(itemIds: Set<string>) {
  424. const id = this.props.params.groupId;
  425. if (itemIds.has(id)) {
  426. const group = GroupStore.get(id) as Group;
  427. if (group) {
  428. // TODO(ts) This needs a better approach. issueActions is splicing attributes onto
  429. // group objects to cheat here.
  430. if ((group as Group & {stale?: boolean}).stale) {
  431. this.fetchData();
  432. return;
  433. }
  434. this.setState({
  435. group,
  436. });
  437. }
  438. }
  439. }
  440. getTitle() {
  441. const {organization} = this.props;
  442. const {group} = this.state;
  443. const defaultTitle = 'Sentry';
  444. if (!group) {
  445. return defaultTitle;
  446. }
  447. const {title} = getTitle(group, organization?.features);
  448. const message = getMessage(group);
  449. const {project} = group;
  450. const eventDetails = `${organization.slug} - ${project.slug}`;
  451. if (title && message) {
  452. return `${title}: ${message} - ${eventDetails}`;
  453. }
  454. return `${title || message || defaultTitle} - ${eventDetails}`;
  455. }
  456. renderError() {
  457. const {projects, location} = this.props;
  458. const projectId = location.query.project;
  459. const project = projects.find(proj => proj.id === projectId);
  460. switch (this.state.errorType) {
  461. case ERROR_TYPES.GROUP_NOT_FOUND:
  462. return (
  463. <StyledLoadingError
  464. message={t('The issue you were looking for was not found.')}
  465. />
  466. );
  467. case ERROR_TYPES.MISSING_MEMBERSHIP:
  468. return (
  469. <MissingProjectMembership
  470. organization={this.props.organization}
  471. project={project}
  472. />
  473. );
  474. default:
  475. return <StyledLoadingError onRetry={this.remountComponent} />;
  476. }
  477. }
  478. renderContent(project: AvatarProject, group: Group) {
  479. const {children, environments, organization} = this.props;
  480. const {loadingEvent, eventError, event, replaysCount} = this.state;
  481. const {currentTab, baseUrl} = this.getCurrentRouteInfo(group);
  482. const groupReprocessingStatus = getGroupReprocessingStatus(group);
  483. let childProps: Record<string, any> = {
  484. environments,
  485. group,
  486. project,
  487. };
  488. if (currentTab === Tab.DETAILS) {
  489. if (group.id !== event?.groupID && !eventError) {
  490. // if user pastes only the event id into the url, but it's from another group, redirect to correct group/event
  491. const redirectUrl = `/organizations/${organization.slug}/issues/${event?.groupID}/events/${event?.id}/`;
  492. this.props.router.push(redirectUrl);
  493. } else {
  494. childProps = {
  495. ...childProps,
  496. event,
  497. loadingEvent,
  498. eventError,
  499. groupReprocessingStatus,
  500. onRetry: () => this.remountComponent(),
  501. };
  502. }
  503. }
  504. if (currentTab === Tab.TAGS) {
  505. childProps = {...childProps, event, baseUrl};
  506. }
  507. return (
  508. <Fragment>
  509. <GroupHeader
  510. groupReprocessingStatus={groupReprocessingStatus}
  511. project={project as Project}
  512. event={event}
  513. group={group}
  514. replaysCount={replaysCount}
  515. currentTab={currentTab}
  516. baseUrl={baseUrl}
  517. />
  518. {isValidElement(children) ? cloneElement(children, childProps) : children}
  519. </Fragment>
  520. );
  521. }
  522. renderPageContent() {
  523. const {error: isError, group, project, loading} = this.state;
  524. const isLoading = loading || (!group && !isError);
  525. if (isLoading) {
  526. return <LoadingIndicator />;
  527. }
  528. if (isError) {
  529. return this.renderError();
  530. }
  531. const {organization} = this.props;
  532. return (
  533. <Projects
  534. orgId={organization.slug}
  535. slugs={[project?.slug ?? '']}
  536. data-test-id="group-projects-container"
  537. >
  538. {({projects, initiallyLoaded, fetchError}) =>
  539. initiallyLoaded ? (
  540. fetchError ? (
  541. <StyledLoadingError message={t('Error loading the specified project')} />
  542. ) : (
  543. // TODO(ts): Update renderContent function to deal with empty group
  544. this.renderContent(projects[0], group!)
  545. )
  546. ) : (
  547. <LoadingIndicator />
  548. )
  549. }
  550. </Projects>
  551. );
  552. }
  553. render() {
  554. const {project, group} = this.state;
  555. const {organization} = this.props;
  556. const isSampleError = group?.tags.some(tag => tag.key === 'sample_event');
  557. return (
  558. <Fragment>
  559. {isSampleError && project && (
  560. <SampleEventAlert project={project} organization={organization} />
  561. )}
  562. <SentryDocumentTitle noSuffix title={this.getTitle()}>
  563. <PageFiltersContainer
  564. skipLoadLastUsed
  565. forceProject={project}
  566. shouldForceProject
  567. >
  568. {this.renderPageContent()}
  569. </PageFiltersContainer>
  570. </SentryDocumentTitle>
  571. </Fragment>
  572. );
  573. }
  574. }
  575. export default withApi(Sentry.withProfiler(GroupDetails));
  576. const StyledLoadingError = styled(LoadingError)`
  577. margin: ${space(2)};
  578. `;