fieldRenderers.tsx 28 KB

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