eventEntries.tsx 16 KB

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