fieldRenderers.tsx 26 KB

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