fieldRenderers.tsx 29 KB

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