fieldRenderers.tsx 15 KB

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