fieldRenderers.tsx 27 KB

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