eventEntries.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. import {Fragment, useCallback, useEffect, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import {Location} from 'history';
  5. import uniq from 'lodash/uniq';
  6. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  7. import {Client} from 'sentry/api';
  8. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  9. import ErrorBoundary from 'sentry/components/errorBoundary';
  10. import EventContexts from 'sentry/components/events/contexts';
  11. import EventContextSummary from 'sentry/components/events/contextSummary';
  12. import EventDevice from 'sentry/components/events/device';
  13. import EventErrors, {Error} from 'sentry/components/events/errors';
  14. import EventAttachments from 'sentry/components/events/eventAttachments';
  15. import EventCause from 'sentry/components/events/eventCause';
  16. import EventDataSection from 'sentry/components/events/eventDataSection';
  17. import EventExtraData from 'sentry/components/events/eventExtraData';
  18. import {EventSdk} from 'sentry/components/events/eventSdk';
  19. import {EventTags} from 'sentry/components/events/eventTags';
  20. import EventGroupingInfo from 'sentry/components/events/groupingInfo';
  21. import {EventPackageData} from 'sentry/components/events/packageData';
  22. import RRWebIntegration from 'sentry/components/events/rrwebIntegration';
  23. import EventSdkUpdates from 'sentry/components/events/sdkUpdates';
  24. import {DataSection} from 'sentry/components/events/styles';
  25. import EventUserFeedback from 'sentry/components/events/userFeedback';
  26. import ExternalLink from 'sentry/components/links/externalLink';
  27. import {t, tct} from 'sentry/locale';
  28. import space from 'sentry/styles/space';
  29. import {
  30. Entry,
  31. EntryType,
  32. Event,
  33. ExceptionValue,
  34. Group,
  35. IssueAttachment,
  36. IssueCategory,
  37. Organization,
  38. Project,
  39. SharedViewOrganization,
  40. Thread,
  41. } from 'sentry/types';
  42. import {DebugFile} from 'sentry/types/debugFiles';
  43. import {Image} from 'sentry/types/debugImage';
  44. import {isNotSharedOrganization} from 'sentry/types/utils';
  45. import {defined, objectIsEmpty} from 'sentry/utils';
  46. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  47. import withApi from 'sentry/utils/withApi';
  48. import withOrganization from 'sentry/utils/withOrganization';
  49. import {projectProcessingIssuesMessages} from 'sentry/views/settings/project/projectProcessingIssues';
  50. import {CommitRow} from '../commitRow';
  51. import findBestThread from './interfaces/threads/threadSelector/findBestThread';
  52. import getThreadException from './interfaces/threads/threadSelector/getThreadException';
  53. import EventEntry from './eventEntry';
  54. import EventTagsAndScreenshot from './eventTagsAndScreenshot';
  55. const MINIFIED_DATA_JAVA_EVENT_REGEX_MATCH =
  56. /^(([\w\$]\.[\w\$]{1,2})|([\w\$]{2}\.[\w\$]\.[\w\$]))(\.|$)/g;
  57. function isDataMinified(str: string | null) {
  58. if (!str) {
  59. return false;
  60. }
  61. return !![...str.matchAll(MINIFIED_DATA_JAVA_EVENT_REGEX_MATCH)].length;
  62. }
  63. function hasThreadOrExceptionMinifiedFrameData(definedEvent: Event, bestThread?: Thread) {
  64. if (!bestThread) {
  65. const exceptionValues: Array<ExceptionValue> =
  66. definedEvent.entries?.find(e => e.type === EntryType.EXCEPTION)?.data?.values ?? [];
  67. return !!exceptionValues.find(exceptionValue =>
  68. exceptionValue.stacktrace?.frames?.find(frame => isDataMinified(frame.module))
  69. );
  70. }
  71. const threadExceptionValues = getThreadException(definedEvent, bestThread)?.values;
  72. return !!(threadExceptionValues
  73. ? threadExceptionValues.find(threadExceptionValue =>
  74. threadExceptionValue.stacktrace?.frames?.find(frame =>
  75. isDataMinified(frame.module)
  76. )
  77. )
  78. : bestThread?.stacktrace?.frames?.find(frame => isDataMinified(frame.module)));
  79. }
  80. type ProGuardErrors = Array<Error>;
  81. type Props = Pick<React.ComponentProps<typeof EventEntry>, 'route' | 'router'> & {
  82. api: Client;
  83. location: Location;
  84. /**
  85. * The organization can be the shared view on a public issue view.
  86. */
  87. organization: Organization | SharedViewOrganization;
  88. project: Project;
  89. className?: string;
  90. event?: Event;
  91. group?: Group;
  92. isShare?: boolean;
  93. showTagSummary?: boolean;
  94. };
  95. const EventEntries = ({
  96. organization,
  97. project,
  98. location,
  99. api,
  100. event,
  101. group,
  102. className,
  103. router,
  104. route,
  105. isShare = false,
  106. showTagSummary = true,
  107. }: Props) => {
  108. const [isLoading, setIsLoading] = useState(true);
  109. const [proGuardErrors, setProGuardErrors] = useState<ProGuardErrors>([]);
  110. const [attachments, setAttachments] = useState<IssueAttachment[]>([]);
  111. const orgSlug = organization.slug;
  112. const projectSlug = project.slug;
  113. const orgFeatures = organization?.features ?? [];
  114. const hasEventAttachmentsFeature = orgFeatures.includes('event-attachments');
  115. const hasReplay = Boolean(event?.tags?.find(({key}) => key === 'replayId')?.value);
  116. const recordIssueError = useCallback(() => {
  117. if (!event || !event.errors || !(event.errors.length > 0)) {
  118. return;
  119. }
  120. const errors = event.errors;
  121. const errorTypes = errors.map(errorEntries => errorEntries.type);
  122. const errorMessages = errors.map(errorEntries => errorEntries.message);
  123. const platform = project.platform;
  124. // uniquify the array types
  125. trackAdvancedAnalyticsEvent('issue_error_banner.viewed', {
  126. organization: organization as Organization,
  127. group: event?.groupID,
  128. error_type: uniq(errorTypes),
  129. error_message: uniq(errorMessages),
  130. ...(platform && {platform}),
  131. });
  132. }, [event, organization, project.platform]);
  133. const fetchProguardMappingFiles = useCallback(
  134. async (query: string): Promise<Array<DebugFile>> => {
  135. try {
  136. const proguardMappingFiles = await api.requestPromise(
  137. `/projects/${orgSlug}/${projectSlug}/files/dsyms/`,
  138. {
  139. method: 'GET',
  140. query: {
  141. query,
  142. file_formats: 'proguard',
  143. },
  144. }
  145. );
  146. return proguardMappingFiles;
  147. } catch (error) {
  148. Sentry.captureException(error);
  149. // do nothing, the UI will not display extra error details
  150. return [];
  151. }
  152. },
  153. [api, orgSlug, projectSlug]
  154. );
  155. const checkProGuardError = useCallback(async () => {
  156. if (!event || event.platform !== 'java') {
  157. setIsLoading(false);
  158. return;
  159. }
  160. const hasEventErrorsProGuardMissingMapping = event.errors?.find(
  161. error => error.type === 'proguard_missing_mapping'
  162. );
  163. if (hasEventErrorsProGuardMissingMapping) {
  164. setIsLoading(false);
  165. return;
  166. }
  167. const newProGuardErrors: ProGuardErrors = [];
  168. const debugImages = event.entries?.find(e => e.type === EntryType.DEBUGMETA)?.data
  169. .images as undefined | Array<Image>;
  170. // When debugImages contains a 'proguard' entry, it must always be only one entry
  171. const proGuardImage = debugImages?.find(
  172. debugImage => debugImage?.type === 'proguard'
  173. );
  174. const proGuardImageUuid = proGuardImage?.uuid;
  175. // If an entry is of type 'proguard' and has 'uuid',
  176. // it means that the Sentry Gradle plugin has been executed,
  177. // otherwise the proguard id wouldn't be in the event.
  178. // But maybe it failed to upload the mappings file
  179. if (defined(proGuardImageUuid)) {
  180. if (isShare) {
  181. setIsLoading(false);
  182. return;
  183. }
  184. const proguardMappingFiles = await fetchProguardMappingFiles(proGuardImageUuid);
  185. if (!proguardMappingFiles.length) {
  186. newProGuardErrors.push({
  187. type: 'proguard_missing_mapping',
  188. message: projectProcessingIssuesMessages.proguard_missing_mapping,
  189. data: {mapping_uuid: proGuardImageUuid},
  190. });
  191. }
  192. setProGuardErrors(newProGuardErrors);
  193. setIsLoading(false);
  194. return;
  195. }
  196. if (proGuardImage) {
  197. Sentry.withScope(function (s) {
  198. s.setLevel('warning');
  199. if (event.sdk) {
  200. s.setTag('offending.event.sdk.name', event.sdk.name);
  201. s.setTag('offending.event.sdk.version', event.sdk.version);
  202. }
  203. Sentry.captureMessage('Event contains proguard image but not uuid');
  204. });
  205. }
  206. const threads: Array<Thread> =
  207. event.entries?.find(e => e.type === EntryType.THREADS)?.data?.values ?? [];
  208. const bestThread = findBestThread(threads);
  209. const hasThreadOrExceptionMinifiedData = hasThreadOrExceptionMinifiedFrameData(
  210. event,
  211. bestThread
  212. );
  213. if (hasThreadOrExceptionMinifiedData) {
  214. newProGuardErrors.push({
  215. type: 'proguard_potentially_misconfigured_plugin',
  216. message: tct(
  217. 'Some frames appear to be minified. Did you configure the [plugin]?',
  218. {
  219. plugin: (
  220. <ExternalLink href="https://docs.sentry.io/platforms/android/proguard/#gradle">
  221. Sentry Gradle Plugin
  222. </ExternalLink>
  223. ),
  224. }
  225. ),
  226. });
  227. }
  228. setProGuardErrors(newProGuardErrors);
  229. setIsLoading(false);
  230. }, [event, fetchProguardMappingFiles, isShare]);
  231. const fetchAttachments = useCallback(async () => {
  232. if (!event || isShare || !hasEventAttachmentsFeature) {
  233. return;
  234. }
  235. try {
  236. const response = await api.requestPromise(
  237. `/projects/${orgSlug}/${projectSlug}/events/${event.id}/attachments/`
  238. );
  239. setAttachments(response);
  240. } catch (error) {
  241. Sentry.captureException(error);
  242. addErrorMessage('An error occurred while fetching attachments');
  243. }
  244. }, [api, event, hasEventAttachmentsFeature, isShare, orgSlug, projectSlug]);
  245. const handleDeleteAttachment = useCallback(
  246. async (attachmentId: IssueAttachment['id']) => {
  247. if (!event) {
  248. return;
  249. }
  250. try {
  251. await api.requestPromise(
  252. `/projects/${orgSlug}/${projectSlug}/events/${event.id}/attachments/${attachmentId}/`,
  253. {
  254. method: 'DELETE',
  255. }
  256. );
  257. setAttachments(attachments.filter(attachment => attachment.id !== attachmentId));
  258. } catch (error) {
  259. Sentry.captureException(error);
  260. addErrorMessage('An error occurred while deleting the attachment');
  261. }
  262. },
  263. [api, attachments, event, orgSlug, projectSlug]
  264. );
  265. useEffect(() => {
  266. checkProGuardError();
  267. }, [checkProGuardError]);
  268. useEffect(() => {
  269. recordIssueError();
  270. }, [recordIssueError]);
  271. useEffect(() => {
  272. fetchAttachments();
  273. }, [fetchAttachments]);
  274. if (!event) {
  275. return (
  276. <LatestEventNotAvailable>
  277. <h3>{t('Latest Event Not Available')}</h3>
  278. </LatestEventNotAvailable>
  279. );
  280. }
  281. const hasMobileScreenshotsFeature = orgFeatures.includes('mobile-screenshots');
  282. const hasContext = !objectIsEmpty(event.user ?? {}) || !objectIsEmpty(event.contexts);
  283. const hasErrors = !objectIsEmpty(event.errors) || !!proGuardErrors.length;
  284. return (
  285. <div className={className} data-test-id={`event-entries-loading-${isLoading}`}>
  286. {hasErrors && !isLoading && (
  287. <EventErrors
  288. event={event}
  289. orgSlug={orgSlug}
  290. projectSlug={projectSlug}
  291. proGuardErrors={proGuardErrors}
  292. />
  293. )}
  294. {!isShare && isNotSharedOrganization(organization) && (
  295. <EventCause
  296. project={project}
  297. eventId={event.id}
  298. group={group}
  299. commitRow={CommitRow}
  300. />
  301. )}
  302. {event.userReport && group && (
  303. <StyledEventUserFeedback
  304. report={event.userReport}
  305. orgId={orgSlug}
  306. issueId={group.id}
  307. includeBorder={!hasErrors}
  308. />
  309. )}
  310. {showTagSummary &&
  311. (hasMobileScreenshotsFeature ? (
  312. <EventTagsAndScreenshot
  313. event={event}
  314. organization={organization as Organization}
  315. projectId={projectSlug}
  316. location={location}
  317. isShare={isShare}
  318. hasContext={hasContext}
  319. attachments={attachments}
  320. onDeleteScreenshot={handleDeleteAttachment}
  321. />
  322. ) : (
  323. (!!(event.tags ?? []).length || hasContext) && (
  324. <StyledEventDataSection
  325. title={<GuideAnchor target="tags">{t('Tags')}</GuideAnchor>}
  326. type="tags"
  327. >
  328. {hasContext && <EventContextSummary event={event} />}
  329. <EventTags
  330. event={event}
  331. organization={organization as Organization}
  332. projectId={projectSlug}
  333. location={location}
  334. />
  335. </StyledEventDataSection>
  336. )
  337. ))}
  338. <Entries
  339. definedEvent={event}
  340. projectSlug={projectSlug}
  341. group={group}
  342. organization={organization}
  343. route={route}
  344. router={router}
  345. isShare={isShare}
  346. />
  347. {hasContext && <EventContexts group={group} event={event} />}
  348. {event && !objectIsEmpty(event.context) && <EventExtraData event={event} />}
  349. {event && !objectIsEmpty(event.packages) && <EventPackageData event={event} />}
  350. {event && !objectIsEmpty(event.device) && <EventDevice event={event} />}
  351. {!isShare && hasEventAttachmentsFeature && (
  352. <EventAttachments
  353. event={event}
  354. orgId={orgSlug}
  355. projectId={projectSlug}
  356. location={location}
  357. attachments={attachments}
  358. onDeleteAttachment={handleDeleteAttachment}
  359. />
  360. )}
  361. {event.sdk && !objectIsEmpty(event.sdk) && (
  362. <EventSdk sdk={event.sdk} meta={event._meta?.sdk} />
  363. )}
  364. {!isShare && event?.sdkUpdates && event.sdkUpdates.length > 0 && (
  365. <EventSdkUpdates event={{sdkUpdates: event.sdkUpdates, ...event}} />
  366. )}
  367. {!isShare && event.groupID && (
  368. <EventGroupingInfo
  369. projectId={projectSlug}
  370. event={event}
  371. showGroupingConfig={
  372. orgFeatures.includes('set-grouping-config') && 'groupingConfig' in event
  373. }
  374. />
  375. )}
  376. {!isShare && !hasReplay && hasEventAttachmentsFeature && (
  377. <RRWebIntegration
  378. event={event}
  379. orgId={orgSlug}
  380. projectId={projectSlug}
  381. renderer={children => (
  382. <StyledReplayEventDataSection type="context-replay" title={t('Replay')}>
  383. {children}
  384. </StyledReplayEventDataSection>
  385. )}
  386. />
  387. )}
  388. </div>
  389. );
  390. };
  391. function injectResourcesEntry(definedEvent: Event) {
  392. const entries = definedEvent.entries;
  393. let adjustedEntries: Entry[] = [];
  394. // This check is to ensure we are not injecting multiple Resources entries
  395. const resourcesIndex = entries.findIndex(entry => entry.type === EntryType.RESOURCES);
  396. if (resourcesIndex === -1) {
  397. const spansIndex = entries.findIndex(entry => entry.type === EntryType.SPANS);
  398. const breadcrumbsIndex = entries.findIndex(
  399. entry => entry.type === EntryType.BREADCRUMBS
  400. );
  401. // We want the Resources section to appear after Breadcrumbs.
  402. // If Breadcrumbs are included on this event, we will inject this entry right after it.
  403. // Otherwise, we inject it after the Spans entry.
  404. const resourcesEntry: Entry = {type: EntryType.RESOURCES, data: null};
  405. if (breadcrumbsIndex > -1) {
  406. adjustedEntries = [
  407. ...entries.slice(0, breadcrumbsIndex + 1),
  408. resourcesEntry,
  409. ...entries.slice(breadcrumbsIndex + 1, entries.length),
  410. ];
  411. } else if (spansIndex > -1) {
  412. adjustedEntries = [
  413. ...entries.slice(0, spansIndex + 1),
  414. resourcesEntry,
  415. ...entries.slice(spansIndex + 1, entries.length),
  416. ];
  417. }
  418. }
  419. if (adjustedEntries.length > 0) {
  420. definedEvent.entries = adjustedEntries;
  421. }
  422. }
  423. function Entries({
  424. definedEvent,
  425. projectSlug,
  426. isShare,
  427. group,
  428. organization,
  429. route,
  430. router,
  431. }: {
  432. definedEvent: Event;
  433. projectSlug: string;
  434. isShare?: boolean;
  435. } & Pick<Props, 'group' | 'organization' | 'route' | 'router'>) {
  436. if (!Array.isArray(definedEvent.entries)) {
  437. return null;
  438. }
  439. if (
  440. group?.issueCategory === IssueCategory.PERFORMANCE &&
  441. organization.features?.includes('performance-issues')
  442. ) {
  443. injectResourcesEntry(definedEvent);
  444. }
  445. return (
  446. <Fragment>
  447. {(definedEvent.entries as Array<Entry>).map((entry, entryIdx) => (
  448. <ErrorBoundary
  449. key={`entry-${entryIdx}`}
  450. customComponent={
  451. <EventDataSection type={entry.type} title={entry.type}>
  452. <p>{t('There was an error rendering this data.')}</p>
  453. </EventDataSection>
  454. }
  455. >
  456. <EventEntry
  457. projectSlug={projectSlug}
  458. group={group}
  459. organization={organization}
  460. event={definedEvent}
  461. entry={entry}
  462. route={route}
  463. router={router}
  464. isShare={isShare}
  465. />
  466. </ErrorBoundary>
  467. ))}
  468. </Fragment>
  469. );
  470. }
  471. const StyledEventDataSection = styled(EventDataSection)`
  472. /* Hiding the top border because of the event section appears at this breakpoint */
  473. @media (max-width: 767px) {
  474. &:first-of-type {
  475. border-top: none;
  476. }
  477. }
  478. `;
  479. const LatestEventNotAvailable = styled('div')`
  480. padding: ${space(2)} ${space(4)};
  481. `;
  482. const BorderlessEventEntries = styled(EventEntries)`
  483. & ${DataSection} {
  484. margin-left: 0 !important;
  485. margin-right: 0 !important;
  486. padding: ${space(3)} 0 0 0;
  487. }
  488. & ${DataSection}:first-child {
  489. padding-top: 0;
  490. border-top: 0;
  491. }
  492. `;
  493. type StyledEventUserFeedbackProps = {
  494. includeBorder: boolean;
  495. };
  496. const StyledEventUserFeedback = styled(EventUserFeedback)<StyledEventUserFeedbackProps>`
  497. border-radius: 0;
  498. box-shadow: none;
  499. padding: ${space(3)} ${space(4)} 0 40px;
  500. border: 0;
  501. ${p => (p.includeBorder ? `border-top: 1px solid ${p.theme.innerBorder};` : '')}
  502. margin: 0;
  503. `;
  504. const StyledReplayEventDataSection = styled(EventDataSection)`
  505. overflow: hidden;
  506. margin-bottom: ${space(3)};
  507. `;
  508. // TODO(ts): any required due to our use of SharedViewOrganization
  509. export default withOrganization<any>(withApi(EventEntries));
  510. export {BorderlessEventEntries};