fieldRenderers.tsx 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. import {Fragment} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Location} from 'history';
  5. import partial from 'lodash/partial';
  6. import {Button} from 'sentry/components/button';
  7. import Count from 'sentry/components/count';
  8. import {DropdownMenu, MenuItemProps} from 'sentry/components/dropdownMenu';
  9. import Duration from 'sentry/components/duration';
  10. import FileSize from 'sentry/components/fileSize';
  11. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  12. import UserBadge from 'sentry/components/idBadge/userBadge';
  13. import ExternalLink from 'sentry/components/links/externalLink';
  14. import Link from 'sentry/components/links/link';
  15. import {RowRectangle} from 'sentry/components/performance/waterfall/rowBar';
  16. import {pickBarColor, toPercent} from 'sentry/components/performance/waterfall/utils';
  17. import {Tooltip} from 'sentry/components/tooltip';
  18. import UserMisery from 'sentry/components/userMisery';
  19. import Version from 'sentry/components/version';
  20. import {IconDownload} from 'sentry/icons';
  21. import {t} from 'sentry/locale';
  22. import {space} from 'sentry/styles/space';
  23. import {AvatarProject, IssueAttachment, Organization, Project} from 'sentry/types';
  24. import {defined, isUrl} from 'sentry/utils';
  25. import {trackAnalytics} from 'sentry/utils/analytics';
  26. import EventView, {EventData, MetaType} from 'sentry/utils/discover/eventView';
  27. import {
  28. AGGREGATIONS,
  29. getAggregateAlias,
  30. getSpanOperationName,
  31. isEquation,
  32. isRelativeSpanOperationBreakdownField,
  33. SPAN_OP_BREAKDOWN_FIELDS,
  34. SPAN_OP_RELATIVE_BREAKDOWN_FIELD,
  35. } from 'sentry/utils/discover/fields';
  36. import {getShortEventId} from 'sentry/utils/events';
  37. import {formatFloat, formatPercentage} from 'sentry/utils/formatters';
  38. import getDynamicText from 'sentry/utils/getDynamicText';
  39. import Projects from 'sentry/utils/projects';
  40. import toArray from 'sentry/utils/toArray';
  41. import {QuickContextHoverWrapper} from 'sentry/views/discover/table/quickContext/quickContextWrapper';
  42. import {ContextType} from 'sentry/views/discover/table/quickContext/utils';
  43. import {
  44. filterToLocationQuery,
  45. SpanOperationBreakdownFilter,
  46. stringToFilter,
  47. } from 'sentry/views/performance/transactionSummary/filter';
  48. import {PercentChangeCell} from 'sentry/views/starfish/components/tableCells/percentChangeCell';
  49. import {TimeSpentCell} from 'sentry/views/starfish/components/tableCells/timeSpentCell';
  50. import {SpanMetricsFields} from 'sentry/views/starfish/types';
  51. import {decodeScalar} from '../queryString';
  52. import ArrayValue from './arrayValue';
  53. import {
  54. BarContainer,
  55. Container,
  56. FieldDateTime,
  57. FieldShortId,
  58. FlexContainer,
  59. NumberContainer,
  60. OverflowFieldShortId,
  61. OverflowLink,
  62. UserIcon,
  63. VersionContainer,
  64. } from './styles';
  65. import TeamKeyTransactionField from './teamKeyTransactionField';
  66. /**
  67. * Types, functions and definitions for rendering fields in discover results.
  68. */
  69. export type RenderFunctionBaggage = {
  70. location: Location;
  71. organization: Organization;
  72. eventView?: EventView;
  73. projectSlug?: string;
  74. unit?: string;
  75. };
  76. type RenderFunctionOptions = {
  77. enableOnClick?: boolean;
  78. };
  79. type FieldFormatterRenderFunction = (
  80. field: string,
  81. data: EventData,
  82. baggage?: RenderFunctionBaggage
  83. ) => React.ReactNode;
  84. type FieldFormatterRenderFunctionPartial = (
  85. data: EventData,
  86. baggage: RenderFunctionBaggage
  87. ) => React.ReactNode;
  88. type FieldFormatter = {
  89. isSortable: boolean;
  90. renderFunc: FieldFormatterRenderFunction;
  91. };
  92. type FieldFormatters = {
  93. array: FieldFormatter;
  94. boolean: FieldFormatter;
  95. date: FieldFormatter;
  96. duration: FieldFormatter;
  97. integer: FieldFormatter;
  98. number: FieldFormatter;
  99. percent_change: FieldFormatter;
  100. percentage: FieldFormatter;
  101. size: FieldFormatter;
  102. string: FieldFormatter;
  103. };
  104. export type FieldTypes = keyof FieldFormatters;
  105. const EmptyValueContainer = styled('span')`
  106. color: ${p => p.theme.gray300};
  107. `;
  108. const emptyValue = <EmptyValueContainer>{t('(no value)')}</EmptyValueContainer>;
  109. const emptyStringValue = <EmptyValueContainer>{t('(empty string)')}</EmptyValueContainer>;
  110. export function nullableValue(value: string | null): string | React.ReactElement {
  111. switch (value) {
  112. case null:
  113. return emptyValue;
  114. case '':
  115. return emptyStringValue;
  116. default:
  117. return value;
  118. }
  119. }
  120. export const SIZE_UNITS = {
  121. bit: 1 / 8,
  122. byte: 1,
  123. kibibyte: 1024,
  124. mebibyte: 1024 ** 2,
  125. gibibyte: 1024 ** 3,
  126. tebibyte: 1024 ** 4,
  127. pebibyte: 1024 ** 5,
  128. exbibyte: 1024 ** 6,
  129. kilobyte: 1000,
  130. megabyte: 1000 ** 2,
  131. gigabyte: 1000 ** 3,
  132. terabyte: 1000 ** 4,
  133. petabyte: 1000 ** 5,
  134. exabyte: 1000 ** 6,
  135. };
  136. export const ABYTE_UNITS = [
  137. 'kilobyte',
  138. 'megabyte',
  139. 'gigabyte',
  140. 'terabyte',
  141. 'petabyte',
  142. 'exabyte',
  143. ];
  144. export const DURATION_UNITS = {
  145. nanosecond: 1 / 1000 ** 2,
  146. microsecond: 1 / 1000,
  147. millisecond: 1,
  148. second: 1000,
  149. minute: 1000 * 60,
  150. hour: 1000 * 60 * 60,
  151. day: 1000 * 60 * 60 * 24,
  152. week: 1000 * 60 * 60 * 24 * 7,
  153. };
  154. export const PERCENTAGE_UNITS = ['ratio', 'percent'];
  155. /**
  156. * A mapping of field types to their rendering function.
  157. * This mapping is used when a field is not defined in SPECIAL_FIELDS
  158. * and the field is not being coerced to a link.
  159. *
  160. * This mapping should match the output sentry.utils.snuba:get_json_type
  161. */
  162. export const FIELD_FORMATTERS: FieldFormatters = {
  163. boolean: {
  164. isSortable: true,
  165. renderFunc: (field, data) => {
  166. const value = data[field] ? t('true') : t('false');
  167. return <Container>{value}</Container>;
  168. },
  169. },
  170. date: {
  171. isSortable: true,
  172. renderFunc: (field, data, baggage) => (
  173. <Container>
  174. {data[field]
  175. ? getDynamicText({
  176. value: (
  177. <FieldDateTime
  178. date={data[field]}
  179. year
  180. seconds
  181. timeZone
  182. utc={decodeScalar(baggage?.location?.query?.utc) === 'true'}
  183. />
  184. ),
  185. fixed: 'timestamp',
  186. })
  187. : emptyValue}
  188. </Container>
  189. ),
  190. },
  191. duration: {
  192. isSortable: true,
  193. renderFunc: (field, data, baggage) => {
  194. const {unit} = baggage ?? {};
  195. return (
  196. <NumberContainer>
  197. {typeof data[field] === 'number' ? (
  198. <Duration
  199. seconds={(data[field] * ((unit && DURATION_UNITS[unit]) ?? 1)) / 1000}
  200. fixedDigits={2}
  201. abbreviation
  202. />
  203. ) : (
  204. emptyValue
  205. )}
  206. </NumberContainer>
  207. );
  208. },
  209. },
  210. integer: {
  211. isSortable: true,
  212. renderFunc: (field, data) => (
  213. <NumberContainer>
  214. {typeof data[field] === 'number' ? <Count value={data[field]} /> : emptyValue}
  215. </NumberContainer>
  216. ),
  217. },
  218. number: {
  219. isSortable: true,
  220. renderFunc: (field, data) => (
  221. <NumberContainer>
  222. {typeof data[field] === 'number' ? formatFloat(data[field], 4) : emptyValue}
  223. </NumberContainer>
  224. ),
  225. },
  226. percentage: {
  227. isSortable: true,
  228. renderFunc: (field, data) => (
  229. <NumberContainer>
  230. {typeof data[field] === 'number' ? formatPercentage(data[field]) : emptyValue}
  231. </NumberContainer>
  232. ),
  233. },
  234. size: {
  235. isSortable: true,
  236. renderFunc: (field, data, baggage) => {
  237. const {unit} = baggage ?? {};
  238. return (
  239. <NumberContainer>
  240. {unit && SIZE_UNITS[unit] && typeof data[field] === 'number' ? (
  241. <FileSize
  242. bytes={data[field] * SIZE_UNITS[unit]}
  243. base={ABYTE_UNITS.includes(unit) ? 10 : 2}
  244. />
  245. ) : (
  246. emptyValue
  247. )}
  248. </NumberContainer>
  249. );
  250. },
  251. },
  252. string: {
  253. isSortable: true,
  254. renderFunc: (field, data) => {
  255. // Some fields have long arrays in them, only show the tail of the data.
  256. const value = Array.isArray(data[field])
  257. ? data[field].slice(-1)
  258. : defined(data[field])
  259. ? data[field]
  260. : emptyValue;
  261. if (isUrl(value)) {
  262. return (
  263. <Container>
  264. <ExternalLink href={value} data-test-id="group-tag-url">
  265. {value}
  266. </ExternalLink>
  267. </Container>
  268. );
  269. }
  270. return <Container>{nullableValue(value)}</Container>;
  271. },
  272. },
  273. array: {
  274. isSortable: true,
  275. renderFunc: (field, data) => {
  276. const value = toArray(data[field]);
  277. return <ArrayValue value={value} />;
  278. },
  279. },
  280. percent_change: {
  281. isSortable: true,
  282. renderFunc: (fieldName, data) => {
  283. const deltaValue = data[fieldName];
  284. const sign = deltaValue >= 0 ? '+' : '-';
  285. const delta = formatPercentage(Math.abs(deltaValue), 2);
  286. const trendDirection = deltaValue < 0 ? 'good' : deltaValue > 0 ? 'bad' : 'neutral';
  287. return (
  288. <PercentChangeCell
  289. trendDirection={trendDirection}
  290. >{`${sign}${delta}`}</PercentChangeCell>
  291. );
  292. },
  293. },
  294. };
  295. type SpecialFieldRenderFunc = (
  296. data: EventData,
  297. baggage: RenderFunctionBaggage
  298. ) => React.ReactNode;
  299. type SpecialField = {
  300. renderFunc: SpecialFieldRenderFunc;
  301. sortField: string | null;
  302. };
  303. type SpecialFields = {
  304. attachments: SpecialField;
  305. 'count_unique(user)': SpecialField;
  306. 'error.handled': SpecialField;
  307. id: SpecialField;
  308. issue: SpecialField;
  309. 'issue.id': SpecialField;
  310. minidump: SpecialField;
  311. 'profile.id': SpecialField;
  312. project: SpecialField;
  313. release: SpecialField;
  314. replayId: SpecialField;
  315. team_key_transaction: SpecialField;
  316. 'timestamp.to_day': SpecialField;
  317. 'timestamp.to_hour': SpecialField;
  318. trace: SpecialField;
  319. 'trend_percentage()': SpecialField;
  320. user: SpecialField;
  321. 'user.display': SpecialField;
  322. };
  323. const DownloadCount = styled('span')`
  324. padding-left: ${space(0.75)};
  325. `;
  326. const RightAlignedContainer = styled('span')`
  327. margin-left: auto;
  328. margin-right: 0;
  329. `;
  330. /**
  331. * "Special fields" either do not map 1:1 to an single column in the event database,
  332. * or they require custom UI formatting that can't be handled by the datatype formatters.
  333. */
  334. const SPECIAL_FIELDS: SpecialFields = {
  335. // This is a custom renderer for a field outside discover
  336. // TODO - refactor code and remove from this file or add ability to query for attachments in Discover
  337. attachments: {
  338. sortField: null,
  339. renderFunc: (data, {organization, projectSlug}) => {
  340. const attachments: Array<IssueAttachment> = data.attachments;
  341. const items: MenuItemProps[] = attachments
  342. .filter(attachment => attachment.type !== 'event.minidump')
  343. .map(attachment => ({
  344. key: attachment.id,
  345. label: attachment.name,
  346. onAction: () =>
  347. window.open(
  348. `/api/0/projects/${organization.slug}/${projectSlug}/events/${attachment.event_id}/attachments/${attachment.id}/?download=1`
  349. ),
  350. }));
  351. return (
  352. <RightAlignedContainer>
  353. <DropdownMenu
  354. position="left"
  355. size="xs"
  356. triggerProps={{
  357. showChevron: false,
  358. icon: (
  359. <Fragment>
  360. <IconDownload color="gray500" size="sm" />
  361. <DownloadCount>{items.length}</DownloadCount>
  362. </Fragment>
  363. ),
  364. }}
  365. items={items}
  366. />
  367. </RightAlignedContainer>
  368. );
  369. },
  370. },
  371. minidump: {
  372. sortField: null,
  373. renderFunc: (data, {organization, projectSlug}) => {
  374. const attachments: Array<IssueAttachment & {url: string}> = data.attachments;
  375. const minidump = attachments.find(
  376. attachment => attachment.type === 'event.minidump'
  377. );
  378. return (
  379. <RightAlignedContainer>
  380. <Button
  381. size="xs"
  382. disabled={!minidump}
  383. onClick={
  384. minidump
  385. ? () => {
  386. window.open(
  387. `/api/0/projects/${organization.slug}/${projectSlug}/events/${minidump.event_id}/attachments/${minidump.id}/?download=1`
  388. );
  389. }
  390. : undefined
  391. }
  392. >
  393. <IconDownload color="gray500" size="sm" />
  394. <DownloadCount>{minidump ? 1 : 0}</DownloadCount>
  395. </Button>
  396. </RightAlignedContainer>
  397. );
  398. },
  399. },
  400. id: {
  401. sortField: 'id',
  402. renderFunc: data => {
  403. const id: string | unknown = data?.id;
  404. if (typeof id !== 'string') {
  405. return null;
  406. }
  407. return <Container>{getShortEventId(id)}</Container>;
  408. },
  409. },
  410. trace: {
  411. sortField: 'trace',
  412. renderFunc: data => {
  413. const id: string | unknown = data?.trace;
  414. if (typeof id !== 'string') {
  415. return emptyValue;
  416. }
  417. return <Container>{getShortEventId(id)}</Container>;
  418. },
  419. },
  420. 'issue.id': {
  421. sortField: 'issue.id',
  422. renderFunc: (data, {organization}) => {
  423. const target = {
  424. pathname: `/organizations/${organization.slug}/issues/${data['issue.id']}/`,
  425. };
  426. return (
  427. <Container>
  428. <OverflowLink to={target} aria-label={data['issue.id']}>
  429. {data['issue.id']}
  430. </OverflowLink>
  431. </Container>
  432. );
  433. },
  434. },
  435. replayId: {
  436. sortField: 'replayId',
  437. renderFunc: data => {
  438. const replayId = data?.replayId;
  439. if (typeof replayId !== 'string' || !replayId) {
  440. return emptyValue;
  441. }
  442. return <Container>{getShortEventId(replayId)}</Container>;
  443. },
  444. },
  445. 'profile.id': {
  446. sortField: 'profile.id',
  447. renderFunc: data => {
  448. const id: string | unknown = data?.['profile.id'];
  449. if (typeof id !== 'string') {
  450. return emptyValue;
  451. }
  452. return <Container>{getShortEventId(id)}</Container>;
  453. },
  454. },
  455. issue: {
  456. sortField: null,
  457. renderFunc: (data, {organization}) => {
  458. const issueID = data['issue.id'];
  459. if (!issueID) {
  460. return (
  461. <Container>
  462. <FieldShortId shortId={`${data.issue}`} />
  463. </Container>
  464. );
  465. }
  466. const target = {
  467. pathname: `/organizations/${organization.slug}/issues/${issueID}/`,
  468. };
  469. return (
  470. <Container>
  471. <QuickContextHoverWrapper
  472. dataRow={data}
  473. contextType={ContextType.ISSUE}
  474. organization={organization}
  475. >
  476. <StyledLink to={target} aria-label={issueID}>
  477. <OverflowFieldShortId shortId={`${data.issue}`} />
  478. </StyledLink>
  479. </QuickContextHoverWrapper>
  480. </Container>
  481. );
  482. },
  483. },
  484. project: {
  485. sortField: 'project',
  486. renderFunc: (data, {organization}) => {
  487. let slugs: string[] | undefined = undefined;
  488. let projectIds: number[] | undefined = undefined;
  489. if (typeof data.project === 'number') {
  490. projectIds = [data.project];
  491. } else {
  492. slugs = [data.project];
  493. }
  494. return (
  495. <Container>
  496. <Projects orgId={organization.slug} slugs={slugs} projectIds={projectIds}>
  497. {({projects}) => {
  498. let project: Project | AvatarProject | undefined;
  499. if (typeof data.project === 'number') {
  500. project = projects.find(p => p.id === data.project.toString());
  501. } else {
  502. project = projects.find(p => p.slug === data.project);
  503. }
  504. return (
  505. <ProjectBadge
  506. project={project ? project : {slug: data.project}}
  507. avatarSize={16}
  508. />
  509. );
  510. }}
  511. </Projects>
  512. </Container>
  513. );
  514. },
  515. },
  516. user: {
  517. sortField: 'user',
  518. renderFunc: data => {
  519. if (data.user) {
  520. const [key, value] = data.user.split(':');
  521. const userObj = {
  522. id: '',
  523. name: '',
  524. email: '',
  525. username: '',
  526. ip_address: '',
  527. };
  528. userObj[key] = value;
  529. const badge = <UserBadge user={userObj} hideEmail avatarSize={16} />;
  530. return <Container>{badge}</Container>;
  531. }
  532. return <Container>{emptyValue}</Container>;
  533. },
  534. },
  535. 'user.display': {
  536. sortField: 'user.display',
  537. renderFunc: data => {
  538. if (data['user.display']) {
  539. const userObj = {
  540. id: '',
  541. name: data['user.display'],
  542. email: '',
  543. username: '',
  544. ip_address: '',
  545. };
  546. const badge = <UserBadge user={userObj} hideEmail avatarSize={16} />;
  547. return <Container>{badge}</Container>;
  548. }
  549. return <Container>{emptyValue}</Container>;
  550. },
  551. },
  552. 'count_unique(user)': {
  553. sortField: 'count_unique(user)',
  554. renderFunc: data => {
  555. const count = data.count_unique_user ?? data['count_unique(user)'];
  556. if (typeof count === 'number') {
  557. return (
  558. <FlexContainer>
  559. <NumberContainer>
  560. <Count value={count} />
  561. </NumberContainer>
  562. <UserIcon size="md" />
  563. </FlexContainer>
  564. );
  565. }
  566. return <Container>{emptyValue}</Container>;
  567. },
  568. },
  569. release: {
  570. sortField: 'release',
  571. renderFunc: (data, {organization}) =>
  572. data.release ? (
  573. <VersionContainer>
  574. <QuickContextHoverWrapper
  575. dataRow={data}
  576. contextType={ContextType.RELEASE}
  577. organization={organization}
  578. >
  579. <Version version={data.release} truncate />
  580. </QuickContextHoverWrapper>
  581. </VersionContainer>
  582. ) : (
  583. <Container>{emptyValue}</Container>
  584. ),
  585. },
  586. 'error.handled': {
  587. sortField: 'error.handled',
  588. renderFunc: data => {
  589. const values = data['error.handled'];
  590. // Transactions will have null, and default events have no handled attributes.
  591. if (values === null || values?.length === 0) {
  592. return <Container>{emptyValue}</Container>;
  593. }
  594. const value = Array.isArray(values) ? values : [values];
  595. return (
  596. <Container>
  597. {value.every(v => [1, null].includes(v)) ? 'true' : 'false'}
  598. </Container>
  599. );
  600. },
  601. },
  602. team_key_transaction: {
  603. sortField: null,
  604. renderFunc: (data, {organization}) => (
  605. <Container>
  606. <TeamKeyTransactionField
  607. isKeyTransaction={(data.team_key_transaction ?? 0) !== 0}
  608. organization={organization}
  609. projectSlug={data.project}
  610. transactionName={data.transaction}
  611. />
  612. </Container>
  613. ),
  614. },
  615. 'trend_percentage()': {
  616. sortField: 'trend_percentage()',
  617. renderFunc: data => (
  618. <NumberContainer>
  619. {typeof data.trend_percentage === 'number'
  620. ? formatPercentage(data.trend_percentage - 1)
  621. : emptyValue}
  622. </NumberContainer>
  623. ),
  624. },
  625. 'timestamp.to_hour': {
  626. sortField: 'timestamp.to_hour',
  627. renderFunc: data => (
  628. <Container>
  629. {getDynamicText({
  630. value: <FieldDateTime date={data['timestamp.to_hour']} year timeZone />,
  631. fixed: 'timestamp.to_hour',
  632. })}
  633. </Container>
  634. ),
  635. },
  636. 'timestamp.to_day': {
  637. sortField: 'timestamp.to_day',
  638. renderFunc: data => (
  639. <Container>
  640. {getDynamicText({
  641. value: <FieldDateTime date={data['timestamp.to_day']} dateOnly year utc />,
  642. fixed: 'timestamp.to_day',
  643. })}
  644. </Container>
  645. ),
  646. },
  647. };
  648. type SpecialFunctionFieldRenderer = (
  649. fieldName: string
  650. ) => (data: EventData, baggage: RenderFunctionBaggage) => React.ReactNode;
  651. type SpecialFunctions = {
  652. sps_percent_change: SpecialFunctionFieldRenderer;
  653. time_spent_percentage: SpecialFunctionFieldRenderer;
  654. user_misery: SpecialFunctionFieldRenderer;
  655. };
  656. /**
  657. * "Special functions" are functions whose values either do not map 1:1 to a single column,
  658. * or they require custom UI formatting that can't be handled by the datatype formatters.
  659. */
  660. const SPECIAL_FUNCTIONS: SpecialFunctions = {
  661. user_misery: fieldName => data => {
  662. const userMiseryField = fieldName;
  663. if (!(userMiseryField in data)) {
  664. return <NumberContainer>{emptyValue}</NumberContainer>;
  665. }
  666. const userMisery = data[userMiseryField];
  667. if (userMisery === null || isNaN(userMisery)) {
  668. return <NumberContainer>{emptyValue}</NumberContainer>;
  669. }
  670. const projectThresholdConfig = 'project_threshold_config';
  671. let countMiserableUserField: string = '';
  672. let miseryLimit: number | undefined = parseInt(
  673. userMiseryField.split('(').pop()?.slice(0, -1) || '',
  674. 10
  675. );
  676. if (isNaN(miseryLimit)) {
  677. countMiserableUserField = 'count_miserable(user)';
  678. if (projectThresholdConfig in data) {
  679. miseryLimit = data[projectThresholdConfig][1];
  680. } else {
  681. miseryLimit = undefined;
  682. }
  683. } else {
  684. countMiserableUserField = `count_miserable(user,${miseryLimit})`;
  685. }
  686. const uniqueUsers = data['count_unique(user)'];
  687. let miserableUsers: number | undefined;
  688. if (countMiserableUserField in data) {
  689. const countMiserableMiseryLimit = parseInt(
  690. userMiseryField.split('(').pop()?.slice(0, -1) || '',
  691. 10
  692. );
  693. miserableUsers =
  694. countMiserableMiseryLimit === miseryLimit ||
  695. (isNaN(countMiserableMiseryLimit) && projectThresholdConfig)
  696. ? data[countMiserableUserField]
  697. : undefined;
  698. }
  699. return (
  700. <BarContainer>
  701. <UserMisery
  702. bars={10}
  703. barHeight={20}
  704. miseryLimit={miseryLimit}
  705. totalUsers={uniqueUsers}
  706. userMisery={userMisery}
  707. miserableUsers={miserableUsers}
  708. />
  709. </BarContainer>
  710. );
  711. },
  712. sps_percent_change: fieldName => data => {
  713. const deltaValue = data[fieldName];
  714. const sign = deltaValue >= 0 ? '+' : '-';
  715. const delta = formatPercentage(Math.abs(deltaValue), 2);
  716. return (
  717. // N.B. For throughput, the change is neither good nor bad regardless of value! Throughput is just throughput
  718. <PercentChangeCell trendDirection="neutral">{`${sign}${delta}`}</PercentChangeCell>
  719. );
  720. },
  721. time_spent_percentage: fieldName => data => {
  722. return (
  723. <TimeSpentCell
  724. timeSpentPercentage={data[fieldName]}
  725. totalSpanTime={data[`sum(${SpanMetricsFields.SPAN_SELF_TIME})`]}
  726. />
  727. );
  728. },
  729. };
  730. /**
  731. * Get the sort field name for a given field if it is special or fallback
  732. * to the generic type formatter.
  733. */
  734. export function getSortField(
  735. field: string,
  736. tableMeta: MetaType | undefined
  737. ): string | null {
  738. if (SPECIAL_FIELDS.hasOwnProperty(field)) {
  739. return SPECIAL_FIELDS[field as keyof typeof SPECIAL_FIELDS].sortField;
  740. }
  741. if (!tableMeta) {
  742. return field;
  743. }
  744. if (isEquation(field)) {
  745. return field;
  746. }
  747. for (const alias in AGGREGATIONS) {
  748. if (field.startsWith(alias)) {
  749. return AGGREGATIONS[alias].isSortable ? field : null;
  750. }
  751. }
  752. const fieldType = tableMeta[field];
  753. if (FIELD_FORMATTERS.hasOwnProperty(fieldType)) {
  754. return FIELD_FORMATTERS[fieldType as keyof typeof FIELD_FORMATTERS].isSortable
  755. ? field
  756. : null;
  757. }
  758. return null;
  759. }
  760. const isDurationValue = (data: EventData, field: string): boolean => {
  761. return field in data && typeof data[field] === 'number';
  762. };
  763. export const spanOperationRelativeBreakdownRenderer = (
  764. data: EventData,
  765. {location, organization, eventView}: RenderFunctionBaggage,
  766. options?: RenderFunctionOptions
  767. ): React.ReactNode => {
  768. const {enableOnClick = true} = options ?? {};
  769. const sumOfSpanTime = SPAN_OP_BREAKDOWN_FIELDS.reduce(
  770. (prev, curr) => (isDurationValue(data, curr) ? prev + data[curr] : prev),
  771. 0
  772. );
  773. const cumulativeSpanOpBreakdown = Math.max(sumOfSpanTime, data['transaction.duration']);
  774. if (
  775. SPAN_OP_BREAKDOWN_FIELDS.every(field => !isDurationValue(data, field)) ||
  776. cumulativeSpanOpBreakdown === 0
  777. ) {
  778. return FIELD_FORMATTERS.duration.renderFunc(SPAN_OP_RELATIVE_BREAKDOWN_FIELD, data);
  779. }
  780. let otherPercentage = 1;
  781. let orderedSpanOpsBreakdownFields;
  782. const sortingOnField = eventView?.sorts?.[0]?.field;
  783. if (sortingOnField && (SPAN_OP_BREAKDOWN_FIELDS as string[]).includes(sortingOnField)) {
  784. orderedSpanOpsBreakdownFields = [
  785. sortingOnField,
  786. ...SPAN_OP_BREAKDOWN_FIELDS.filter(op => op !== sortingOnField),
  787. ];
  788. } else {
  789. orderedSpanOpsBreakdownFields = SPAN_OP_BREAKDOWN_FIELDS;
  790. }
  791. return (
  792. <RelativeOpsBreakdown data-test-id="relative-ops-breakdown">
  793. {orderedSpanOpsBreakdownFields.map(field => {
  794. if (!isDurationValue(data, field)) {
  795. return null;
  796. }
  797. const operationName = getSpanOperationName(field) ?? 'op';
  798. const spanOpDuration: number = data[field];
  799. const widthPercentage = spanOpDuration / cumulativeSpanOpBreakdown;
  800. otherPercentage = otherPercentage - widthPercentage;
  801. if (widthPercentage === 0) {
  802. return null;
  803. }
  804. return (
  805. <div key={operationName} style={{width: toPercent(widthPercentage || 0)}}>
  806. <Tooltip
  807. title={
  808. <div>
  809. <div>{operationName}</div>
  810. <div>
  811. <Duration
  812. seconds={spanOpDuration / 1000}
  813. fixedDigits={2}
  814. abbreviation
  815. />
  816. </div>
  817. </div>
  818. }
  819. containerDisplayMode="block"
  820. >
  821. <RectangleRelativeOpsBreakdown
  822. style={{
  823. backgroundColor: pickBarColor(operationName),
  824. cursor: enableOnClick ? 'pointer' : 'default',
  825. }}
  826. onClick={event => {
  827. if (!enableOnClick) {
  828. return;
  829. }
  830. event.stopPropagation();
  831. const filter = stringToFilter(operationName);
  832. if (filter === SpanOperationBreakdownFilter.NONE) {
  833. return;
  834. }
  835. trackAnalytics('performance_views.relative_breakdown.selection', {
  836. action: filter,
  837. organization,
  838. });
  839. browserHistory.push({
  840. pathname: location.pathname,
  841. query: {
  842. ...location.query,
  843. ...filterToLocationQuery(filter),
  844. },
  845. });
  846. }}
  847. />
  848. </Tooltip>
  849. </div>
  850. );
  851. })}
  852. <div key="other" style={{width: toPercent(otherPercentage || 0)}}>
  853. <Tooltip title={<div>{t('Other')}</div>} containerDisplayMode="block">
  854. <OtherRelativeOpsBreakdown />
  855. </Tooltip>
  856. </div>
  857. </RelativeOpsBreakdown>
  858. );
  859. };
  860. const RelativeOpsBreakdown = styled('div')`
  861. position: relative;
  862. display: flex;
  863. `;
  864. const RectangleRelativeOpsBreakdown = styled(RowRectangle)`
  865. position: relative;
  866. width: 100%;
  867. `;
  868. const OtherRelativeOpsBreakdown = styled(RectangleRelativeOpsBreakdown)`
  869. background-color: ${p => p.theme.gray100};
  870. `;
  871. const StyledLink = styled(Link)`
  872. max-width: 100%;
  873. `;
  874. /**
  875. * Get the field renderer for the named field and metadata
  876. *
  877. * @param {String} field name
  878. * @param {object} metadata mapping.
  879. * @param {boolean} isAlias convert the name with getAggregateAlias
  880. * @returns {Function}
  881. */
  882. export function getFieldRenderer(
  883. field: string,
  884. meta: MetaType,
  885. isAlias: boolean = true
  886. ): FieldFormatterRenderFunctionPartial {
  887. if (SPECIAL_FIELDS.hasOwnProperty(field)) {
  888. return SPECIAL_FIELDS[field].renderFunc;
  889. }
  890. if (isRelativeSpanOperationBreakdownField(field)) {
  891. return spanOperationRelativeBreakdownRenderer;
  892. }
  893. const fieldName = isAlias ? getAggregateAlias(field) : field;
  894. const fieldType = meta[fieldName];
  895. for (const alias in SPECIAL_FUNCTIONS) {
  896. if (fieldName.startsWith(alias)) {
  897. return SPECIAL_FUNCTIONS[alias](fieldName);
  898. }
  899. }
  900. if (FIELD_FORMATTERS.hasOwnProperty(fieldType)) {
  901. return partial(FIELD_FORMATTERS[fieldType].renderFunc, fieldName);
  902. }
  903. return partial(FIELD_FORMATTERS.string.renderFunc, fieldName);
  904. }
  905. type FieldTypeFormatterRenderFunctionPartial = (
  906. data: EventData,
  907. baggage?: RenderFunctionBaggage
  908. ) => React.ReactNode;
  909. /**
  910. * Get the field renderer for the named field only based on its type from the given
  911. * metadata.
  912. *
  913. * @param {String} field name
  914. * @param {object} metadata mapping.
  915. * @param {boolean} isAlias convert the name with getAggregateAlias
  916. * @returns {Function}
  917. */
  918. export function getFieldFormatter(
  919. field: string,
  920. meta: MetaType,
  921. isAlias: boolean = true
  922. ): FieldTypeFormatterRenderFunctionPartial {
  923. const fieldName = isAlias ? getAggregateAlias(field) : field;
  924. const fieldType = meta[fieldName];
  925. if (FIELD_FORMATTERS.hasOwnProperty(fieldType)) {
  926. return partial(FIELD_FORMATTERS[fieldType].renderFunc, fieldName);
  927. }
  928. return partial(FIELD_FORMATTERS.string.renderFunc, fieldName);
  929. }