fieldRenderers.tsx 27 KB

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