fieldRenderers.tsx 28 KB

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