fieldRenderers.tsx 29 KB

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