fieldRenderers.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. import * as React 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 Count from 'app/components/count';
  7. import Duration from 'app/components/duration';
  8. import ProjectBadge from 'app/components/idBadge/projectBadge';
  9. import UserBadge from 'app/components/idBadge/userBadge';
  10. import {RowRectangle} from 'app/components/performance/waterfall/rowBar';
  11. import {pickBarColour, toPercent} from 'app/components/performance/waterfall/utils';
  12. import Tooltip from 'app/components/tooltip';
  13. import UserMisery from 'app/components/userMisery';
  14. import Version from 'app/components/version';
  15. import {t} from 'app/locale';
  16. import {Organization} from 'app/types';
  17. import {defined} from 'app/utils';
  18. import {trackAnalyticsEvent} from 'app/utils/analytics';
  19. import {
  20. AGGREGATIONS,
  21. getAggregateAlias,
  22. getSpanOperationName,
  23. isRelativeSpanOperationBreakdownField,
  24. SPAN_OP_BREAKDOWN_FIELDS,
  25. SPAN_OP_RELATIVE_BREAKDOWN_FIELD,
  26. } from 'app/utils/discover/fields';
  27. import {getShortEventId} from 'app/utils/events';
  28. import {formatFloat, formatPercentage} from 'app/utils/formatters';
  29. import getDynamicText from 'app/utils/getDynamicText';
  30. import Projects from 'app/utils/projects';
  31. import {
  32. filterToLocationQuery,
  33. SpanOperationBreakdownFilter,
  34. stringToFilter,
  35. } from 'app/views/performance/transactionSummary/filter';
  36. import ArrayValue from './arrayValue';
  37. import {EventData, MetaType} from './eventView';
  38. import KeyTransactionField from './keyTransactionField';
  39. import {
  40. BarContainer,
  41. Container,
  42. FlexContainer,
  43. NumberContainer,
  44. OverflowLink,
  45. StyledDateTime,
  46. StyledShortId,
  47. UserIcon,
  48. VersionContainer,
  49. } from './styles';
  50. /**
  51. * Types, functions and definitions for rendering fields in discover results.
  52. */
  53. type RenderFunctionBaggage = {
  54. organization: Organization;
  55. location: Location;
  56. };
  57. type FieldFormatterRenderFunction = (field: string, data: EventData) => React.ReactNode;
  58. type FieldFormatterRenderFunctionPartial = (
  59. data: EventData,
  60. baggage: RenderFunctionBaggage
  61. ) => React.ReactNode;
  62. type FieldFormatter = {
  63. isSortable: boolean;
  64. renderFunc: FieldFormatterRenderFunction;
  65. };
  66. type FieldFormatters = {
  67. boolean: FieldFormatter;
  68. date: FieldFormatter;
  69. duration: FieldFormatter;
  70. integer: FieldFormatter;
  71. number: FieldFormatter;
  72. percentage: FieldFormatter;
  73. string: FieldFormatter;
  74. array: FieldFormatter;
  75. };
  76. export type FieldTypes = keyof FieldFormatters;
  77. const EmptyValueContainer = styled('span')`
  78. color: ${p => p.theme.gray300};
  79. `;
  80. const emptyValue = <EmptyValueContainer>{t('n/a')}</EmptyValueContainer>;
  81. /**
  82. * A mapping of field types to their rendering function.
  83. * This mapping is used when a field is not defined in SPECIAL_FIELDS
  84. * and the field is not being coerced to a link.
  85. *
  86. * This mapping should match the output sentry.utils.snuba:get_json_type
  87. */
  88. const FIELD_FORMATTERS: FieldFormatters = {
  89. boolean: {
  90. isSortable: true,
  91. renderFunc: (field, data) => {
  92. const value = data[field] ? t('true') : t('false');
  93. return <Container>{value}</Container>;
  94. },
  95. },
  96. date: {
  97. isSortable: true,
  98. renderFunc: (field, data) => (
  99. <Container>
  100. {data[field]
  101. ? getDynamicText({
  102. value: <StyledDateTime date={data[field]} />,
  103. fixed: 'timestamp',
  104. })
  105. : emptyValue}
  106. </Container>
  107. ),
  108. },
  109. duration: {
  110. isSortable: true,
  111. renderFunc: (field, data) => (
  112. <NumberContainer>
  113. {typeof data[field] === 'number' ? (
  114. <Duration seconds={data[field] / 1000} fixedDigits={2} abbreviation />
  115. ) : (
  116. emptyValue
  117. )}
  118. </NumberContainer>
  119. ),
  120. },
  121. integer: {
  122. isSortable: true,
  123. renderFunc: (field, data) => (
  124. <NumberContainer>
  125. {typeof data[field] === 'number' ? <Count value={data[field]} /> : emptyValue}
  126. </NumberContainer>
  127. ),
  128. },
  129. number: {
  130. isSortable: true,
  131. renderFunc: (field, data) => (
  132. <NumberContainer>
  133. {typeof data[field] === 'number' ? formatFloat(data[field], 4) : emptyValue}
  134. </NumberContainer>
  135. ),
  136. },
  137. percentage: {
  138. isSortable: true,
  139. renderFunc: (field, data) => (
  140. <NumberContainer>
  141. {typeof data[field] === 'number' ? formatPercentage(data[field]) : emptyValue}
  142. </NumberContainer>
  143. ),
  144. },
  145. string: {
  146. isSortable: true,
  147. renderFunc: (field, data) => {
  148. // Some fields have long arrays in them, only show the tail of the data.
  149. const value = Array.isArray(data[field])
  150. ? data[field].slice(-1)
  151. : defined(data[field])
  152. ? data[field]
  153. : emptyValue;
  154. return <Container>{value}</Container>;
  155. },
  156. },
  157. array: {
  158. isSortable: true,
  159. renderFunc: (field, data) => {
  160. const value = Array.isArray(data[field]) ? data[field] : [data[field]];
  161. return <ArrayValue value={value} />;
  162. },
  163. },
  164. };
  165. type SpecialFieldRenderFunc = (
  166. data: EventData,
  167. baggage: RenderFunctionBaggage
  168. ) => React.ReactNode;
  169. type SpecialField = {
  170. sortField: string | null;
  171. renderFunc: SpecialFieldRenderFunc;
  172. };
  173. type SpecialFields = {
  174. id: SpecialField;
  175. trace: SpecialField;
  176. project: SpecialField;
  177. user: SpecialField;
  178. 'user.display': SpecialField;
  179. 'count_unique(user)': SpecialField;
  180. 'issue.id': SpecialField;
  181. 'error.handled': SpecialField;
  182. issue: SpecialField;
  183. release: SpecialField;
  184. key_transaction: SpecialField;
  185. 'trend_percentage()': SpecialField;
  186. 'timestamp.to_hour': SpecialField;
  187. 'timestamp.to_day': SpecialField;
  188. };
  189. /**
  190. * "Special fields" either do not map 1:1 to an single column in the event database,
  191. * or they require custom UI formatting that can't be handled by the datatype formatters.
  192. */
  193. const SPECIAL_FIELDS: SpecialFields = {
  194. id: {
  195. sortField: 'id',
  196. renderFunc: data => {
  197. const id: string | unknown = data?.id;
  198. if (typeof id !== 'string') {
  199. return null;
  200. }
  201. return <Container>{getShortEventId(id)}</Container>;
  202. },
  203. },
  204. trace: {
  205. sortField: 'trace',
  206. renderFunc: data => {
  207. const id: string | unknown = data?.trace;
  208. if (typeof id !== 'string') {
  209. return null;
  210. }
  211. return <Container>{getShortEventId(id)}</Container>;
  212. },
  213. },
  214. 'issue.id': {
  215. sortField: 'issue.id',
  216. renderFunc: (data, {organization}) => {
  217. const target = {
  218. pathname: `/organizations/${organization.slug}/issues/${data['issue.id']}/`,
  219. };
  220. return (
  221. <Container>
  222. <OverflowLink to={target} aria-label={data['issue.id']}>
  223. {data['issue.id']}
  224. </OverflowLink>
  225. </Container>
  226. );
  227. },
  228. },
  229. issue: {
  230. sortField: null,
  231. renderFunc: (data, {organization}) => {
  232. const issueID = data['issue.id'];
  233. if (!issueID) {
  234. return (
  235. <Container>
  236. <StyledShortId shortId={`${data.issue}`} />
  237. </Container>
  238. );
  239. }
  240. const target = {
  241. pathname: `/organizations/${organization.slug}/issues/${issueID}/`,
  242. };
  243. return (
  244. <Container>
  245. <OverflowLink to={target} aria-label={issueID}>
  246. <StyledShortId shortId={`${data.issue}`} />
  247. </OverflowLink>
  248. </Container>
  249. );
  250. },
  251. },
  252. project: {
  253. sortField: 'project',
  254. renderFunc: (data, {organization}) => {
  255. return (
  256. <Container>
  257. <Projects orgId={organization.slug} slugs={[data.project]}>
  258. {({projects}) => {
  259. const project = projects.find(p => p.slug === data.project);
  260. return (
  261. <ProjectBadge
  262. project={project ? project : {slug: data.project}}
  263. avatarSize={16}
  264. />
  265. );
  266. }}
  267. </Projects>
  268. </Container>
  269. );
  270. },
  271. },
  272. user: {
  273. sortField: 'user',
  274. renderFunc: data => {
  275. if (data.user) {
  276. const [key, value] = data.user.split(':');
  277. const userObj = {
  278. id: '',
  279. name: '',
  280. email: '',
  281. username: '',
  282. ip_address: '',
  283. };
  284. userObj[key] = value;
  285. const badge = <UserBadge user={userObj} hideEmail avatarSize={16} />;
  286. return <Container>{badge}</Container>;
  287. }
  288. return <Container>{emptyValue}</Container>;
  289. },
  290. },
  291. 'user.display': {
  292. sortField: 'user.display',
  293. renderFunc: data => {
  294. if (data['user.display']) {
  295. const userObj = {
  296. id: '',
  297. name: data['user.display'],
  298. email: '',
  299. username: '',
  300. ip_address: '',
  301. };
  302. const badge = <UserBadge user={userObj} hideEmail avatarSize={16} />;
  303. return <Container>{badge}</Container>;
  304. }
  305. return <Container>{emptyValue}</Container>;
  306. },
  307. },
  308. 'count_unique(user)': {
  309. sortField: 'count_unique(user)',
  310. renderFunc: data => {
  311. const count = data.count_unique_user;
  312. if (typeof count === 'number') {
  313. return (
  314. <FlexContainer>
  315. <NumberContainer>
  316. <Count value={count} />
  317. </NumberContainer>
  318. <UserIcon size="20" />
  319. </FlexContainer>
  320. );
  321. }
  322. return <Container>{emptyValue}</Container>;
  323. },
  324. },
  325. release: {
  326. sortField: 'release',
  327. renderFunc: data =>
  328. data.release ? (
  329. <VersionContainer>
  330. <Version version={data.release} anchor={false} tooltipRawVersion truncate />
  331. </VersionContainer>
  332. ) : (
  333. <Container>{emptyValue}</Container>
  334. ),
  335. },
  336. 'error.handled': {
  337. sortField: 'error.handled',
  338. renderFunc: data => {
  339. const values = data['error.handled'];
  340. // Transactions will have null, and default events have no handled attributes.
  341. if (values === null || values?.length === 0) {
  342. return <Container>{emptyValue}</Container>;
  343. }
  344. const value = Array.isArray(values) ? values.slice(-1)[0] : values;
  345. return <Container>{[1, null].includes(value) ? 'true' : 'false'}</Container>;
  346. },
  347. },
  348. key_transaction: {
  349. sortField: 'key_transaction',
  350. renderFunc: (data, {organization}) => (
  351. <Container>
  352. <KeyTransactionField
  353. isKeyTransaction={(data.key_transaction ?? 0) !== 0}
  354. organization={organization}
  355. projectSlug={data.project}
  356. transactionName={data.transaction}
  357. />
  358. </Container>
  359. ),
  360. },
  361. 'trend_percentage()': {
  362. sortField: 'trend_percentage()',
  363. renderFunc: data => (
  364. <NumberContainer>
  365. {typeof data.trend_percentage === 'number'
  366. ? formatPercentage(data.trend_percentage - 1)
  367. : emptyValue}
  368. </NumberContainer>
  369. ),
  370. },
  371. 'timestamp.to_hour': {
  372. sortField: 'timestamp.to_hour',
  373. renderFunc: data => (
  374. <Container>
  375. {getDynamicText({
  376. value: <StyledDateTime date={data['timestamp.to_hour']} format="lll z" />,
  377. fixed: 'timestamp.to_hour',
  378. })}
  379. </Container>
  380. ),
  381. },
  382. 'timestamp.to_day': {
  383. sortField: 'timestamp.to_day',
  384. renderFunc: data => (
  385. <Container>
  386. {getDynamicText({
  387. value: <StyledDateTime date={data['timestamp.to_day']} format="MMM D, YYYY" />,
  388. fixed: 'timestamp.to_day',
  389. })}
  390. </Container>
  391. ),
  392. },
  393. };
  394. type SpecialFunctions = {
  395. user_misery: SpecialFieldRenderFunc;
  396. };
  397. /**
  398. * "Special functions" are functions whose values either do not map 1:1 to a single column,
  399. * or they require custom UI formatting that can't be handled by the datatype formatters.
  400. */
  401. const SPECIAL_FUNCTIONS: SpecialFunctions = {
  402. user_misery: data => {
  403. let userMiseryField: string = '';
  404. let countMiserableUserField: string = '';
  405. let projectThresholdConfig: string = '';
  406. for (const field in data) {
  407. if (field.startsWith('user_misery')) {
  408. userMiseryField = field;
  409. } else if (
  410. field.startsWith('count_miserable_user') ||
  411. field.startsWith('count_miserable_new_user')
  412. ) {
  413. countMiserableUserField = field;
  414. } else if (field === 'project_threshold_config') {
  415. projectThresholdConfig = field;
  416. }
  417. }
  418. if (!userMiseryField) {
  419. return <NumberContainer>{emptyValue}</NumberContainer>;
  420. }
  421. const uniqueUsers = data.count_unique_user;
  422. const userMisery = data[userMiseryField];
  423. let miseryLimit = parseInt(userMiseryField.split('_').pop() || '', 10);
  424. if (isNaN(miseryLimit)) {
  425. miseryLimit = projectThresholdConfig ? data[projectThresholdConfig][1] : undefined;
  426. }
  427. let miserableUsers: number | undefined;
  428. if (countMiserableUserField) {
  429. const countMiserableMiseryLimit = parseInt(
  430. countMiserableUserField.split('_').pop() || '',
  431. 10
  432. );
  433. miserableUsers =
  434. countMiserableMiseryLimit === miseryLimit ||
  435. (isNaN(countMiserableMiseryLimit) && projectThresholdConfig)
  436. ? data[countMiserableUserField]
  437. : undefined;
  438. }
  439. return (
  440. <BarContainer>
  441. <UserMisery
  442. bars={10}
  443. barHeight={20}
  444. miseryLimit={miseryLimit}
  445. totalUsers={uniqueUsers}
  446. userMisery={userMisery}
  447. miserableUsers={miserableUsers}
  448. />
  449. </BarContainer>
  450. );
  451. },
  452. };
  453. /**
  454. * Get the sort field name for a given field if it is special or fallback
  455. * to the generic type formatter.
  456. */
  457. export function getSortField(
  458. field: string,
  459. tableMeta: MetaType | undefined
  460. ): string | null {
  461. if (SPECIAL_FIELDS.hasOwnProperty(field)) {
  462. return SPECIAL_FIELDS[field as keyof typeof SPECIAL_FIELDS].sortField;
  463. }
  464. if (!tableMeta) {
  465. return field;
  466. }
  467. for (const alias in AGGREGATIONS) {
  468. if (field.startsWith(alias)) {
  469. return AGGREGATIONS[alias].isSortable ? field : null;
  470. }
  471. }
  472. const fieldType = tableMeta[field];
  473. if (FIELD_FORMATTERS.hasOwnProperty(fieldType)) {
  474. return FIELD_FORMATTERS[fieldType as keyof typeof FIELD_FORMATTERS].isSortable
  475. ? field
  476. : null;
  477. }
  478. return null;
  479. }
  480. const isDurationValue = (data: EventData, field: string): boolean => {
  481. return field in data && typeof data[field] === 'number';
  482. };
  483. const spanOperationRelativeBreakdownRenderer = (
  484. data: EventData,
  485. {location, organization}: RenderFunctionBaggage
  486. ): React.ReactNode => {
  487. const cumulativeSpanOpBreakdown = data['spans.total.time'];
  488. if (
  489. !isDurationValue(data, 'spans.total.time') ||
  490. SPAN_OP_BREAKDOWN_FIELDS.every(field => !isDurationValue(data, field)) ||
  491. cumulativeSpanOpBreakdown === 0
  492. ) {
  493. return FIELD_FORMATTERS.duration.renderFunc(SPAN_OP_RELATIVE_BREAKDOWN_FIELD, data);
  494. }
  495. let otherPercentage = 1;
  496. return (
  497. <RelativeOpsBreakdown>
  498. {SPAN_OP_BREAKDOWN_FIELDS.map(field => {
  499. if (!isDurationValue(data, field)) {
  500. return null;
  501. }
  502. const operationName = getSpanOperationName(field) ?? 'op';
  503. const spanOpDuration: number = data[field];
  504. const widthPercentage = spanOpDuration / cumulativeSpanOpBreakdown;
  505. otherPercentage = otherPercentage - widthPercentage;
  506. if (widthPercentage === 0) {
  507. return null;
  508. }
  509. return (
  510. <div key={operationName} style={{width: toPercent(widthPercentage || 0)}}>
  511. <Tooltip
  512. title={
  513. <div>
  514. <div>{`${operationName} ${formatPercentage(widthPercentage, 0)}`}</div>
  515. <div>
  516. <Duration
  517. seconds={spanOpDuration / 1000}
  518. fixedDigits={2}
  519. abbreviation
  520. />
  521. </div>
  522. </div>
  523. }
  524. containerDisplayMode="block"
  525. >
  526. <RectangleRelativeOpsBreakdown
  527. spanBarHatch={false}
  528. style={{
  529. backgroundColor: pickBarColour(operationName),
  530. cursor: 'pointer',
  531. }}
  532. onClick={event => {
  533. event.stopPropagation();
  534. const filter = stringToFilter(operationName);
  535. if (filter === SpanOperationBreakdownFilter.None) {
  536. return;
  537. }
  538. trackAnalyticsEvent({
  539. eventName: 'Performance Views: Select Relative Breakdown',
  540. eventKey: 'performance_views.relative_breakdown.selection',
  541. organization_id: parseInt(organization.id, 10),
  542. action: filter as string,
  543. });
  544. browserHistory.push({
  545. pathname: location.pathname,
  546. query: {
  547. ...location.query,
  548. ...filterToLocationQuery(filter),
  549. },
  550. });
  551. }}
  552. />
  553. </Tooltip>
  554. </div>
  555. );
  556. })}
  557. <div key="other" style={{width: toPercent(otherPercentage || 0)}}>
  558. <Tooltip title={<div>{t('Other')}</div>} containerDisplayMode="block">
  559. <OtherRelativeOpsBreakdown spanBarHatch={false} />
  560. </Tooltip>
  561. </div>
  562. </RelativeOpsBreakdown>
  563. );
  564. };
  565. const RelativeOpsBreakdown = styled('div')`
  566. position: relative;
  567. display: flex;
  568. `;
  569. const RectangleRelativeOpsBreakdown = styled(RowRectangle)`
  570. position: relative;
  571. top: 0;
  572. width: 100%;
  573. `;
  574. const OtherRelativeOpsBreakdown = styled(RectangleRelativeOpsBreakdown)`
  575. background-color: ${p => p.theme.gray100};
  576. `;
  577. /**
  578. * Get the field renderer for the named field and metadata
  579. *
  580. * @param {String} field name
  581. * @param {object} metadata mapping.
  582. * @returns {Function}
  583. */
  584. export function getFieldRenderer(
  585. field: string,
  586. meta: MetaType
  587. ): FieldFormatterRenderFunctionPartial {
  588. if (SPECIAL_FIELDS.hasOwnProperty(field)) {
  589. return SPECIAL_FIELDS[field].renderFunc;
  590. }
  591. if (isRelativeSpanOperationBreakdownField(field)) {
  592. return spanOperationRelativeBreakdownRenderer;
  593. }
  594. const fieldName = getAggregateAlias(field);
  595. const fieldType = meta[fieldName];
  596. for (const alias in SPECIAL_FUNCTIONS) {
  597. if (fieldName.startsWith(alias)) {
  598. return SPECIAL_FUNCTIONS[alias];
  599. }
  600. }
  601. if (FIELD_FORMATTERS.hasOwnProperty(fieldType)) {
  602. return partial(FIELD_FORMATTERS[fieldType].renderFunc, fieldName);
  603. }
  604. return partial(FIELD_FORMATTERS.string.renderFunc, fieldName);
  605. }
  606. type FieldTypeFormatterRenderFunctionPartial = (data: EventData) => React.ReactNode;
  607. /**
  608. * Get the field renderer for the named field only based on its type from the given
  609. * metadata.
  610. *
  611. * @param {String} field name
  612. * @param {object} metadata mapping.
  613. * @returns {Function}
  614. */
  615. export function getFieldFormatter(
  616. field: string,
  617. meta: MetaType
  618. ): FieldTypeFormatterRenderFunctionPartial {
  619. const fieldName = getAggregateAlias(field);
  620. const fieldType = meta[fieldName];
  621. if (FIELD_FORMATTERS.hasOwnProperty(fieldType)) {
  622. return partial(FIELD_FORMATTERS[fieldType].renderFunc, fieldName);
  623. }
  624. return partial(FIELD_FORMATTERS.string.renderFunc, fieldName);
  625. }