fieldRenderers.tsx 26 KB

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