eventEntries.tsx 17 KB

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